Trying to put an if-statement in a for loop - java

I am trying to input an if-statement inside of this for-loop so that whenever the user still has to eat the loop can be redone without having to lose the data already provided.
boolean yes = true;
boolean no = false;
double calorieCount = DCN;
int snackCalories = 300;
int mealCalories = 1100;
double meal = mealCalories;
double snack = snackCalories;
for (int i = 1; calorieCount <= calorieCount; calorieCount--) {
System.out.println("Did you eat? yes or no");
String answer = sc.next();
if(yes == true) { //You did eat
System.out.println("Did you eat a meal(1) or a snack(2)?");
int foodChoice = sc.nextInt();
if(foodChoice == 1) //Meal
System.out.println("Your calories left for the day : " + (calorieCount - meal));
}
int foodChoice = sc.nextInt();
if(foodChoice == 2) {//Snack
calorieCount = calorieCount - snack;
System.out.println("Your calories left for the day : " + (calorieCount - snack));
}
else {
System.out.println("Your calories left for the day : " + calorieCount);
};
else(no == false){
System.out.println(calorieCount);
}

it seems like you have some real syntax & semantic problems. For example your for-loop condition is calorieCount <= calorieCount. Both sides are equal. Overall its hard to read your Code because its not formatted correctly. Its hard to help right now - use a formatting Tool - Check Syntax and use a Debugger. Then clarify your question. Naming of your variables could also be improved.

Related

how to extract answers from for loop

I can't figure out how to correctly write my for loop statement that will give me the correct score. I bolded the code that is what I can't figure out how to write correctly. Anytime I run my program I end up with the first result of (rslt < 3) no matter what numbers I enter.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String options[] = {
"mild or spicy",
"tea or coffee",
"breakfast or " +
"brunch",
"summer or winter",
"paper or plastic"
};
int answers[] = new int[options.length];
String result[] = new String[answers.length];
boolean bool = true;
while (true) {
for (int i = 0; i < options.length; i++) {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 1] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 2] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 3] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 4] + "?");
answers[i] = scanner.nextInt();
break;
}
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
int rslt = getScore(result);
if (rslt < 3)
System.out.println("You prefer life to be calm and organized");
else if (rslt > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
int out = scanner.nextInt();
if (out == 0)
bool = false;
if (!bool)
System.exit(0);
}
}
static int getScore(String[] result) {
int score = 0;
for (int i = 0; i < result.length; i++) {
switch (result[i]) {
case "spicy":
score++;
break;
case "coffee":
score++;
break;
case "breakfast":
score++;
break;
case "winter":
score++;
break;
case "paper":
score++;
break;
}
}
return score;
}
}
I have modified your code according to my understanding of the code.
It works just exactly like you may have wanted.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[][] options = {
{"mild", "spicy"},
{"tea", "coffee"},
{"brunch", "breakfast"},
{"summer", "winter"},
{"plastic", "paper"}
};
int[] answers = new int[options.length];
do {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i][0] +
" or " + options[i][1] + "?");
answers[i] = scanner.nextInt();
}
int result = getScore(answers);
if (result < 3)
System.out.println("You prefer life to be calm and organized");
else if (result > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
} while (scanner.nextInt() != 0);
}
static int getScore(int[] answers) {
int score = 0;
for (int answer : answers) if (answer == 1) score++;
return score;
}
}
To Fix Your Code
In the first for-loop, you are supposed to loop through the options array. But somehow you unfold the loop within the loop body. To prevent the whole thing loop again, you break the loop immediately. To fix the first loop, write it like this instead. Properly loop through each element, no need to unfold it, no need to break it.
System.out.println("Enter 0 for the preference on the left\n" + "Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
}
In the second loop, you are supposed to retrieve the selected string from answers and write the string to results. Without modifying your data structure, this can be achieved by using split(" or ") on the option, which gives you an array of string which you can use the answer as index to access. Note that this does not prevent array index out of bound exception if user enter anything other than 0 or 1, which you should totally do, but is out of scope of this question.
for (int i = 0; i < answers.length; i++) {
result[i] = options[i].split(" or ")[answers[i]] ;
}
And there you go.
To Solve Your Task
Alternatively, redesigning the data structure and logic to get rid of the unnecessary string manipulation and comparison is more ideal. You don't even need the result and answers array, simply add up the user input will do (if the user follows your instruction)
int rslt = 0;
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
rslt += scanner.nextInt();
}
Inside the loop, you continue assigning the result to the same index in the answers list, rather than assigning the result to another index for each input. Because you are not iterating anything, you don't even need the loop. Replace the entire while loop with the code below. Please upvote and accept answer if it solves/helps you with your problem.
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[0] + "?");
answers[0] = scanner.nextInt();
System.out.println("Do you prefer " + options[1] + "?");
answers[1] = scanner.nextInt();
System.out.println("Do you prefer " + options[2] + "?");
answers[2] = scanner.nextInt();
System.out.println("Do you prefer " + options[3] + "?");
answers[3] = scanner.nextInt();
System.out.println("Do you prefer " + options[4] + "?");
answers[4] = scanner.nextInt();
Also, please note this:
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
won't work. Instead of result[i] = [answers[i]];, do result[i] = Integer.parseInt(answers.get(i)).
This is part causing the unexpected behaviour: result[i] = [answers[i]];
From what I understood, you want to implement this:
For each option, store the user choice like 0 or 1, 0 for left, 1 for right
For each user choice, store the string value of the choice, i.e., for the 1st question if the user inputs 0, mild should be captured
Calculate scores by comparing string value of user input against a branching construct, switch case here
The problem is in step 2, the current code result[i] = [answers[i]]; does not express this operation properly.
answers[i] stores the user choice 0 or 1, step 1 operation. So to convert it to the corresponding choice in string step 2 operation, something like this should be done
(options[i].split(" or "))[answers[i]]
Explanation:
Pick up the complete string for each answer
Divide the string into two parts(array with 2 indexes 0 and 1), left and right, using a delimiter, " or " in this case
pick up the left or right based on the value stored in answers[i](the user input)
This should let the code behave as expected :)
There are other aspects that can be improved in the code though, as others have already suggested.

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.

