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!
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.