About while loops and if statements nested - java

I'm working on this project challenge called "Algebra Tutor" for my very first java class.
The program should be able to output a question to decide whether you want to solver for m or b or y in the formula y = mx + b.
Once one of those is pick by a number: "Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. "
It should give you an output to solve the formula.
I'm working in part 3 of the project which is:
Update your program so that each problem type mode will repeatedly ask questions until the user gets 3 correct answers in a row.
If the attempts more than 3 questions in a particular mode, the program should provide a hint on how to solve problems of this type.
After the student has correctly answered 3 questions in a row, an overall score (the number of questions answered correctly divided by the total number of questions attempted) should be displayed, and the menu is presented again.
So I'm getting stuck on how I can place a counter that starts at 0 and every time the user answers correctly then 1 will be added to the counter and quit if it gets 3 in a row or go back to 0 if the user answer is incorrect.
I will provide my code I'm getting confused on how having a while loop inside of the if statement and then another while loop for the count, it's confusing I know but once you see my code you will see what I'm talking about.
So I know I can place a counter like this:
int counter = 0;
while (counter < 4)
if statement here
counter ++;
else
counter = 0;
import java.util.Scanner;
class AlgebraTutor {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generate_random(max_value, min_value);
double x_value = generate_random(max_value, min_value);
double b_value = generate_random(max_value, min_value);
double y_value = generate_random(max_value, min_value);
Scanner user_input = new Scanner(System.in);
int user_answer_int = 0;
while ((user_answer_int < 4) && (user_answer_int >= 0)) {
System.out.println("Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. ");
user_answer_int = user_input.nextInt();
if (user_answer_int == 1) {
check_answer_for_y(m_value, x_value, b_value);
}
else if (user_answer_int == 2) {
check_answer_for_m(x_value, y_value, b_value);
}
else if (user_answer_int == 3) {
check_answer_for_b(m_value, x_value, y_value);
}
else {
System.out.println("You are done");
}
}
}
static void check_answer_for_m(double x_value, double y_value, double b_value) {
System.out.println("Solve For M Problem ");
System.out.println("Given: ");
System.out.println("b = " + b_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of m? ");
Scanner user_input = new Scanner(System.in);
String user_answer_m = "";
user_answer_m = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_m);
int correct_answer_m = (((int)y_value - (int)b_value) / (int)x_value);
if (user_answer_int == correct_answer_m){
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_m);
}
}
static void check_answer_for_b(double m_value, double x_value, double y_value) {
System.out.println("Solve For B Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of b? ");
Scanner user_input = new Scanner(System.in);
String user_answer_b = "";
user_answer_b = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_b);
int correct_answer_b = ((int)y_value - ((int)m_value * (int)x_value));
if (user_answer_int == correct_answer_b){
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_b);
}
}
static void check_answer_for_y(double m_value, double x_value, double b_value) {
System.out.println("Solve For Y Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer_y = "";
user_answer_y = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_y);
int correct_answer_y = (int) m_value * (int) x_value + (int) b_value;
if (user_answer_int == correct_answer_y) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_y);
}
}
static int generate_random(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)+ 1)) + min_value);
}
}
Where I stated my while loop for the number entered by user
depending on the number then the if statement jumps in
where can I place my counter to start and catch all the if statements depending on the number the user picks and then if the user gets 3 correct in a row the program should go back to the main question. Can I do another while loop inside the one I already have? Or should I place it inside each if statement?