Java. making a question re-ask if you get it wrong

I am new to java so I'm terrible at it. Basically I am making a multi choice quiz thing.
But my problem is that even if you get the question wrong it goes to the next question
and I want it to ask the same question again, like a loop. I have tried to make it work but I can't, it's probably very simple and easy.
If anyone can help that would be cool !
it says
whats 9+10?
1. 19
2. 21
3. 18
current code:
iAnswer = Integer.parseInt(System.console().readLine());
if (iAnswer == 1) {
System.out.println(" ");
System.out.println("Correct");
}
else {
iLives -= 1;
System.out.println(" ");
System.out.println("Incorrect");
}
(when you get a question wrong you lose a life, but i don't think that matters)
I'm not sure if this is what you asked for but I came up with this !
//get input from console
Scanner scanner = new Scanner(System.in);
//create a loop to keep
while (true) {
//get 2 random number on value(0 - 20)
int n1 = (int) (Math.random() * 20 + 1);
int n2 = (int) (Math.random() * 20 + 1);
//correct Answer is saved in correctAns value
int correctAns = n1 + n2;
System.out.println("What is the anwser of : ");
System.out.print(n1 + " + " + n2 + " = ");
//get the answer from user input
int ans = scanner.nextInt();
//if user input is equal to current Answer
if (ans == correctAns) {
System.out.println("Congrats next question !");
} else {
//if user input is not equal to currentAns
boolean condition = true;
//create another loop where user has to answer right to get to
//the next question
while (condition) {
System.out.println("What is the anwser of : ");
System.out.print(n1 + " + " + n2 + " = ");
ans = scanner.nextInt();
//if user input is equal to currentAns
if (ans == correctAns) {
//stop the loop and continue to the other question
condition = false;
} else {
// if user input is not equal to currentAns keep asking
// the same question
condition = true;
}
}
}
}

How would I loop my program back to the beginning after a question was answered correctly 3 times in a row/ and add variance

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();
}
}

