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) ...
Related
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;
}
}
}
}
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.
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();
}
}
So I'm starting to get the hang of java, and I'm creating a quiz as a mini project. However, when I get to the input part of my program, it breaks down. What's going on?
I also apologize for the formatting
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int score = 0;
int total = 0;
System.out.println("Are you ready for a quiz? (Y/N)");
char answer = in.findInLine(".").charAt(0);
if (answer == 'Y' || answer == 'y');
{
String a = "Barrow";
String b = "Juneau";
String c = "Anchorage";
String d = "Annapolis";
System.out.println("Alright! Lets get right to it!");
System.out.println("What is the Capital of Alaska?");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
char choice = in.findInLine(".").charAt(0);
if (choice == 'B' || choice == 'b')
{
System.out.println("Good Job! 1 point for you!");
score = score + 1;
}
else
{
System.out.println("Incorrect! the answer was actually " + b);
}
String e = "Yes";
String f = "No";
System.out.println("Alright, Next Question! Can you"
+ " store the value 'cat' in a variable of type int?");
System.out.println("A: " + e);
System.out.println("B: " + f);
char secchoice = in.findInLine(".").charAt(0);
if (secchoice == 'A' || secchoice == 'a')
{
System.out.println("Correct! Good Job!");
score = score + 1;
}
else
{
System.out.println("Incorrect");
}
System.out.println("What is the result of 2+2X3-5?");
int result = in.nextInt();
if (result == 3)
{
System.out.println("Correct! Good Job!");
}
else
{
System.out.println("Incorrect");
}
System.out.println("Your total score was " + score + "out of 3");
}
}
}
You are getting a NullPointerException on line 26 because of the way that findInLine() works. Basically, you have used up the one line of input you give it when it starts and the Scanner has advanced passed it to find the next one (which does not exist). In other words, you should use another method for Scanner or use an entirely different approach for getting input.
For example, it is preferable to use this technique
char answer = in.nextLine().charAt(0);
because nextLine() will wait until it has more input.
Of course, you will have to come up with some way to parse the input from the user to make sure that it is valid (i.e. if they can only choose between 'Y' and 'N' you handle the case where they choose neither).
That would look something like
char answer = parseInput(in.nextLine().charAt(0));
where parseInput(String s) is a method you write yourself.
As far as other approaches go, this tutorial from Oracle can help you get started.
I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();