Java Program Loop won't Execute and Prompt User? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
Okay so I am only part of the way through my array inventory program, but my while loop that is supposed to prompt a user to re-enter a number when they have entered an invalid one will not execute. When an invalid number is entered the program just ends...I have tried a couple methods and neither are working. this is where i am at now, any ideas??
thanks much!
public class InventorySystem {
public static void main(String[] args) {
String[] newItemInfo = new String[1000];
String[] itemDescription = new String[1000];
int[] itemPrice = new int[1000];
int choice;
boolean isValid;
int itemChoice;
Scanner inputDevice = new Scanner(System.in);
System.out.println("*****Raider Inventory System*****");
System.out.println("1. Enter a new item");
System.out.println("2. View Item Information");
System.out.println("3. View a list of all items");
System.out.println("9. End Program\n");
System.out.println("Please enter your selection: ");
choice = inputDevice.nextInt();
if (choice == 1 || choice == 2 || choice == 3 || choice == 9) {
isValid = true;
} else {
isValid = false;
}
** while (isValid = false) {
System.out.println("Invalid entry, please enter either 1, 2, 3, or 9 for menu options.");
** }
for (int x = 0; x < 1000; ++x) {
if (choice == 1) {
System.out.println("Please enter the name if the item: ");
newItemInfo[x] = inputDevice.nextLine();
System.out.println("Please enter the item description: ");
itemDescription[x] = inputDevice.nextLine();
System.out.println("Please enter item price: ");
itemPrice[x] = inputDevice.nextInt();
}
}
if (choice == 2) {
System.out.println("***Show item Description***");
System.out.println("0. ");
System.out.println("please enter the item number ot view details: ");
itemChoice = inputDevice.nextInt();
}
if (choice == 3) {
System.out.println("****Item List Report****");
}
if (choice == 9) {
System.exit(0);
}
}
}

In your line
while(isValid = false)
the = doesn’t do what you think it does. In Java, a single = means assign the expression on the right side to the variable on the left side. It does not mean to compare the two sides.
So you should rather write this:
while (isValid == false)
Note the double ==. This code works, but you can write it even more beautifully:
while (!isValid)
The ! means not.

Don't do while (isValid = false). You're setting it to false!
Instead do
while (!isValid) {
}
Also, don't do while (isValid == false) -- that's ugly code.
Next, change isValid inside the loop.
while (!isValid) {
// get input from user in here
// test input and check if is valid. If so, set isValid = true;
// something must set isValid to true in here, else it will
// loop forever
}
Otherwise you'll be stuck in an infinite loop. The lesson to be learned here is to mentally walk through your code as if you were running it in your brain. This way you catch logic errors like what you've got.

Related

