Java Logic Issue in askQuestion() method - java

I'm trying to create a Java math training program. I have a working version in Javascript and some of you guys have already helped me convert it over to Java. It's supposed to ask the user a difficulty (which then uses that amount of digits for each number in the questions). It then asks the user what type of math to do (addition, subtraction, multiplication, division, random). It then asks the user 10 questions. As the user answers, it tells them if they're right or wrong. If wrong, they get to continue attempting the question. At the end of 10 questions, it calculates if you got over 75% of them right and displays an appropriate response. Full instructions:
I finally got most of it working correctly, only to find out that the math itself is wrong.
Sometimes if I enter a difficulty of 2, it only gives 1 digit (it basically doesn't calculate the difficulty right). Also, it always tells me my math is wrong. Is there any chance you guys can spot anything wrong with the logic?
Thanks for any help.
import java.util.*;
import javax.swing.JOptionPane;
public class Assignment2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int difficulty = 1;
String[] operators = {"plus", "minus", "times", "divided by"};
int selectedOperator = 1;
int correctAnswers = 0;
int answeredTyped = 0;
int difficultyInput = Integer.parseInt(
JOptionPane.showInputDialog(
"Please choose the difficulty. " +
"Enter the number of digits to use in each problem."));
if (difficultyInput > 0) {
difficulty = difficultyInput;
}
int arithmeticMethod = Integer.parseInt(
JOptionPane.showInputDialog(
"Choose an arithmetic problem to study: " +
"1 = Addition Only, 2 = Subtraction Only, " +
"3 = Multiplication Only, 4 = Division Only, " +
"5 = Random Problems" ));
selectedOperator = arithmeticMethod;
new Assignment2().askQuestion(
difficulty, null, arithmeticMethod,
arithmeticMethod, operators, arithmeticMethod);
}
public static boolean checkResponse (
int primaryInt, int secondaryInt,
String operatorText, float response){
boolean result = false;
switch (operatorText) {
case "1":
return (primaryInt + secondaryInt) == response;
case "2":
return (primaryInt - secondaryInt) == response;
case "3":
return (primaryInt * secondaryInt) == response;
case "4":
return (primaryInt / secondaryInt) == response;
}
return false;
}
public static String displayResponse (boolean isCorrect) {
int randomIndex = (int) (Math.floor(Math.random() * (4 - 1 + 1)) + 1);
switch (randomIndex) {
case 1:
return isCorrect ? "Very Good!" : "No. Please try again.";
case 2:
return isCorrect ? "Excellent!" : "Wrong. Try once more.";
case 3:
return isCorrect ? "Nice Work!" : "Don\'t give up!";
case 4:
return isCorrect ? "Keep up the good work!" : "No. Keep trying.";
}
return "Oops...";
}
public static void askQuestion(
int difficulty, String operatorText,
int selectedOperator, int answeredTyped,
String[] operators, int correctAnswers) {
boolean correctAnswer = false;
int primaryInt = (int) Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
int secondaryInt = (int) Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
operatorText = (selectedOperator == 5) ? operators[(int) Math.floor(Math.random() * operators.length)] : operators[selectedOperator - 1];
while(!correctAnswer && answeredTyped < 10) {
float response = Float.parseFloat (JOptionPane.showInputDialog("How much is " + primaryInt + " " + operatorText + " " + secondaryInt + "?"));
correctAnswer = checkResponse (primaryInt, secondaryInt, operatorText, response);
JOptionPane.showMessageDialog(null, displayResponse(correctAnswer));
answeredTyped++;
if(correctAnswer)
correctAnswers++;
}
{
while(answeredTyped < 10) {
askQuestion(0, null, 0, 0, null, 0);
}
if((correctAnswers / answeredTyped) >= 0.75) {
JOptionPane.showMessageDialog(
null, "Congratulations, you are ready to " +
"go on to the next level!");
} else {
JOptionPane.showMessageDialog(
null, "Please ask your teacher for extra help.");
}
}
}
}