Place the loop here for each
else if (user_answer_int == 3) {
check_answer_for_b(m_value, x_value, y_value);
}
changing your main function to this.
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generate_random(max_value, min_value);
double x_value = generate_random(max_value, min_value);
double b_value = generate_random(max_value, min_value);
double y_value = generate_random(max_value, min_value);
Scanner user_input = new Scanner(System.in);
int user_answer_int = 0;
while ((user_answer_int < 4) && (user_answer_int >= 0)) {
System.out.println("Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. ");
user_answer_int = user_input.nextInt();
int i = 0;
if (user_answer_int == 1) {
while (i < 3){
if (check_answer_for_y(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
i++;
}
else {
i = 0;
}
}
}
else if (user_answer_int == 2) {
while (i < 3){
if (check_answer_for_m(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
i++;
}
else {
i = 0;
}
}
}
else if (user_answer_int == 3) {
while (i < 3){
if (check_answer_for_b(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
i++;
}
else {
i = 0;
}
}
}
else {
System.out.println("You are done");
}
}
}
static boolean check_answer_for_m(double x_value, double y_value, double b_value) {
System.out.println("Solve For M Problem ");
System.out.println("Given: ");
System.out.println("b = " + b_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of m? ");
Scanner user_input = new Scanner(System.in);
String user_answer_m = "";
user_answer_m = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_m);
int correct_answer_m = (((int)y_value - (int)b_value) / (int)x_value);
if (user_answer_int == correct_answer_m){
System.out.println("You are correct!");
return true;
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_m);
return false;
}
}
static boolean check_answer_for_b(double m_value, double x_value, double y_value) {
System.out.println("Solve For B Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of b? ");
Scanner user_input = new Scanner(System.in);
String user_answer_b = "";
user_answer_b = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_b);
int correct_answer_b = ((int)y_value - ((int)m_value * (int)x_value));
if (user_answer_int == correct_answer_b){
System.out.println("You are correct!");
return true;
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_b);
return false;
}
}
static boolean check_answer_for_y(double m_value, double x_value, double b_value) {
System.out.println("Solve For Y Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer_y = "";
user_answer_y = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_y);
int correct_answer_y = (int) m_value * (int) x_value + (int) b_value;
if (user_answer_int == correct_answer_y) {
System.out.println("You are correct!");
return true;
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_y);
return false;
}
}
static int generate_random(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)+ 1)) + min_value);
}

Related

How can I quit the game whenever e is pressed at any time?

If someone presses e, I want my game to stop at any time in the game.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time! ");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
int theAnswer = input.nextInt();
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}
Instead of just "int theAnswer = input.nextInt();" write this:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equal("e")) {
System.out.println("Exiting the game...")
break;
}
else {
theAnswer = Integer.parseInt(nextIn);
}
I obviously haven't accounted for exceptions, but you can if you want.
So altogether it looks like this:
public class Game{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time!");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
//new part:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equals("e")) {
System.out.println("Exiting the game...")
break;
} else {
theAnswer = Integer.parseInt(nextIn);
}
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}

Change the askToContinue method so that it requires the user to enter Y, y, N or n

Having a problem getting the program to keep running after an error message has occurred. I have tried using different If/Else or While loops to get it to work but none seem to be giving any luck. The current code posted works until you enter something other than y, Y, n, or N. The error message will keep popping up after even if i enter y, Y, n, or N.
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class FutureValueApp {
public static void main(String[] args) {
// Avery Owen
System.out.println("Welcome to the Future Value Calculator\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
System.out.println();
// calculate the future value
double monthlyInterestRate = interestRate / 12 / 100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// print the results
System.out.println("FORMATTED RESULTS");
printFormattedResults(monthlyInvestment, interestRate,
years, futureValue);
// see if the user wants to continue
choice = askToContinue(sc);
}
}
public static double getDoubleWithinRange(Scanner sc, String prompt,
double min, double max) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
d = getDouble(sc, prompt);
if (d <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (d >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return d;
}
public static double getDouble(Scanner sc, String prompt) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt,
int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(sc, prompt);
if (i <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (i >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return i;
}
public static int getInt(Scanner sc, String prompt) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
try {
i = sc.nextInt();
isValid = true;
} catch (InputMismatchException e) {
System.out.println("Error! Enter a whole number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static double calculateFutureValue(double monthlyInvestment,
double monthlyInterestRate, int months) {
double futureValue = 0;
for (int i = 1; i <= months; i++) {
futureValue = (futureValue + monthlyInvestment) *
(1 + monthlyInterestRate);
}
return futureValue;
}
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice = sc.next();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
sc.nextLine(); // discard any other data entered on the line
System.out.println("Error! Enter y or n. Try again.");
}
return choice;
}
private static void printFormattedResults(double monthlyInvestment,
double interestRate, int years, double futureValue) {
// get the currency and percent formatters
NumberFormat c = NumberFormat.getCurrencyInstance();
NumberFormat p = NumberFormat.getPercentInstance();
p.setMinimumFractionDigits(1);
// format the result as a single string
String results
= "Monthly investment: " + c.format(monthlyInvestment) + "\n"
+ "Yearly interest rate: " + p.format(interestRate / 100) + "\n"
+ "Number of years: " + years + "\n"
+ "Future value: " + c.format(futureValue) + "\n";
// print the results
System.out.println(results);
}
}
Try this:
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice = sc.next();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
sc.nextLine(); // discard any other data entered on the line
System.out.println("Error! Enter y or n. Try again.");
System.out.print("Continue? (y/n): "); //this was missing
choice = sc.next(); //take the input again
}
return choice;
}
You are getting stuck in a while loop in case of invalid input and not accepting the input again.

