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
Related
/*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.
I'm creating a program to help with students solving y= m(x) + b. As of right now, I have the program to display the menu and evaluate if your response is correct to the answer. However, I need it to also count the number of correct answers in a row.
If 3 correct end program and output total correct out of attempts tried.
else if there were 3 attempts made the output a tip.
The main issue I'm having is the loop of the two (methods?). I apologize in advance if my code is atrocious, I'm having a hard time understanding methods and classes in this compared to how Python is. Anyone's suggestions or tips would be immensely helpful.
So far I've tried adding methods, and attempts at classes to certain parts of the program such as
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {}
and
public static test_input() {}
However, now I'm facing scoping problems as well as errors referencing certain variables.
package algebra_Tutor;
import java.util.Scanner;
class AlgebraTutor {
public static void main(String[] args){
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Asks for user input
System.out.print("Enter your selection: ");
}
//Creates random # for values in formula
int y_ = point_of_line_cross;
int m_ = slope;
int b_ = y_intercept;
int x_ = independent_variable;
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
//Converts user input to an integer
int selection = user_Selection.nextInt();
user_Selection.close();
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " +slope +"("+independent_variable+")"+" + "+y_intercept);
System.out.println("Input your answer: ");
}
else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = "+"("+point_of_line_cross+" - "+y_intercept+")"+" / "+independent_variable);
System.out.println("Input your answer: ");
}
else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = "+point_of_line_cross+" - "+slope+"("+independent_variable+")");
System.out.println("Input your answer: ");
}
else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
return;
}
}
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m =(y_) - ((b_) / (x_));
int answer_b =(y_) - ((m_)* (x_));
public static test_input() {
//Problem solver defined
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
//Creates loop for program
var counter = 0;
int correct = 0;
var answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y){
counter++;
correct++;
System.out.println("You answered correctly");
return;
}
else if (counter >= 3 && correct < 3) {
System.out.println("Youve been missing the questions lately, let me help! ");
}
else
{
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
}
I expect the program to output correct answers out of attempts after the user completes 3 problems in a row. In addition, it needs to output a tip after 3 attempts. And then after 3 correct, it should loop back to the beginning of program.
well I figured I would let you figure out how to make it loop on your own but I solved your other problems and put comments where I changed things. Hope this helps
//declared variables here. global variables must be declared static when accessed in a static method (ex: user_input())
static int y_;
static int m_;
static int b_;
static int x_;
public static void main(String[] args) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Converts user input to an integer
int selection = user_Selection.nextInt();
//call user_input()
user_input(selection);
}
public static void user_input(int selection) {
Scanner user_Selection = new Scanner(System.in);
int userAnswer;
int y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
int slope = (int) Math.floor(Math.random() * 201) - 100;
int point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
int independent_variable = (int) Math.floor(Math.random() * 201) - 100;
y_ = point_of_line_cross;
m_ = slope;
b_ = y_intercept;
x_ = independent_variable;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " + slope + "(" + independent_variable + ")" + " + " + y_intercept);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = " + "(" + point_of_line_cross + " - " + y_intercept + ")" + " / " + independent_variable);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = " + point_of_line_cross + " - " + slope + "(" + independent_variable + ")");
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
}
}
// you forgot to include return type ex: void, int, String, double, float, etc
public static void test_input(int entered_answer) {
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m = (y_) - ((b_) / (x_));
int answer_b = (y_) - ((m_) * (x_));
//Problem solver defined
int answer = entered_answer;
//Creates loop for program
int counter = 0;
int correct = 0;
boolean answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y) {
counter++;
correct++;
System.out.println("You answered correctly");
return;
} else if (counter >= 3 && correct < 3) {
System.out.println("You've been missing the questions lately, let me help! ");
} else {
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
`
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable)
If you give a method parameters, then when the method is called you will have to enter the values into the parameter yourself. I don't think this is what you intended because you defined what you wanted those parameter values to be here:
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
In your test_input() method you wrote:
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
.nextInt() will make the program halt and wait for user input so you don't want to use it until you are ready to get the input.
I don't really know much about the var keyword in java but rather than using var I figured you should just declare the variable type so from this:
var counter = 0;
to this:
int counter = 0;
and to get a better understanding on how methods work I recommend these two videos:
Intro to java methods
Java method parameters and return types
For an in depth explanation of the fundamentals of java in general then I recommend this whole playlist
Java Beginner Programming
It's quite late on a saturday for me to do algebra, so I will stick to suggesting changes to the structure of your program. First, you can accomplish everything with a single class to contain the questions, and score for the user. The methods in that class can be chosen via a menu in the main.
I wrote a sample of how I would structure this based on standard Java OOP methodology. In my program, the main needs no static class, it loops a menu, and the choice of a question is made there. My methods hava single question, you can add as many as you like in the menu, the important thing is the structure.
import java.util.Scanner;
//This class contains the two methods and over-all score
class Material {
private int score;
//The user chooses this or the earth method
public void sky() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
//within the method, is this while loop which gives a hint after 3 attempts.
while (!answer.equals("blue") && (!answer.equals("exit"))) {
System.out.println("What color is the sky? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'b'");
}
if (answer.equals("blue"))
score += 1;//The score will increment if the choice is correct,
else//or else leave with nothing...
return;
}
//This method is the same as the sky() method, just different question and answer.
public void earth() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
while (!answer.equals("iron") && (!answer.equals("exit"))) {
System.out.println("What is the core made of? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'i'");
}
if (answer.equals("iron"))
score += 1;
else
return;
}
public int getScore() {
return score;
}
}
public class Questions {
public static void main(String[] args) {
//No static methods needed, here is an instance of our test materia class.
Material material = new Material();
//The choice and scanner are instantiated here.
int choice = 0;
Scanner input = new Scanner(System.in);
//This while loop uses a switch statement to choose the methods for the questions
while (choice != 3) {
if (material.getScore() == 3) {
System.out.println("Good job, you scored three right.");
return;
}
System.out.println("SCORE: " + material.getScore());
System.out.println("Anwer questions about the sky: 1");
System.out.println("Answer quetions about the earth: 2");
System.out.println("Exit: 3");
choice = input.nextInt();
//choices are 1 , 2 for questions, and 3 to leave.
switch (choice) {
case 1:
material.sky();
break;
case 2:
material.earth();
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("not a valid number choice...");
}
}
}// main
}// class
Side note: instead of asking the user for 1, 2, 3 or 4, you should directly ask them to enter the variable they want to solve:
Solve the equation y = m * x + b for which variable (y, m, b, quit)?
This makes the users of the program think more in the problem domain instead of some technically useless indirection.
As you have a Python background you should know that the indentation of the lines is important and has meaning. It's the same for Java programs. The only difference is that the Java compiler ignores the indentation completely. But Java programs are also read by humans, and for them the indentation is viable for understanding the structure of the program. The code you posted has inconsistent indentation, and you should let your IDE fix that.
Your program should be structured like this:
public class AlgebraTutor {
private final Scanner in = new Scanner(System.in);
private final PrintStream out = System.out;
private int attempts = 0;
void solveForY() {
...
}
void solveForM() {
...
}
void solveForB() {
...
}
void mainMenu() {
while (true) {
out.println("Solve the equation y = m * x + b for which variable (y, m, b), or quit?");
if (!in.hasNextLine()) {
return;
}
switch (in.nextLine()) {
case "y":
solveForY();
break;
case "m":
solveForX();
break;
case "b":
solveForB();
break;
case "q":
case "quit":
return;
}
}
}
public static void main(String[] args) {
new AlgebraTutor().mainLoop();
}
}
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);
}
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.
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"
}