In you code where you are calling askQuestion you have done
new Assignment2().askQuestion(arithmeticMethod, null, arithmeticMethod, arithmeticMethod, operators, arithmeticMethod);
}
But looking at your method definition it should be, you are passing arthmeticMethod instead of difficulty level
new Assignment2().askQuestion(difficulty, null, arithmeticMethod, arithmeticMethod, operators, arithmeticMethod);
}

Related

How do I get the numberOfQuestions variable to reset back to Zero after the loop completes?

/*Class MentalMathProgram
Michael
11/18/2020
This program is designed to present the user with randomly generated numbers
and it gets progressively harder for every question correct.
/
import java.util.;
public class mentalMathProgram {
static double ranNum(int min, int max){
Random ran = new Random();
double ranNum = min + (int)(Math.random() * ((max- - min)+ 1));
return (double)ranNum;
}
static byte mathType(int min, int max){
Random ran = new Random();
int mathType = min + (int)(Math.random() * ((max- - min)+ 1));
return (byte) mathType;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int restart = 0;
int correctAnswers = 0,incorrectAnswers = 0;
int numberOfQuestions = 0;
byte mathType = 0;
char again;
again = 'Y';
while(again == 'Y') {
do{
int questionCounter = 0;
System.out.println(" \n\nWelcome to your mental math assistance program! There will"
+ "\n be varying levels of difficulty as you progress through the questions"
+ "\n or when you select the difficulty preset. "
+ "\n\n Please select a difficulty below!");
System.out.println("\n 1. Easy"
+ "\n 2. Normal"
+ "\n 3. Medium"
+ "\n 4. Hard");
byte difficultyChoice = input.nextByte();
switch(difficultyChoice){
case 1: {
System.out.println("How many Questions do you want to do?");
numberOfQuestions = input.nextInt();
do {
byte randomOperationMin = 1;
byte randomOperationMax = 4;
byte operationValue = mathType(randomOperationMin,randomOperationMax);
mathType = operationValue;
switch(mathType) {
case 1: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
int result1=(int) ranNum(easyMin,easyMax);
int result2=(int) ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "+" +result2+ "=");
int userAnswer = input.nextInt();
int answer = result1 + result2;
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
case 2: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
int result1=(int) ranNum(easyMin,easyMax);
int result2=(int) ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "-" +result2+ "=");
int userAnswer = input.nextInt();
int answer = result1 - result2;
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
case 3: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
int result1=(int) ranNum(easyMin,easyMax);
int result2=(int) ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "*" +result2+ "=");
int userAnswer = input.nextInt();
int answer = result1 * result2;
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
case 4: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
double result1=ranNum(easyMin,easyMax);
double result2=ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "/" +result2+ "=");
double userAnswer = input.nextDouble();
double answer = result1 / result2;
double remainder = result1 % result2;
System.out.println("The Remainder is "+remainder);
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
}
}while(questionCounter != numberOfQuestions);
break;
//I need to figure out a way to loop this code over and over instead of it just breaking out. I also need to
// make it so that the user can exit the program whenever they want
}
}
}while(restart==0);//condition for the do while death/restart loop
System.out.println("\nPlay Again? Y OR N: ");
//println statement, asking if user would like to play again.
System.out.println("Questions Correct: "+correctAnswers+"");
again = input.nextLine().charAt(0);
// set variable again to value assigned from user input
}
}
}
This is my code but I'm very new to coding. Im just trying to reset the variable that controls the amount of questions presented to the user to reset at the end of each loop. So far I'm unable to figure out what I'm doing wrong
There are a number of issues with your code that makes it difficult to trace / debug.
If I understand correctly, your outer doWhile is supposed to run indefinitely until user chooses to terminate the program.
The second doWhile is controlling the number of questions that are being asked in any single, complete round of the game.
Firstly, bring the 'numberOfQuestions' variable to be within the scope of the outer loop.
Secondly, you can simply declare a boolean variable to control whether the user wants to continue playing the game or to terminate the program.
Lastly, for each of the switch cases, you can simply do questionCounter++, instead of summing the correct and incorrect answers.
boolean keepGoing = true;
do {
int numberOfQuestions = 0;
int questionCounter = 0;
System.out.println("How many questions?");
numberOfQuestions = sc.nextInt();
do {
// ask questions repeatedly
// for each case, questionCounter++
} while (questionCounter != numberOfQuestions);
System.out.println("Enter '0' to continue");
if (input.nextInt() != 0) {
keepGoing = false;
}
} while (keepGoing);
It is also good practice to make sure your lines are indented properly, so that you are able to see what codes belong in which block for better maintainability and debugging.

please check my Java homework, dialog boxes and variable type mismatches

The title says this is homework, I have been beating my head into the wall for hours, so please help. It works fine, at least the math part does, I work the conversion it worked just fine. I went to change the output dialog box to list what the ending unit was, instead of just listing the variable e.g. your lbs is the end. And not to allow negative starting weights.
Now I can't get the dialog box to not give me an error. (Lines 145 -148) I put in a sample dialog box using the Return option that doesn't work, but if I set it to a variable in my case test, it will work fine. He gave us starting code, I recopied his original code and that doesn't work. The next error I get is I wrote a method that takes two doubles and a char. When I call the function I pass it two doubles and a char it says it can't convert a string (Line 255).
This has been frustrating I over engineered this and now to have it not work is killing me. I don't understand how I can copy his original code in and it no longer works. Dialog boxes confuse me but I think I understand them.
return JOptionPane.showConfirmDialog(A)(null(B), display(C),0,1);
A is the call of the for the box what type
B is the object type my understanding its always call
C is the string, text message of the box
The last two got to do with the the icon and button displayed.
He got us started on eclipse, which said I had error in code where there none, I spent hours looking at them, they went away once I reloaded my code.
Please any thing would be helpful, but an example or corrected code (I know that is a lot) with explanations on why there are correct would be helpful. My husband knows java but not dialog boxes, so he can't help. And the method call looks right to both of us.
/*
* Uses: methods, dialog boxes, and a menu to convert weights
*
*/
import javax.swing.JOptionPane;
public class WeightCon {
char choices, choicee;
public static char menu() {
char choice;
int typeNum = 3;
boolean OK;
String prompt, results, title;
prompt = "Choose Starting Unit\n";
prompt += "A. Pounds\n";
prompt += "B. Kilograms\n";
prompt += "C. Stones\n";
prompt += "D. ounces\n";
prompt += "E. Netons\n";
prompt += "F.Grams\n";
prompt += "\n\nEnter the letter of your choice:";
title = "Weights";
do {
results = JOptionPane.showInputDialog(null,prompt,title, typeNum);
choice = results.toUpperCase().charAt(0);
if(choice >= 'A' && choice <= 'F') {
OK = true;
}
else {
OK = false;
title = "Not Valid Input!";
typeNum = 0;
}
}while(! OK);
return choice;
}
public static double LbstoKG(double k) {
return k * 0.453592;
}
public static double KtoLBS(double L) {
return L / 0.453592;
}
public static double LbstoStone(double S) {
return S / 14;
}
public static double LBStoOunce(double O) {
return O / .0625;
}
public static double LbstoNewton(double N) {
return N * 4.4482216282509;
}
public static double LBStoGarm(double G) {
return G / 0.00220462 ;
}
public static double KtoL(double L) {
return L / 0.453592;
}
public static double stoneToLbs(double L) {
return L * 14;
}
public static double ounceToLBS(double L) {
return L * .0625;
}
public static double NewtonToLBS(double L) {
return L / 4.4482216282509;
}
public static double GramtoLBS(double L) {
return L * 0.00220462 ;
}
//public static double
public static double getDouble(String prompt) {
boolean OK;
double val=0;
String temp, title = "Enter a double value";
int typeNum = 3;
do {
OK = true;
temp = JOptionPane.showInputDialog(null, prompt, title, typeNum);
try {
val = Double.parseDouble(temp);
}
catch(Exception e) {
OK = false;
title = "Error! Invalid input. Must be a double value";
typeNum = 0;
}
try {
val = Double.parseDouble(temp);
}
catch(Exception b) {
if( val < 0) {
title = "Error! Invalid input. Must be a positive double value";
typeNum = 0;
}
}while(! OK);
}while(! OK);
return val;
}
public static String outputResults(double start, double end, char choices){
int test;
String end1;
if(choices == 'A') {
end1 = "Your end weight is the following pounds: ";
} else if (choices == 'B') {
end1 = " Your end weight is the following kilograms: ";
} else if (choices == 'C') {
end1 = " Your end weight is the following stones: ";
} else if (choices == 'D') {
end1 = " Your end weight is the following ounces: ";
} else if (choices == 'E') {
end1 = " Your end weight is the following newtons: ";
} else if (choices == 'F') {
end1 = " Your end weight is the following grams: ";
} else {end1 = " ERROR ERROR UNDEFINDED ERROR PLEASE CONSOLT DOCUMENTATION";}
String endreal = String.valueOf(end);
String display = "" + end1 + endreal;
//int input =
test = JOptionPane.showConfirmDialog(null, display,0,1);
test = JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1);
}
//display += "Do again?";
//return JOptionPane.showConfirmDialog(null,"test",0,1);
//return JOptionPane.showConfirmDialog(null,display,0,1);}}
//return JOptionPane.showConfirmDialog(null, "test",0,1);}}
//}
//
public static void main(String[] args) {
double get;
double lbs=0,ounce=0,kgs=0, stone=0,newton=0,gram=0 ;
double temp,start, end;
char choice, choices;
int button;
//String end1;
start =-99;
end = -999;
get = 0;
temp = 0;
do {
choice = menu();
choices = choice;
switch(choice) {
case 'A':
get = getDouble("Enter pounds : ");
lbs = get;
start = get; //LbstoKG(get);
temp = kgs;
break;
case 'B':
get = getDouble("Enter kilograms : ");
kgs = get;
start = KtoL(get);
temp = lbs;
break;
case 'C':
get = getDouble("Enter Stones : ");
stone = get;
start = stoneToLbs(get);
temp = lbs;
break;
case 'D':
ounce = getDouble("Enter Ounces : ");
start = ounceToLBS(get);
temp = lbs;
break;
case 'E':
get= getDouble("Enter Newtons : ");
newton = get;
start = NewtonToLBS(get);
temp = lbs;
break;
case 'F':
get = getDouble("Enter grams : ");
gram = get;
start = GramtoLBS(get);
temp = lbs;
break;
}
//button = outputResults(get,get);
//} while(button == 0);
// do {
choice = menu();
switch(choice) {
case 'A':
//get = getDouble("Enter pounds : ");
//lbs = getDouble("Enter pounds : ");
//kgs = get;
end = start;
break;
case 'B':
//get = getDouble("Enter kilograms : ");
end = LbstoKG(start);
break;
case 'C':
//get = getDouble("Enter Stones : ");
//stone = get;
end = LbstoStone(start);
break;
case 'D':
//ounce = getDouble("Enter Ounces : ");
end = LBStoOunce(start);
break;
case 'E':
//get= getDouble("Enter Newtons : ");
end = LbstoNewton(start);
System.out.printf("Hello");
break;
case 'F':
//get = getDouble("Enter grams : ");
end = LBStoGarm(start);
break;
}
button = outputResults(end,start,choice);
} while(button == 0);
}}
After copying and pasting your code into my compiler, there were multiple errors.
First Mistake in outputResults(): Remove the 0, and the 1.
The method showConfirmDialog(Component, Object, String, int) in the type JOptionPane
is not applicable for the arguments (null, String, int, int)
Line:
test = JOptionPane.showConfirmDialog(null, display,0,1);
Correction:
test = JOptionPane.showConfirmDialog(null, display);
Second and Third Mistake also in outputResults(): You cannot return two objects. Also, your method returns a String.
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1); // 0, 1 again.
// The second return statement is dead code, and this also makes the first mistake again
Your method returns a String.
JOptionPane.showConfirmDialog(null, display); returns an int.
So in your method returning a String, if you return an int instead, it will be a compiler error. For example:
... String outputResults(...){
return JOptionPane.showConfirmDialog(null, display);
}
1 quick fix: change return type to int (method: String outputResults(double, double, char))
Fourth Mistake in main(): Fix your Third Mistake and ignore this fix.
int button = ...;
...
button = outputResults(end,start,choice); // Returns String, but button is an int
// Change button to a string?
// Integer.parseInt(outputResults(end,start,choice)); ?