Java scanner: nextInt

I am a beginner in programming (learning Java). I am trying to write a program in which I list four different options for the user to choose from.
Here is part of it:
import java.util.*;
public class fight {
public static int upgrade1 = 0;
public static int upgrade2 = 0;
public static int upgrade3 = 0;
public static int upgrade4 = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your name:");
String player = scan.next();
System.out.println("You have earned 2 upgrade points. Which of the following traits would you like to boost by 2 points?\n"
+ " 1. upgrade1\n 2. upgrade2\n 3. upgrade3\n"
+ " 4. upgrade4");
if (scan.nextInt() == 1) {
upgrade1 = upgrade1 + 2;
System.out.println("Your upgrade1 level is now: " + upgrade1);
}
else if (scan.nextInt() == 2) {
upgrade2 = upgrade2 + 2;
System.out.println("Your upgrade2 level is now: " + upgrade2);
}
else if (scan.nextInt() == 3) {
upgrade3 = upgrade3 + 2;
System.out.println("Your upgrade3 level is now: " + upgrade3);
}
else if (scan.nextInt() == 4) {
upgrade4 = upgrade4 + 2;
System.out.println("Your upgrade4 level is now: " + upgrade4);
}
}
}
The problem is: When the user enters which option they want to pick, they must enter the number (x being the number they choose) x amount of times. For instance, the user wants to choose option 3. They must enter the number 3 three times into the console before it understands and completes the next line.
Here is the console after running the program:
Please enter your name:
rick
Hello, rick. You have earned 2 upgrade points. Which of the following traits would you like to boost by 2 points?
1. upgrade1
2. upgrade2
3. upgrade3
4. upgrade4
3
3
3
Your upgrade3 level is now: 2
I hope this makes sense, and any help is much appreciated (I assume I'm just making a dumb rookie error). Also, if you have any constructive criticism about the way it's structured, please don't hesitate. Thanks!
You can't repeatedly call scan.nextInt(). Unless, of course, you're expecting multiple different integers to be read.
Instead:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your name:");
String player = scan.next();
int ichoice = scan.nextInt();
switch (ichoice) {
case 1:
...
Each time you call scan.nextInt in one of your if statements, it reads another int. Change to:
int userChoice = scan.nextInt();
if (userChoice == 1)
{
...
}
else if (userChoice == 2)
...
As for constructive criticism, pick a style you like and use it. Your indentation is all over the place; this makes code more difficult to read. It doesn't matter if it's a commonly used style and it doesn't matter what everyone else thinks of it, just make sure you like it and stick to it.
Eclipse can auto-format code for you, and this behavior is customizable (You can fiddle with it so it matches your style).
This is because you are calling scan.nextInt() in every if/else if statement. What you want to do is store the value they entered and then check the value in the if/else if statements, otherwise you're basically prompting the user for input multiple times.
int input = scan.nextInt();
if (input == 1) {
upgrade1 = upgrade1 + 2;
System.out.println("Your upgrade1 level is now: " + upgrade1);
}
else if (input == 2) {
upgrade2 = upgrade2 + 2;
System.out.println("Your upgrade2 level is now: " + upgrade2);
}
else if (input == 3) {
upgrade3 = upgrade3 + 2;
System.out.println("Your upgrade3 level is now: " + upgrade3);
}
else if (input == 4) {
upgrade4 = upgrade4 + 2;
System.out.println("Your upgrade4 level is now: " + upgrade4);
}
Each time you call nextInt(), another int is read from the input. You thus want to call it only once!
int choice = scan.nextInt();
if (choice == 1) ...
if (choice == 2) ...

Categories