How to set a limit in a for loop?

I have to create a program to calculate the average of each students' scores. I managed to do that but how can I limit the score to be only between 0 to 100? I've searched other questions and many shows to put while statement. The problem is that I don't know where to add the while. So here's the code:
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
If there is any other ways please do state. Thanks in advance.
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
double Input = 0; **//Add this in your variable**
boolean Valid = false; **//Add this in your variable**
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
//validation of your input from 0 to 100
if(Input>=0&&Input<=100)
{
Valid = true;
}
//enter while loop if not valid
while(!Valid)
{
System.out.println("");
System.out.print("Please enter a valid score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
if(Input>=0&&Input<=100)
{
Valid = true;
}
}
Valid = false; //reset validation;
Total += Input;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid:
Scanner scanner = new Scanner(System.in);
int score;
while (true) {
System.out.print("Please enter score " + (g + 1) + ": ");
score = scanner.nextInt();
if (score >= 0 && score <= 100) {
break;
}
System.out.println("Please enter a valid score between 0 and 100!");
}
Total += score;
Remember to close your Scanners to avoid memory leaks!

Array not printing properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}

Global Int variable method for multiple methods

I have to set up a math program that supplies random questions to the user based on their year level, and if they're doing well raise the difficulty. I've set up this code here that runs through questions and if they meet the requirements it displays the harder questions, however if "i" that i use to determinate how member questions they've done if separate the program will run the harder questions then go back and finish the easier questions
So basically I've tried to write a method for global "i" which all other methods will use, however when i replace "i" with the method it stops counting and continues to display questions infinitely and i don't know how to fix this.
import java.util.Scanner;
import java.util.*;
import java.util.Date;
public class Quiz {
public static void main(String[] args) {
int answer;
int correct;
double current_score = 100.00;
// int i = 0;
while (questionsDone() < 10) { // start of question loop
int random = (int) (Math.random() * 9 + 0);
int random2 = (int) (Math.random() * 9 + 0);
System.out.print("What is the sum of" + " ");
System.out.print(random);
System.out.print(" + " + random2 + " ");
System.out.print("=" + " ");
Scanner scan = new Scanner(System.in);
//answer
answer = scan.nextInt();
correct = random + random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10.00);
}
System.out.println("Your current percentage is " + current_score); // end of result display
// i++; // raise number of questions given by 1
if (questionsDone() == 5 && current_score >= 75) { // code to move up or down year level
System.out.println("You are doing well! Let's increase the difficulty a little");
Year1_10Questions();
}
}
}
public static void Year1_10Questions() {
int i = 0;
int answer;
int correct;
double current_score = 100.00;
while (i < 10) { // start of question loop
int random = (int) (Math.random() * 9 + 0);
int random2 = (int) (Math.random() * 9 + 0);
int random3 = (int) (Math.random() * 2 + 1);
String operator = "";
switch (random3) {
case 1:
operator = "+";
break;
case 2:
operator = "-";
break;
}
System.out.print("What is the sum of ");
System.out.print(" " + random + " ");
System.out.print(operator + " ");
System.out.print(random2 + " ");
Scanner scan = new Scanner(System.in);
//answer
answer = scan.nextInt();
if (random3 == 1) {
correct = random + random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10);
}
} else if (random3 == 2) {
correct = random - random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10);
}
}
System.out.println("Your current percentage is " + current_score); // end of result display
i++; // raise number of questions given by 1
}
} // end of year 1_10 questions
public static int questionsDone() {
int i = 0;
i++;
return i;
}
}
Since all the methods are in the same class, you can define i on class level:
public class Quiz {
static int i;
...
}

Categories

Resources