How to pass value from one method into main method?

I'm creating a math program that asks the user how many digits they'd like to use, then asks them what kind of math they want to do. It then asks the user 10 math questions based on their answers. It then decides if they're right or wrong and displays an appropriate message. It then calculates their percentage of correct answers and displays a message based on the percentage.
The problem is that the program never stops after 10 questions and never calculates the percentage or displays the final message. I believe this is at least partially occurring because I'm not passing the new "answeredTyped" value from the "askQuestion" method. Can someone explain how I can easily pass this new value back to the main method so that it'll stop at 10? Or perhaps tell me what else is keeping this from working correctly?
I've asked quite a few questions about this program already, so I appreciate everyone's patience with me learning Java and having very little knowledge of the language.
Thank you for any help! (also I apologize for any bad formatting here! After changing about a million things, it got ugly)
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Assignment2 {
public static int answeredTyped = 0;
public static int correctAnswers = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int difficulty = 1;
String[] operators = { "plus", "minus", "times", "divided by" };
int selectedOperator = 1;
int difficultyInput = Integer
.parseInt(JOptionPane
.showInputDialog("Please choose the difficulty. Enter the number of digits to use in each problem."));
if (difficultyInput > 0) {
difficulty = difficultyInput;
}
int arithmeticMethod = Integer
.parseInt(JOptionPane
.showInputDialog("Choose an arithmetic problem to study: 1 = Addition Only, 2 = Subtraction Only, 3 = Multiplication Only, 4 = Division Only, 5 = Random Problems"));
selectedOperator = arithmeticMethod;
new Assignment2().askQuestion(difficulty, null, selectedOperator,
answeredTyped, operators, correctAnswers);
while (answeredTyped < 10) {
askQuestion(difficulty, null, selectedOperator, answeredTyped,
operators, correctAnswers);
answeredTyped++;
if (answeredTyped>= 10) {
if (((float) correctAnswers / answeredTyped) >= 0.75) {
JOptionPane
.showMessageDialog(null,
"Congratulations, you are ready to go on to the next level!");
} else {
JOptionPane.showMessageDialog(null,
"Please ask your teacher for extra help.");
}
}
}
}
public static boolean checkResponse(double primaryInt, double secondaryInt,
String operatorText, double response) {
if (operatorText.equals("plus")) {
return (primaryInt + secondaryInt) == response;
} else if (operatorText.equals("minus")) {
return (primaryInt - secondaryInt) == response;
} else if (operatorText.equals("times")) {
return (primaryInt * secondaryInt) == response;
} else if (operatorText.equals("divided by")) {
return (primaryInt / secondaryInt) == response;
}
return false;
}
public static String displayResponse(boolean isCorrect) {
int randomIndex = (int) (Math.floor(Math.random() * (4 - 1 + 1)) + 1);
switch (randomIndex) {
case 1:
return isCorrect ? "Very Good!" : "No. Please try again.";
case 2:
return isCorrect ? "Excellent!" : "Wrong. Try once more.";
case 3:
return isCorrect ? "Nice Work!" : "Don\'t give up!";
case 4:
return isCorrect ? "Keep up the good work!" : "No. Keep trying.";
}
return "Oops...";
}
public static void askQuestion(int difficulty, String operatorText,
int selectedOperator, int answeredTyped, String[] operators,
int correctAnswers) {
boolean correctAnswer = false;
double primaryInt = Math.floor(Math.pow(10, difficulty - 1)
+ Math.random() * 9 * Math.pow(10, difficulty - 1));
double secondaryInt = Math.floor(Math.pow(10, difficulty - 1)
+ Math.random() * 9 * Math.pow(10, difficulty - 1));
operatorText = (selectedOperator == 5) ? operators[(int) Math
.floor(Math.random() * operators.length)]
: operators[selectedOperator - 1];
double response = Double.parseDouble(JOptionPane
.showInputDialog("How much is " + primaryInt + " "
+ operatorText + " " + secondaryInt + "?"));
correctAnswer = checkResponse(primaryInt, secondaryInt,
operatorText, response);
JOptionPane.showMessageDialog(null, displayResponse(correctAnswer));
if (correctAnswer)
correctAnswers++;
}
}
You have two while loops, so it will call askQuestion() ten times, and then there is askQuestion's own while loop:
main()
while (answeredTyped < 10) {
askQuestion()
while (!correctAnswer && answeredTyped < 10) {
Try using only a single while loop, and putting the evaluation of the answers in total outside of the askQuestion() method
You have to increment answeredType in the while loop of the main method,not within another method,since you have not declared the variable as global

Trying to translate Javascript to Java - help fix?

I'm trying to learn Java, but I'm struggling a little bit. I'm trying to do an assignment from a textbook, so I did it in javascript and was using my limited knowledge of Java to convert it over. (Here's the original instructions - http://i518.photobucket.com/albums/u341/ACrippledFerret/5ea8ec0e-02aa-4b96-b207-a83c52f8db48_zps2cd2ab7f.jpg)
I think I've got most of it correct, but I'm running into a couple of errors. Almost all of it is "(variable) cannot be resolved to a variable". It happens to lots of variables in my last method. I also seem to have an issue with a bracket somewhere... "Syntax error on token "}", { expected after this token".
If anyone can help fix this code, I would be very grateful. I am new to Java so this is a bit tough for me to translate. The first set of code is the javascript, the second set of code is my translated java (That's not working). Thanks for any help.
JAVASCRIPT
window.onload=function(){
var difficulty = 1,
operators = ['plus', 'minus', 'times', 'divided by'],
selectedOperator = 1,
correctAnswers = 0,
answeredTyped = 0;
var difficultyInput = parseInt(prompt('Please choose the difficulty. Enter the number of digits to use in each problem.'), 10);
if(difficultyInput > 0) {
difficulty = difficultyInput;
}
var arithmeticMethod = parseInt(prompt('Choose an arithmetic problem to study:\n1 = Addition Only\n2 = Subtraction Only\n3 = Multiplication Only\n4 = Division Only\n5 = Random Problems'), 10);
if(arithmeticMethod == 5 || operators[arithmeticMethod - 1]) {
selectedOperator = arithmeticMethod;
}
function checkResponse(primaryInt, secondaryInt, operatorText, suggestedAnswer) {
var result = false;
switch (operatorText) {
case 'plus':
return (primaryInt + secondaryInt) == suggestedAnswer;
case 'minus':
return (primaryInt - secondaryInt) == suggestedAnswer;
case 'times':
return (primaryInt * secondaryInt) == suggestedAnswer;
case 'divided by':
return (primaryInt / secondaryInt) == suggestedAnswer;
default:
return false;
}
}
function displayResponse(isCorrect) {
var randomIndex = Math.floor(Math.random() * (4 - 1 + 1)) + 1;
switch (randomIndex) {
case 1:
return isCorrect ? 'Very good!' : 'No. Please try again.';
case 2:
return isCorrect ? 'Excellent!' : 'Wrong. Try once more.';
case 3:
return isCorrect ? 'Nice Work!' : 'Don\'t give up!';
case 4:
return isCorrect ? 'Keep up the good work!' : 'No. Keep trying.';
default:
return 'Woops...';
}
}
function askQuestion() {
var correctAnswer = false;
var primaryInt = Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
secondaryInt = Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
operatorText = (selectedOperator == 5) ? operators[Math.floor(Math.random() * operators.length)] : operators[selectedOperator - 1];
while(!correctAnswer && answeredTyped < 10) {
var response = parseFloat(prompt('How much is ' + primaryInt + ' ' + operatorText + ' ' + secondaryInt + '?'));
correctAnswer = checkResponse(primaryInt, secondaryInt, operatorText, response);
alert(displayResponse(correctAnswer));
answeredTyped++;
if(correctAnswer)
correctAnswers++;
}
}
while(answeredTyped < 10) {
askQuestion();
}
if((correctAnswers / answeredTyped) >= 0.75) {
alert('Congratulations, you are ready to go on the next level!');
} else {
alert('Please ask your teacher for extra help.');
}
}
JAVA
import java.util.*;
import javax.swing.JOptionPane;
/**
*
*/
/**
* #author Tyler
*
*/
public class Assignment2 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int difficulty = 1;
String[] operators = {"plus", "minus", "times", "divided by"};
int selectedOperator = 1;
int correctAnswers = 0;
int answeredTyped = 0;
int difficultyInput = Integer.parseInt(JOptionPane.showInputDialog("Please choose the difficulty. Enter the number of digits to use in each problem."));
if (difficultyInput > 0) {
difficulty = difficultyInput;
}
int arithmeticMethod = Integer.parseInt(JOptionPane.showInputDialog("Choose an arithmetic problem to study: 1 = Addition Only, 2 = Subtraction Only, 3 = Multiplication Only, 4 = Division Only, 5 = Random Problems" ));
selectedOperator = arithmeticMethod;
}
public static boolean checkResponse (double primaryInt, double secondaryInt, String operatorText, float response){
boolean result = false;
switch (operatorText){
case "1":
return (primaryInt + secondaryInt) == response;
case "2":
return (primaryInt - secondaryInt) == response;
case "3":
return (primaryInt * secondaryInt) == response;
case "4":
return (primaryInt / secondaryInt) == response;
}
return false;
}
public static String displayResponse (boolean isCorrect){
int randomIndex = (int) (Math.floor(Math.random() * (4 - 1 + 1)) + 1);
switch (randomIndex){
case 1:
return isCorrect ? "Very Good!" : "No. Please try again.";
case 2:
return isCorrect ? "Excellent!" : "Wrong. Try once more.";
case 3:
return isCorrect ? "Nice Work!" : "Don\'t give up!";
case 4:
return isCorrect ? "Keep up the good work!" : "No. Keep trying.";
}
return "Oops...";
}
public static void askQuestion(int difficulty, String operatorText, int selectedOperator, int answeredTyped, String[] operators, int correctAnswers){
boolean correctAnswer = false;
double primaryInt = Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
double secondaryInt = Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
operatorText = (selectedOperator == 5) ? operators[(int) Math.floor(Math.random() * operators.length)] : operators[selectedOperator - 1];
while(!correctAnswer && answeredTyped < 10) {
float response = Float.parseFloat (JOptionPane.showInputDialog("How much is " + primaryInt + " " + operatorText + " " + secondaryInt + "?"));
correctAnswer = checkResponse (primaryInt, secondaryInt, operatorText, response);
JOptionPane.showMessageDialog(null, displayResponse(correctAnswer));
answeredTyped++;
if(correctAnswer)
correctAnswers++;
}
{
while(answeredTyped < 10){
askQuestion(0, null, 0, 0, null, 0);
}
if((correctAnswers / answeredTyped) >= 0.75) {
JOptionPane.showMessageDialog(null, "Congratulations, you are ready to go on to the next level!");
}
else{
JOptionPane.showMessageDialog(null, "Please ask your teacher for extra help.");
}
}
}
}
The scoping is different in Java than in Javascript; Java variables defined in a method (static or instance) will be valid only within that method, so you can't reference variables such as difficulty (defined in main()) from other methods such as askQuestion(). You could make them static class member variables, but that's generally bad practice in Java (and also in Javascript, really), so the better option is to pass them into methods such as askQuestion() as arguments to the method.

