While loop goes infinite when moving back an iteration - java

Using a while loop to prompt the user to enter 3 ints to average them out, need to reprompt when the input isn't an int, so I decided to take a step back in the loop when the input isn't an int, but when I enter a non int, it's as if it consistently goes to the condition that it isn't a int, and continues to reprompt, without rechecking for a new input.
Scanner scnr = new Scanner(System.in);
String prompt = "Type an integer: ";
int num = 0;
int i = 0;
while (i < 3) {
System.out.print(prompt);
if (scnr.hasNextInt()) {
int input = scnr.nextInt();
num += input;
} else i -= 1;
i += 1;
}
double average = num / 3.0;
System.out.println("Average: " + average);

hasNextInt() only returns true if an int is already there -- it doesn't actually get input. That's what your call to nextInt() is doing. But that's never being called because hasNextInt() is always false, as you've never actually taken user input, so i is being decremented in the else block and then incremented again forever.
An alternative approach would be to use a try/catch block with nextInt() to get the next input value, and step back if that catches an exception (meaning the input was not an int).

As a previous user has mentioned the main problem is that the hasNextInt() only checks and doesn't advance your scanner forward.
Here is how I would do this code, I hope it solves the issue:
int counter = 0;
boolean flag = false;
int sum = 0;
while(!flag){
System.out.println(prompt);
if (scnr.hasNextInt()){
int input = Integer.parseInt(scnr.nextLine());
sum = sum + input;
counter++;
}else{
scnr.nextLine();
System.out.println("You didn't enter an Integer.");
}
if (counter == 3){
flag = true;
}
}
double avg = sum / 3;
System.out.println("Average: " + avg);
There are probably better ways of doing it than mine but I hope it helps, good luck!

Related

User input never enters if statement

The point of the program is to have a user input an amount of integers endlessly (until they enter something other than an integer), and for each integer the user inputs, it should check if the integer is greater than or less than the value entered.
The problem: When the program runs, everything is fine until reaching
number = scanner.nextInt();
At this point, the user inputs their integer, but never makes it inside the following if statements. I would love a hint instead of an answer, but I'll take what I can get.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
} while (true);
scanner.close();
}
}
Your minNumber and maxNumber declarations should be out side of the loop. Also, you need to initialize the values as below to get correct min and max comparison with the entered values only:
int minNumber = Integer.MAX_VALUE;
int maxNumber = Integer.MIN_VALUE;
In print statement instead of minNumber you are printing number!
It's not reaching the if statements, because if it did, the user input would update to the value entered I would think. It doesn't. It outputs the values initially declared.
You're not getting the right output and you have a hypothesis that the cause is the code not entering the if statements. Following the scientific method, the next step is to test your hypothesis.
If you put printouts inside the if statements you'll see that they are indeed running. That's not it. The mistake must be elsewhere. You should collect more evidence and develop a new hypothesis.
Hint: Try printing out the values of your variables at the beginning and end of each iteration. I've marked the places below. Are they what you expect them to be? You're going to see an anomaly that should point you in the right direction.
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
// Print number, minNumber, and maxNumber.
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
// Print number, minNumber, and maxNumber.
} while (true);

For loop to get user input lets you enter two values for the first question, but only calculates one value

