Convert this C++ to JavaScript and run in browser.
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <iostream>
using namespace std;
/*
*
*/
class Dice{
private:
static const int MAXDICE=6;
static const int MINDICE=1;
int faceVal;
public:
Dice(int);
void setFace(int);
int getFace();
string toString();
};
Dice::Dice(int faceVal)
{
if(faceVal<MINDICE&&faceVal>MAXDICE)
{
setFace(1);
}
else
{
this->faceVal=faceVal;
}
}
void Dice::setFace(int faceVal)
{
this->faceVal=faceVal;
}
int Dice::getFace()
{
return faceVal;
}
string Dice::toString()
{
stringstream ss;
ss<<faceVal;
string str="face value is ";
str+=ss.str();
return str;
}
int main(int argc, char** argv) {
srand((unsigned)time(NULL));
Dice dice((rand()%(6))+1);
cout<<dice.toString()<<endl;
return 0;
}
class Dice {
constructor(faceVal) {
let MAXDICE = 6;
let MINDICE = 1;
this.faceVal = 0;
if (faceVal < MINDICE && faceVal > MAXDICE) {
setFace(1);
} else {
this.faceVal = faceVal;
}
}
setFace(faceVal) {
this.faceVal = faceVal;
}
getFace() {
return faceVal;
}
toString() {
let str = "face value is ";
str += this.faceVal
return str;
}
}
let num = Math.floor(Math.random() * 6) + 1;
dice = new Dice(num);
console.log(dice.toString());
Output: (can be run online at jsfiddle.net )
Get Answers For Free
Most questions answered within 1 hours.