How to validate user input in Java? [duplicate]

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed last year.
I'm trying to get user input and check if it is "1" or "2" and display an error messages if it's not. I keep getting error messages even when the input is correct.
Scanner user_input = new Scanner(System.in);
String choice = "";
// Input Validation
do {
// Read user choice
choice = user_input.nextLine();
if (!choice.equals("1") || !choice.equals("2"))
System.out.println("Invalid input. Give new value");
}while (!choice.equals("1") || !choice.equals("2"));```
Your condition is incorrect.
Use logical AND if need to eliminate both 1 and 2.
I think you wanted to achieve this
do {
choice = user_input.nextLine();
if (!choice.equals("1") && !choice.equals("2"))
System.out.println("Invalid input. Give new value");
} while (!choice.equals("1") && !choice.equals("2"));
Also to remove redundancy and improve the readability of code consider removing the validation logic to a separate method.
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String choice = "";
do {
choice = user_input.nextLine();
if (isValid(choice))
System.out.println("Invalid input. Give new value");
} while (isValid(choice));
System.out.println("Your input is valid: " + choice);
}
private static boolean isValid(String choice) {
return !choice.equals("1") && !choice.equals("2");
}
There's a logical error in the conditions. There should be "&&" instead of "||".
Thanks to #tgdavies.
Like this...
String choice = "";
// Input Validation
do {
// Read user choice
choice = user_input.nextLine();
if (!choice.equals("1") && !choice.equals("2"))
System.out.println("Invalid input. Give new value");
}while (!choice.equals("1") && !choice.equals("2"));
if (!choice.equals("1") || !choice.equals("2")) doesn't make sense
I'm pretty simple minded, so I always like to do some simple checks, for example...
System.out.println(!true || !false); // !"1".equals("1") || !"1".equals("2")
System.out.println(!false || !true); // !"2".equals("1") || !"2".equals("2")
System.out.println(!false || !false); // !"3".equals("1") || !"3".equals("2")
Which prints
true // Show error message ... this is wrong, `1` is valid
true // Show error message ... this is wrong, `2` is valid
true // Show error message ... this is correct
which is obvious wrong, the first statement, we when not 1 or 2, print an error message
So, instead, we should invert the result of both sides of the ||, for example...
System.out.println(!(true || false)); // !("1".equals("1") || "1".equals("2"))
System.out.println(!(false || true)); // !("2".equals("1") || "2".equals("2"))
System.out.println(!(false || false)); // !("3".equals("1") || "3".equals("2"))
which prints...
false // Don't show error message ... `1` is valid
false // Don't show error message ... `2` is valid
true // Show error message ... `3` is invalid
Okay, that seems better
I'd also simplify the exit condition along the way...
Scanner user_input = new Scanner(System.in);
String choice = "";
boolean isValidChoice = false;
// Input Validation
do {
// Read user choice
choice = user_input.nextLine();
if (!(choice.equals("1") || choice.equals("2"))) {
System.out.println("Invalid input. Give new value");
} else {
isValidChoice = true;
}
} while (!isValidChoice);
System.out.println("Good choice!");
You can escape in the middle of the loop if the input is valid.
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String choice = "";
// Input Validation
while (true) {
// Read user choice
choice = user_input.nextLine();
if (choice.equals("1") || choice.equals("2"))
break;
System.out.println("Invalid input. Give new value");
}
}

While statement isn't excuting inside if statement? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to make it print out a range of specified numbers. So if they select option 1 and put in 1 and 15, I want it to print out 1 to 15. Once it gets to the while statement though it just prints nothing.
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please choose your choice from the following menu");
System.out.print("\n1) Print through all integer numbers between two given integers");
System.out.print("\n2) Display a right triangular pattern of stars");
System.out.println("\n3) Quit");
int userInput = in.nextInt();
if (userInput == 1) {
System.out.print("Enter the start number: ");
int firstInteger = in.nextInt();
System.out.print("Enter the second number: ");
int secondInteger = in.nextInt();
while (firstInteger < secondInteger);
System.out.print(firstInteger);
firstInteger++;
} else if (userInput == 2) {
System.out.print("Enter the height: ");
int triangleHeight = in.nextInt();
} else if (userInput == 3);{
System.exit(userInput);
}
in.close();
}
}
You should change :
while (firstInteger < secondInteger);
System.out.print(firstInteger);
firstInteger++;
to
while (firstInteger < secondInteger) {
System.out.print(firstInteger);
firstInteger++;
}
while (firstInteger < secondInteger);
This will be treated as two executable lines of instructions,
which is similar like
while (firstInteger < secondInteger)
;
Try to remove the ; after while statement

Random Number Guesser - Cannot Input [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm attempting a java challenge in which I guess a random number and the program tells me if it is correct.
However, the program stops at the while loop and tells me I can only input when the program is running:
public class javaChallenge1
{
// Instance variables
int number = 0;
int guess = 0;
boolean gameFinished = false;
// Core variables
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
public void sampleMethod()
{
number = rand.nextInt(100);
System.out.println("Guess the number generated.");
while (gameFinished = false)
{
guess = keyboard.nextInt();
keyboard.nextLine();
if (guess == number) {
System.out.println("Congrats! You have guessed the number correctly.");
gameFinished = true;
} else {
System.out.println("Bad luck. Try again.");
}
keyboard.nextLine();
}
}
}
The error is on this line:
while(gameFinished = false)
You DO NOT check if the value is false but instead you assign the value false to your variable.
You should write == instead of = to compare values instead of assigning it
while(gameFinished == false)
If you want to compare gameFinished against false, use the == operator:
while (gameFinished == false)
The following will change the value of gameFinished to false, then check if it is true. So the loop stops.
while (gameFinished = false)
In while loop you should put the condition but you assigned the value. so please replace
gameFinished = false
to
gameFinished == false

Multiple Choice and True/False Quiz using loops [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to build a quiz for a user that has to have 5 multiple choice questions and 5 true/false questions. I must do this using loops (while loops). I've come to the point where I set up a separate method asking the user the questions and error checking for the true/false or multiple choice questions. I now have to somehow give the user a point if they answer each question correctly. Then in the end, I must give the user the the total amount of points they won. Then I have to ask if they want to play again in the end, if they say yes I have to go back to the first question and restart the game and if they say no the program has to close. Here is where I got to on my main method. I started putting a while loop for the first answer (correct answer being 3) and making a point variable but I'm not sure where to go from there and how to connect everything. I hope what I did so far is correct. Thanks!
UserInteraction input = new UserInteraction();
Questions ask = new Questions();
int answer1 = 0, answer2 = 0, answer3 = 0, answer4 = 0, answer5 = 0;
int a1 = ask.Question1(answer1);
int point;
while (a1==3)
{point = 1;
}
int a2 = ask.Question2(answer2);
int a3 = ask.Question3(answer3);
int a4 = ask.Question4(answer4);
int a5 = ask.Question5(answer5);
boolean answer6=false, answer7=false, answer8=false, answer9=false, answer10=false;
String a6 = ask.Question6(answer6);
String a7 = ask.Question7(answer7);
String a8 = ask.Question8(answer8);
String a9 = ask.Question9(answer9);
String a10 = ask.Question10(answer10);
For the Questions methods, I'll put two blank examples on here.
{public int Question1 (int answer1)
{String message = "";
int smallestValue = 1;
int largestValue = 4;
System.out.println("Q1) What is...?");
System.out.println("1: ....");
System.out.println("2: ......");
System.out.println("3: ......");
System.out.println("4: ......");
System.out.print("Enter the number");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer1 = input2.getIntValueFromUserBetween(message, smallestValue, largestValue);
return answer1;
}
public String Question6(boolean answer10)
{String message = "";
System.out.println("(Q10) ....(true/false)");
System.out.print("Enter your answer here: ");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer10 = input2.confirm(message);
return "" + answer10;
}
}
Sorry if I misunderstand your question, but I don't understand why you're using a loop here.
while (a1==3)
Your program is either going to get stuck here or never use it. What I mean is that if the user answers the question correctly (i.e 3), they will be stuck in the while loop until you set a1 != 3.
What I think is a better solution is using selection. For example:
if (a1 == 3) {
point += 1; // point = point + 1
// Or whatever functionality you need here
}
Edit: If you really must use a loop, then having a Boolean flag would be the way to go. For example:
Boolean flag = false;
if (a1 == 3) {
flag = true;
while (flag) {
point += 1; //point = point + 1
// Make sure that you set flag equals to false at the end of the loop though, otherwise it will infinitely loop
// Include any other functionality needed
flag = false;
}
}
Is this similar to what your looking for?
int correct;
public void quiz() { // this is so you can restart quiz easily
String[] answers = String[5];
//add answers to array, set them to variables/constant first then index
String[] questions = String[5];
// add questions to array
for(int i = 0; i <= questions.length; i++) { // stops after all questions have been asked, make sure its "<="
System.out.println(questions[i]); // prints question 1 first loop then 2 and so on
// read input from user
if(input == answers[i]) { // you may have to convert input to correct type
correct += 1;
}
}
}
System.out.println("You got " + correct + " correct answers");
System.out.println("Would you like to play again?");
if(input == yes) {
quiz(); //starts quiz again // starts quiz method again
P.S. sorry if I've misunderstood the question
To ask different questions you can just change the String variables then call quiz() to ask those questions. nice and simple :)

Error "else" without "if" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this program set up and i need help with 2 errors that i am getting
import java.util.Scanner;
public class EvenOdd {
public static void main(String[]args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("---EvenOdd--- /n");
System.out.printf("Enter a whole number: ");
c = in.nextInt();
}
public static EvenOdd (int num) {
int c = num;
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
return EvenOdd;
}
}
C:\Users\Desktop\EvenOdd.java:28: error: not a statement
else (c)
C:\Users\Desktop\EvenOdd.java:28: error: 'else' without 'if'
else (c)
2 errors
Your else doesn't make sense. First of all, you are not using braces, but also your boolean logic does not make sense. Just adding braces will not make your code compile.
I think this rewrite is the closest to what you have
public static boolean EvenOdd (int num) {
// Here your calculation is done
boolean isEven = (c/2)*2 == c;
if (isEven) {
System.out.println("is even.");
} else if (!isEven) {
// Using 'else if' for a boolean parameter does not make much sense
// but i'll leave it here to explain the syntax
System.out.println("is odd");
}
return isEven;
}
However, the most common way to check for odd or even is using the modulus operator. And if i make the entire code a bit more java-ish, you'd end up with (for example method-naming)
/**
* Check if the given number is even.
* #param num the number to check
* #return whether num is an even number
*/
public static boolean isEven (int num) {
if ((x % 2) == 0) {
System.out.println("is even.");
return true;
} else {
System.out.println("is odd");
return false;
}
}
Here is a solution
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
try{
System.out.println("---EvenOdd---");
System.out.print("Enter a whole number: ");
int c = keyboard.nextInt();
evenOdd(c);
}finally{
keyboard.close();
}
}
public static void evenOdd(int num)
{
int c = num;
if ((c/2)*2 == c){
System.out.println("is even.");
}else {
System.out.println("is odd");
}
}
Output:
for the input value 5
---EvenOdd---
Enter a whole number: 5
is odd
for the input value 4
---EvenOdd---
Enter a whole number: 4
is even.
Continued Reading
There are several problems with the original code and I will attempt to explain them in line order.
Original code for reference:
public class EvenOdd {
public static void main(String[]args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("---EvenOdd--- /n");
System.out.printf("Enter a whole number: ");
c = in.nextInt();
}
public static EvenOdd (int num) {
int c = num;
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
return EvenOdd;
}
}
First we have this line
System.out.print("---EvenOdd--- /n");
use of the .print() method here, while not illegal is unnecessary because java provides us with .println() which automatically creates a new line so we don't have to. (i.e. with "/n")
System.out.printf("Enter a whole number: ");
Next you use the .printf() method, this prints a formatted output and accepts arguments as a parameter. You aren't using any of the exclusive features of this method so we can achieve the same functionality with .print().
c = in.nextInt();
the variable in is not defined in this scope, I presume that you meant to use keyboard.nextInt().
public static EvenOdd (int num) {
when a method has no return type and the same name as the class it resides in (case sensitive) it is a constructor. Constructors do not require a return statement and are invoked with the syntax new ObjectConstructor() usually to assign a value to a variable of the same type as the constructor.
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
This if-else block is clearly not even java syntax.
first there is no need to cast your result to an int and the semicolon at the end of your conditional doesn't belong.
removing these errors brings us to:
if (c/2)*2 = c
System.out.println("is even.");
else (c)
System.out.println("is odd");
now we need to wrap our conditional in parentheses '( and )' and rather than use the assignment operator '=' we should use the comparison operator '==' which returns a boolean. Also, the else clause does not require a condition, if you would like to use a condition look into elseif.
these changes get us to this step.
if ((c/2)*2 == c)
System.out.println("is even.");
else
System.out.println("is odd");
Now we add proper brackets and we are good to go.
if ((c/2)*2 == c){
System.out.println("is even.");
}else{
System.out.println("is odd");
}

Categories