I created a small program that asks the user for 10 random numbers and it will print the sum of those numbers. I embedded it with a for loop and included a counter. Everything seems to be working fine except when I run the program, the first question allows me to enter two values, but it will still only calculate a total of 10 numbers.
Below is what I currently have and I need to understand what is going wrong when it prompts the user for the number the first time:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
boolean hasNextInt = scanner.hasNextInt();
if (hasNextInt) {
sum += numberInput;
} else {
System.out.println("Invalid Number");
}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
}
}
In each loop, you're calling scanner.nextInt() and scanner.hasNextInt(). But you do not use the result of hasNextInt() in a meaningful way (you might have noticed that your "Invalid Number" output is not what happens if you enter something that's not a number).
The first call to nextInt() blocks until you enter a number. Then hasNextInt() will block again because the number has already been read, and you're asking whether there will be a new one. This next number is read from System.in, but you're not actually using it in this iteration (you merely asked whether it's there). Then in the next iterations, nextInt() will not block because the scanner already pulled a number from System.in and can return it immediately, so all the subsequent prompts you see actually wait for input on hasNextInt().
This amounts to 11 total input events: The firts nextInt() plus all 10 hasNextInt()s
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
// boolean hasNextInt = scanner.hasNextInt();
//if (hasNextInt) {
sum += numberInput;
// } else {
// System.out.println("Invalid Number");
//}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
Don't call hasnextInt() it has no use here.
It has taken 11 inputs rather than 10.
If you remove this condition it will take 10 inputs and work fine.
Your condition have no impact on it.

How to check if an int contains a letter

I am trying to validate my code by error checking. I want to make sure the integer people enter does not contain a letter or more.
Here is my code. I am supposed to solve this problem using a one dimensional array. I got the code working but I am having problems with adding the error checking in.
Any help would be appreciated. Thanks
public void getNumbers() {
Scanner keyboard = new Scanner(System.in);
int array[] = new int[5];
int count = 0;
int entered = 0;
int k = -1;
while (entered < array.length) {
System.out.print("Enter a number ");
int number = keyboard.nextInt();
if (10 <= number && number <= 100) {
boolean containsNumber = false;
entered++;
for (int i = 0; i < count; i++) {
if (number == array[i]) // i Or j
{
containsNumber = true;
}
}
if (!containsNumber) {
array[count] = number;
count++;
} else {
System.out.println(number + " has already been entered");
}
} else {
System.out.println("number must be between 10 and 100");
}
//what does %d do?
for (int j = 0; j < count; j++) {
System.out.printf("%d ", array[j]);
}
System.out.println();
}
}
}
I'm assuming that you would want your program to ask the user to re-enter a number if they do not input a number the first time. In this scenario you might want to try something along the lines of this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while(!sc.hasNextInt()) {
//print some error statement
sc.nextLine();
}
int number = sc.nextInt();
System.out.println("Number is: " + number); // to show the value of number
// continue using number however you wish
Since hasNextInt() returns a boolean determining whether or not the input is an Integer, the program will never leave the while-loop until the program can confirm that the user has entered an integer.
keyboard.nextInt() will throw a InputMismatchException if you input a String.
If you want to check whether Scanner has an integer to read, you can use keyboard.hasNextInt().
Alternatively, you can read the input as
String s = keyboard.next() which will take the input as a String, and then use s.matches(".*\\d+.*") to detect whether or not it is an integer.
UPDATE: To answer questions -
keyboard.hasNextInt() will return a boolean. So for example, after System.out.print("Enter a number"), you could have an if statement checking to see if keyboard can receive numerical input, ie. if(keyboard.hasNextInt). If this is true, that means the user has entered numerical input, and you could continue with sayingint number = keyboard.nextInt(). If it is false, you would know that the user input is non-numerical.

Do Loops to create read user input to repeat or exit program Java

