I want the while loop to execute when the user's input is a non-integer value, an integer value less than 1, or an integer value greater than 3. Once the input is valid, I will use it. However, the loop only works when the user inputs a non-integer value. I have gone through the logic and I am still not sure what's wrong.
Code:
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Please enter an integer value 1-3 for the row.");
while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
{
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
row = scnr.nextInt() - 1;
"while" works fine by itself. No "do" is required in this case. Here is your code:
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter an integer value 1-3 for the row.");
while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
{
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
int row = scnr.nextInt() - 1;
You need "do" when you want to execute code at least once and then check "while" condition.
Also each call for nextInt actually requires next int in the input. So, better use it only once like this:
int i;
while((i=scnr.hasNextInt() && (i > 3)) || (scnr.hasNextInt() && (i < 1)) || (!scnr.hasNextInt()))
I am not completly sure about this, but an issue might be calling scnr.nextInt() several times (hence you might give the value to a field to avoid this).
An easy to read solution would be introducing a tester-variable as #Vikrant mentioned in his comment, as example:
System.out.println("Please enter an integer value 1-3 for the row.");
boolean invalid=true;
int input=-1;
while(invalid)
{
invalid=false;
if(scnr.hasNextInt())
input=scnr.nextInt();
else
invalid=true;
if(input>3||input<1)
invalid=true;
if(!invalid)
break;
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
Related
I need to write a java program reading in an indefinite amount of numbers and saves them to a collection of numbers, until an (even number) is entered in by the user. I have tried with a while loop, that when a positive number is found in it it stops. But it is not really working. Here is codes I have tried:
public static void main(String[] args) {
int programInteger = 1;
int inputtedInteger;
while (programInteger < 2) {
System.out.println("Enter a number: "); //Asks user to input a number
Scanner in = new Scanner(System.in);
inputtedInteger = Scanner(in.nextLine);
if (inputtedInteger != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
inputtedInteger=in.nextInt();
}
else if (inputtedInteger % 2 == 0){
programInteger =+1;
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
}
/* if(inputtedInteger % 2 == 0) {
System.out.println("The number "+ inmatatTal +" you entered is an even number!");
}
else {
System.out.println("Enter a number?! ");
inputtedInteger = in.nextInt();
}
Fixing a few things in the logic of the loop should work:
int inputtedInteger = 0;
Scanner in = new Scanner(System.in);
while (inputtedInteger < 1) {
System.out.println("Enter a number: "); //Asks user to input a number
inputtedInteger = in.nextInt();
if (inputtedInteger % 2 != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
}
else if (inputtedInteger % 2 == 0){
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
I would setup an outline for the code like this:
setup Scanner, create collection
while true:
userInput = scanner.nextInt()
if userInput > 0: break
collection.add(userInput)
print('user entered', collection.length(), 'numbers.')
Hope that helps. I'll leave you to fill this using actual Java syntax.
I wrote a comment on the OP on why your structure is failing to solve the issue at hand.
This is part of a code that I am running and when the code runs it lets me enter a number but will not let me move on, it will just continue to print "Enter a student's total quiz score : " even though i have entered a value less than the perfect quiz score help!
while (perfectQuizScore > quizScore ) {
System.out.print("Enter a student's total quiz score : ");
quizScore = Integer.parseInt(keyboard.nextLine()); // 6
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore < 0) {
System.out.println("Invalid value! Value must be greater than 0.");
}
}
OUTPUT:
enter image description here
REVERSING THE SIGNS
enter image description here
If I'm understanding your question correctly... you want to exit the loop when the supplied quiz score is less than (or equal to) the perfect score? If so, you just need to change the sign in your while loop conditional (it is currently checking greater than).
Before:
while (perfectQuizScore > quizScore ) {
After:
while (perfectQuizScore < quizScore ) {
Now this is assuming that you initially set quizScore to a huge value (if you initialize it to 0 then the conditional will evaluate to false before entering the loop). A better solution is probably to use a do-while loop.
int quizScore = 0;
do {
System.out.print("Enter a student's total quiz score : ");
quizScore = Integer.parseInt(keyboard.nextLine()); // 6
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore < 0) {
System.out.println("Invalid value! Value must be greater than 0.");
}
} while (perfectQuizScore < quizScore or quizScore < 0);
Although I would personally probably structure this differently, to avoid writing your "bad" conditions down twice:
int quizScore = 0;
while (True) {
System.out.print("Enter a student's total quiz score : ");
quizScore = Integer.parseInt(keyboard.nextLine()); // 6
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore < 0) {
System.out.println("Invalid value! Value must be greater than 0.");
}
else {
// good input, exit the loop with a break statement
break;
}
}
Maybe the following is what you searching:
do {
System.out.print("Enter a student's total quiz score : ");
quizScore = scnr.nextInt();
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore <= 0) {
System.out.println("Invalid value! Value must be greater than 0.");
} else {
break; // get out of the loop
}
} while ( quizScore <= 0 || quizScore > perfectQuizScore );
Do the check (while) after getting the first time, also change the checks to stay on the loop until the user write a valid value.
The do {...} will let the code inside run one time before the while checks.
**Thanks Adi219 & Charles Spencer for helping with my part 1.
Now i'm trying a different approach, by validating the input before it store into an array, it look fine most of the time, but the exception only run once.
This is what i input to test the validating
1) I input "a", it returned "enter number between 0 to 100" which is correct.
2) I input 1000, and it returned "Invalid age" which i can tell that my IF conditions works.
3) No issue when i input the correct value for User no.1
Problem happens when i try to run the same test on User no.2. After I input correct value for User no.1, I type in "A" again and the programs just bypass all those conditions and captured no integer value.
import java.util.Scanner;
public class test2
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i = 0;
double x = 0;
double Total = 0;
double Average = 0;
int Users = 2; //I fixed a number for testing purpose
boolean isNumber =false;
double ages[] = new double[Users];
for(int counter =0; counter < Users; counter++){
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x =input.nextDouble();
if(x<0 || x>100){
System.out.print("Invalid age.. try again.. ");
}else if(x>0 || x<100){isNumber=true;}
}catch(Exception e){
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
System.out.println("User Age is "+ x); //Just to check input user's age
}
}
}
Because your entire do/while loop is based on whether isNumber is false, if you enter a valid number for user1, the isNumber variable is set to true, and the do/while loop will never run again because you never set isNumber back to false. There are two places were I set isNumber back to false, I've marked them. But I'm pretty sure this whole thing should be rewritten. For example there's no need to do:
else if(x > 0 || x < 100)
because you've already done:
if(x<0 || x>100)
If you do the first condition as x <= 0 || x >= 100 there's no need to do an else if statement.
for(int counter = 0; counter < Users; counter++)
{
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x = input.nextDouble();
if(x<0 || x>100)
{
isNumber = false; // Set to false if invalid number
System.out.print("Invalid age.. try again.. ");
}
else if(x > 0 || x < 100)
{isNumber = true;} // If the age for user1 is valid, isNumber is set
// to true
}catch(Exception e)
{
isNumber = false; // Set to false if number invalid
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
So, in this program when the while loop ends, it properly displays "You Win!" and it does execute the code asking if the user wants to view credits. However, the input isn't being accepted after the question and the program ends without accepting any input.
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to play a game called Threes? Y/N");
String answer = scan.nextLine(); //Simple yes or no
if (answer.contains("Y") || (answer.contains("y"))) {
System.out.println("OK, want to know how it works? Y/N");
String answer2 = scan.nextLine();
if (answer2.contains("n") || (answer2.contains("N"))) {
System.out.println("OK, Enter a single number.");
int mistake = 0; //Used as a counter for number of division mistakes made
int numstart = scan.nextInt(); //First number input
int current = numstart; //Current number displayed - starts as the first number
System.out.println("Enter 1 or -1 if you're adding or subtracting, and 0 to divide.");
System.out.println(numstart); //Displays first number input
int input = scan.nextInt(); //First function performed by user
while (current != 1) { //The game will run until the number '1' is reached
if (input == 1) { //If '1' is input, add one to the number, and display new number
current++;
System.out.println(current);
input = scan.nextInt();
}
if (input == -1) { //If '-1' is input, subtract one from the number, and display new number
current--;
System.out.println(current);
input = scan.nextInt();
}
if (input == 0) { //If '0' is input, try to divide
if (current % 3 != 0 && current != 1) { //If you can't divide by three, try again
System.out.println("Try again.");
mistake++;
input = scan.nextInt();
}
if (current % 3 == 0) { //If you can divide, do it and display new number
current = current / 3;
System.out.println(current);
input = scan.nextInt();
}
}
if (input == 69 || input == 666) //Cheat code! If you input 69 or 666, you automatically win
break;
if (((input > 1) && (input != 69) && (input != 666)) || input < -1) { //If input is not valid, try again and display error
System.out.println("Error - wrong input.");
input = scan.nextInt();
}
}
System.out.println("You Win! Mistakes: " + mistake + "\n"); //Will display a win condition, and amount of division errors
System.out.println("Thank you for playing Threes \n - Chris Burbach");
}
System.out.println("Credits? Y/N");
String credits = scan.nextLine();
if(credits.contains("Y")||credits.contains("y"))
{
System.out.println("\n***********************************************************************");
System.out.println("*Threes: a game of dividing by three - inspired by my boredom in class*");
System.out.println("***********************************************************************");
Sorry for any confusion, I figured it out. After each instance of "You Win!", outside of its nested if statement, I needed to addscan.nextLine(); because of it returning a newline character and terminating the program due to an empty input.
//Input Number
System.out.print("Enter a number from 1-10: ");
words = input.next();
//Processing String
if(!words.equals(FLAG)){
while(!words.equals("1") && !words.equals("2") && !words.equals("3") &&
!words.equals("4") && !words.equals("5") && !words.equals("6") &&
!words.equals("7") && !words.equals("8") && !words.equals("9") &&
!words.equals("10")){
System.out.print("Please enter a number in integer form from 1-10: ");
words = input.next();
}
}
//Close Scanner
input.close();
//String to Integer
num = Integer.parseInt(words);
//Output Number
if(num >=1 || num <=10){
System.out.println("\nYour number is: " + num);
}
How could i change the while loop? What if the number range was from 1-100? IS there any way to shorten the processing string segment? The program needs to be able to handle string and integers.
Parse it to an Integer
int number = Integer.parseInt(words);
and loop :
while( !(number > 0 && number <= 10) ){ // loop the loop }
N.B: Because you will be using parseInt(), you will need to learn to use try-catch blocks. Do look it up.
You can also directly use nextInt() method of the Scanner class for an input of Integer data type.
So you can do,
num = input.nextInt();
and then directly,
//Output Number
if(num >=1 || num <=10){
System.out.println("\nYour number is: " + num);
}
Make a min int and a max int.
int min =1;
int max =10; // change to 100 for if you wanted it bigger
Then when you get their value simply parse it(Parse turns it into an Interger)
int value= Integer.parseInt(words);
The final while loop would look like this:
while( !(number > min && number <= max) ){
//Your code
}
The easiest way to 'shorten' it would be to parse it before the while loop. You should be throwing NumberFormatException and putting your code in a try/catch block if you're going to be parsing strings to ints.
public void f() throws NumberFormatException{
try{
// other code
num = Integer.parseInt(words);
while( !(num>0 && num<=10) ){
// magic
}
// other code
}catch(NumberFormatException e){
// handle it!
}
}
Use a do while loop so that you don't have to ask the user for input twice, just let the loop do the work for you.
int number;
final int MIN = 0;
final int MAX = 100;
do
{
System.out.print("Please enter a number in integer form from 1-10: ");
words = input.next();
number = Integer.parseInt(words);
}while(!(number > MIN && number <= MAX));
Parse the input into an Integer before check validation.
But do remember to handle exception properly.
int number;
while(true){
try{
number = Integer.parseInt(words);
if(number <= 10 && number >= 1) break;
else
System.out.print("Your number is out of range (1, 10):");
}catch(NumberFormatException e){
System.out.print("Please input valid number from 1 to 10:");
}
words = input.next();
}
System.out.println("Your number is " + number);