How to assign a random number a string value in my program

as the title suggests I am doing a program for homework that is a slot machine. I have searched around and I am pretty satisfied that the program works correctly enough for me. The problem Im having is on top of generating the random numbers, I am supposed to assign values for the numbers 1-5 (Cherries, Oranges, Plums, Bells, Melons, Bars). Then I am to display the output instead of the number when my program runs. Can anyone get me pointed in the right direction on how to do this please?
import java.util.Random;
import java.util.Scanner;
public class SlotMachineClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Coins = 1000;
int Wager = 0;
System.out.println("Steve's Slot Machine");
System.out.println("You have " + Coins + " coins.");
System.out.println("Enter your bet and press Enter to play");
while (Coins > 0)
{
int first = new Random().nextInt(5)+1;
int second = new Random().nextInt(5)+1;
int third = new Random().nextInt(5)+1;
Wager = input.nextInt();
if(Wager > Coins)
Wager = Coins;
System.out.println(first + " " + second + " " + third);
if(first == second && second == third)
{ Coins = Coins + (Wager * 3);
System.out.println("You won " + (Wager * 3) + "!!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else if((first == second && first != third) || (first != second && first == third) || (first != second && second == third))
{ Coins = Coins + (Wager * 2);
System.out.println("You won " + (Wager * 2) + "!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else {Coins = Coins - Wager;
System.out.println("You Lost!" + "\nPlay Again? if so Enter your bet.");}
}
while (Wager == 0)
{
System.out.println("You ran out of coins. Thanks for playing.");
}
}
}
If you have an int and want to have some String associated with that, there are a couple of ways to do that.
The first one is to have an array of Strings and look them up.
public static String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
public String getNameForReel(int reelValue) {
return text[reelValue];
}
// And to call it...
System.out.println(getNameForReel(first)); //etc...
Or, you can do it in a switch statement (I don't prefer this, but you might):
public String getNameForReel(int reelValue) {
switch(reelValue) {
case 0: return "Cherry";
case 1: return "Bell";
case 2: return "Lemon";
case 3: return "Bar";
case 4: return "Seven";
}
}
You need a lookup table:
String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
Then you can just do
System.out.println(text[first] + " " + text[second] + " " + text[third]);
without creating more methods.
The non-array solution most likely to be used a by new programmer in an intro course would be a nested if-else:
String fruitToPrint = "";
if (num == 0)
fruitToPrint = "Cherries";
else if (num == 1)
fruitToPrint = "Oranges";
else if (num == 2)
fruitToPrint = "Plums";
else if (num == 3)
fruitToPrint = "Bells";
else if (num == 4)
fruitToPrint = "Melons";
else if (num == 5)
fruitToPrint = "Bars";
else
System.out.println("Couldn't assign fruit from num=" + num);
System.out.println("The corresponding fruit was " + fruitToPrint);
Create an array:
String[] s = {Cherries, Oranges, Plums, Bells, Melons, Bars};
Then you can print s[num-1] instead of num (where num is the random int). E.g. if your random int came out to be 2, print s[2-1] i.e. s[1] which will be Orange.
Here's an alternative solution to the question which I think follows best programming practices. This is probably even less allowed for your assignment than an array, and will be a dead giveaway that you got your answer on StackOverflow, but the problem would lend itself to using an enum type with an int->enum mapping:
enum Fruit {
Cherries(1),
Oranges(2),
Plums(3),
Melons(4),
Bars(5);
private static final Map<Integer, Fruit> lookupMap = new HashMap<Integer, Fruit>();
static {
for (Fruit fruit : Fruit.values()) {
lookupMap.put(fruit.getLookup());
}
}
static Fruit fromLookup(int lookup) {
return lookupMap.get(lookup);
}
private final int lookup;
private Fruit(int lookup) {
this.lookup = lookup;
}
int getLookup() {
return lookup;
}
}
void printEnumExample() {
int fruitToPrint = 4;
System.out.println(Fruit.fromLookup(fruitToPrint)); // <- This will print "Melons"
}

Categories