This is my first post.
Using a Scanner class, I'm trying to let user input to choose to repeat the program or quit. The thing is my Do loop statement repeats the program and does not exit even if the Do Loop is false and should exit the program.
// loop repeat or quit
do {
//initialize variable
int integer;
int x = 1;
int factorial = 1;
System.out.print("Please enter an integer \n");
integer = getInt.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = getString.next();
} while(quit != yes);
System.exit(0);
}
There were a few mistakes in your code, so I rewrote it a little bit and used the correct functions where you used incorrect ones.
public static void main(String args[])
{
// Scanner is used to take in inputs from user
Scanner scan = new Scanner (System.in);
String quit = "";
// loop repeat or quit
do {
//initialize variable
int integer = 0;
int x = 1;
int factorial = 1;
// User needs to enter integer, or it'll throw exception.
System.out.println("Please enter an integer");
integer = scan.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
// factorial = x!
while (x <= integer) {
factorial *= x;
x++;
};
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.println("do you want to quit? y or n");
quit = scan.next();
// if quit is NOT equal to y, we do it again
} while(!quit.equals("y"));
System.exit(0);
}
I hope the comments helps :)
I've edited your code and it now runs.
For future reference: include more comprehensive snippets so viewers of your code can more easily discover mistakes.
Problem: There is no way to guarantee the user only inputs y without any spaces . THe easy solution to this problem is to use the string method contains(). I've modified your loop so that if the user input y the program will exit and it now works. Let me know if this works and happy coding!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String quit ="";
do { //initialize variable
int integer; int x = 1; int factorial = 1;
System.out.print("Please enter an integer \n");
integer = in.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = in.next();
} while(!quit.contains("y"));
System.exit(0);
}
Shouldn't it be
while(quit != "y");
I also don't understand why you use System.out.print(); and then use \n when there's a perfectly good System.out.pritnln();
Also, since we're dealing with Strings the .nextLine(); is good enough for the Scanner. (You'll have to declare String quit as well.)

Do While Statement Issue

I must write a do loop that reads integers and computes their sum. Stop when reading a zero or the same value twice in a row. For example, if the input is 1 2 3 4 4, then the sum is 14 and the loop stops. Same thing if user input is 0. I need to know if I can use multiple parameters for the do while statement or if i need to nest another do while stamenent.
int input = 0;
int total = 0;
int update = 0;
System.out.println("Enter any number");
total = inputDevice.nextInt();
do
{
System.out.println("Enter any number");
input = inputDevice.nextInt();
// Do i have to nest a do-while statement here?
total = total + input;
}while((input != 0); // Or How would i insert a second parameter that stops the loop when a number is entered twice in a row?
For the above parameters I know i would do && to start the second parameter, I just cannot figure out the logic statement I would insert as the parameter.
System.out.println("The sum of the numbers is " + total);
}
}
You need to save the last input in a variable and then compare it with the actual input (and break the while loop if they're equal)
Try this:
int last_input = 0;
int input = 0;
int total = 0;
int update = 0;
Scanner inputDevice = new Scanner(System.in);
do
{
System.out.println("Enter any number");
input = inputDevice.nextInt();
total = total + input;
if(last_input == input)
break;
last_input = input;
}while(input != 0); // Or How would i insert a second parameter that stops the loop when a number is entered twice in a row?
System.out.println("The sum of the numbers is " + total);
This is fairly simple and you can do it with a "normal" while loop, e.g. by replacing the do-while statement with
while (true) {
System.out.println("Enter any number");
input = inputDevice.nextInt();
total = total + input;
if ((input == 0) || (input == update)) {
break; // Exit the loop
} else {
update = input; // Remember the last value
}
}
The above example reuses the update variable which does not seem to be used for anything else. If it is needed for another purpose, it can of course be replaced with another variable, declared in the same area with input.
int prevInput = 0;
bool bFirstRun = true
do
{
System.out.println("Enter any number");
if(!bFirstRun)
{
prevInput = input
}
input = inputDevice.nextInt();
bFirstRun = false;
total = total + input;
if(prevInput == input)
break;
}while((input != 0);
I would add a prevInput parameter as above and a boolean to check if its the first time through the loop. If it is then dont check the previous input, if its not the first time through then check the input to the previous (after it was added to the total) and if its the same then break from the loop.
Here... try this. It's simpler
int num1 = 0, num2 = 0, total = 0;
do {
num2 = num1;
System.out.println("Enter any number");
num1 = inputDevice.nextInt();
total += num1;
System.out.println("The sum of the numbers is " + total);
} while (num1 != num2 && num1 != 0);

Categories