Trying to make a simple loop work [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to write a code that asks the user to enter a 2 digit number. In case the user enters anything but a two digit number the program is supposed to ask the user to reenter the number. I came up with a code that uses a while loop. The code however does not work. Any help would be greatly appreciated. Thank you very much
This is the code I come up with :
import java.util.Scanner;
class Pelindrone {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println(" Enter 2 digit number");
num = input.nextInt();
while(num < 10) {
System.out.println("Enter 2 digit number");
num = input.nextInt();
while(num > 99) {
System.out.println("Enter 2 digit number");
num = input.nextInt();
}
}
}
}

You may try this... Just copy my entire main method and replace with yours.
You only need few lines of code to do the job.
Assuming you just want to validate an input to ensure it is only 2 digits. Without using an advance stuff in java, you may do it this way.
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int num;
do
{
System.out.print("Enter a 2 digit number");
num = nextInt();
}while (num > 99 || num <10);
}
This is good enough for the whole thing to work. Trust me.
You don't need nested loops to do that simple task. Only use nested loops when you really have the needs. You can just combine multiple conditions in one statement and place inside the loop.
As for why your codes didn't work well
That is because of the condition in your outer while-loop. It will only run when user enters a number less than 10. But if user enters anything more than 10 (2,3,4,5,6,n digits), Your outer while-loop (for validation) won't run at all.

Your code runs fine if you initially give it a value that is < 10 because then it has a chance to enter the first while loop. I've check it in Ideone here for the consecutive inputs {-5, 0, 1, 9, 100, 1001, 50}, and the code ends at 50 as expected.
The problem occurs if your first value is > 10 because then it will completely skip all of the inner while loops. This means that you are only guaranteed the first value is > 10 but not < 100. I've checked this here using input of {100, 1001, 50} the code ends on 100 even though it should end on 50.
To get this to work, you need to check both conditional statements at the same time (num < 10 || num > 99). In addition, I would suggest removing the code duplication by using a do-while structure. The do-while checks it's conditional statement after each run. This will allow you to remove your initialization statement. The code is below (see the Ideone here).
Scanner input = new Scanner(System.in);
int num;
do{
System.out.println("Enter 2 digit number");
num = input.nextInt();
} while(num < 10 || num > 99);
System.out.print("Your number is:" + num); // guaranteed that 10 <= num <= 99

The only reason this doesn't work is because when you enter a three digit number, it never gets to the inner while loop.
You can just simply have one while loop that check for either condition (less than 2 or more than 2):
import java.util.Scanner;
class Pelindrone {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println(" Enter 2 digit number");
num = input.nextInt();
while(num < 10 || num > 99) {
System.out.println("Enter 2 digit number");
num = input.nextInt();
}
}
}

If you enter more that 2 digits, which you might want to say by does not work, The first while condition does not catch and the program terminates. You need to catch that case in the first while too instead of the redundant inner one.
class Pelindrone {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println(" Enter 2 digit number");
num = input.nextInt();
while(num < 10 || num > 99) {
System.out.println("Enter 2 digit number");
num = input.nextInt();
}
input.close();
}
}

Related

While loop ignoring my parameters. Basic below 10 above zero

Hey guys just looking over some past assignments and i cant figure out why my while loop wont work. I need to take a input and enter a number between 1 and 10. The problem is the while loop only validates entries outside the parameters
int n;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter number 1&10");
n = sc.nextInt();
}
while (n>=1 && n<=10);
System.out.print("Validated number = "+ n);
Your condition is saying "Keep iterating while the value is in the range we want." Surely you want to keep asking the user for more input while the value is outside the range you want:
do {
System.out.print("Enter number 1&10");
n = sc.nextInt();
} while (n < 1 || n > 10);
Always think about what the condition is intended to represent, and remember that the loop will keep going if the condition is true.

Please check my code i wanted to make use of while where the condition must stop when user enter 0 in first input

Please check my code actually I wanted to try the while looping condition and if the user enters 0 for 1st number(n1) it must get out of the loop or else continue the calculation.
class Test{
public static void main(String []args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter two numbers:");
float n1=sc.nextFloat();
float n2=sc,nextFloat();
float ans1=0;
float ans2=0;
float ans3=0;
int count=0;
while(n1!=0){
ans1=n1+n2;
ans2=n1*n2;
count++;
}
ans3=ans1/ans2;
System.out.println("Answer is "+ans3);
}
}
Actual output:
Enter the number
2.0
3.0
4.0
0
Answer is infinity
Expected Output:
Enter the number
2.0
3.0
Answer is 0.83
Enter the number
4.0
5.0
Answer is 0.45
Enter the number
0
You can simplify your code greatly by moving everything into the loop. You can then put an if condition that breaks out of the loop if n1 is 0 and change the loop to an infinite loop until break is called.
Scanner sc=new Scanner(System.in);
while (true){
System.out.println("Enter two numbers (0 to quit):");
float n1=sc.nextFloat();
if (n1 == 0){
break; //New part of the code
}
float n2=sc.nextFloat();
float ans1=n1+n2;
float ans2=n1*n2;
float ans3=ans1 / ans2;
System.out.println("Answer is "+ans3);
}
This way 0 will never be used in the calculation and infinity will never print since you won't divide by 0.
Example Run:
Enter two numbers (0 to quit):
1 4
Answer is 1.25
Enter two numbers (0 to quit):
2 3
Answer is 0.8333333
Enter two numbers (0 to quit):
0
While this is a very simple problem, and I hope that you are able to solve it yourself, here I try to explain the problem to you and suggest a solution:
You want your input to be repeated until 0 is entered. You already know the concept of the while loop, as you can see. You can now use it to repeat your entire input and calculation until the user enters 0:
Scanner sc =new Scanner(System.in);
float n1 = 1;
while(n1 != 0){
System.out.println("Enter two numbers:");
[...]
}
Go through your program line by line from top to bottom to understand, what you are doing: 1. Create a scanner, 2. Define n1 = 1, 3. Repeat the following part as long as n1 != 0 ...
Then, as you mentioned, you want your executable to terminate instantly when n1 = 0, not just at the end of the code in the while loop.
For this purpose, you can use the break condition: Its jumping directly to the end of the loop, in your case, the end of your code.
I also want you to know the continue command which is directly going to the next iteration of the loop. This is for example helpful if someone enters invalid data.
You could use it the following:
Scanner sc=new Scanner(System.in);
float n1 = 1;
while(n1 != 0){ //loop until n1 == 0
System.out.println("Enter two numbers:");
n1=sc.nextFloat();
if(n1 == 0){ //if n1 equals 0
break; // goes to the end of the loop
}
float n2=sc.nextFloat();
if(n2 == 0){ //division by zero
System.out.println("Division by zero, try again!");
continue; //goes to the beginning of the loop again
}
float ans1=0;
float ans2=0;
float ans3=0;
int count=0;
ans1=n1+n2;
ans2=n1*n2;
count++;
ans3=ans1/ans2;
System.out.println("Answer is "+ans3);
}
You need to take your input inside of your while loop condition. This is because unless the user enters their first number as zero, your loop will run forever. Also you should do some sort of error checking for n2, since that can also not be zero. If n2 is zero, then ans2 is zero. Then ans3 will throw a divide by zero error. It should also be noted that you have an error declaring n2 in your original code due to using a sc,nextFloat() in stead of sc.nextFloat()
Here is some code to demonstrate what I think you are trying to accomplish.
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter two numbers:");
float n1=sc.nextFloat();
float n2=1;
float ans1=0;
float ans2=0;
float ans3=0;
int count=0;
while(n1!=0)
{
n2=sc.nextFloat();
while(n2 == 0)
{
System.out.println("Second number can not be zero. Enter a new number");
n2=sc.nextFloat();
}//End while loop for n2==0
ans1=n1+n2;
ans2=n1*n2;
count++;
ans3=ans1/ans2;
System.out.println("Answer is "+ans3);
System.out.println("Enter two numbers:");
n1=sc.nextFloat();
}//End while loop for n1
}//End main
I personally do not like the use of break statements, as I believe it inhibits bad practice/poor design of loop conditions. For most cases, you should be able to set a loop condition to break out without iterating more than necessary. This is mere opinion however, and mine matches what my professors have told me.

What is the proper way to prevent a program from exiting after a user enters wrong input in Java?

The Task
Design and implement an application that reads an integer value and prints out the sum of all EVEN integers between 2 and its input value, inclusive. Print an error message if the input value is less than 2. Prompt accordingly.
Note: the lesson was on while loops, not other loops such as for loop etc
The Issue
I have everything working, however something about how I have written this feels wrong. I currently have a while loop while(programOn) to keep the program running. without this while loop, if the user enters a number < 2, the user is asked to try again, however if the user tries again, the program exits instead of running the new input into the program. So, I created the while loop to force the program open until the user types an acceptable input.
- something about this feels hacky and incorrect i would really appreciate some validation on my method.
public static void main(String[] args){
int inputNumber;
int sum = 0;
boolean programOn = true;
Scanner scan = new Scanner(System.in);
System.out.println("Please Type a number no smaller than 2");
inputNumber = scan.nextInt();
//include the original input to sum
sum = inputNumber;
while(programOn){
if(inputNumber < 2){
System.out.println("you need a number greater than or equal to 2, try again");
inputNumber = scan.nextInt();
sum = inputNumber;
}else{
//from the number chosen divide until you reach 0
while(inputNumber != 0){
//subtract one from the number
inputNumber = (inputNumber - 1);
if((inputNumber % 2 == 0) && (inputNumber != 0)){
System.out.println(inputNumber);
//add the input to the sum
sum += inputNumber;
}
}
System.out.println("The sum is " + sum);
programOn = false;
}
}
}
That's because the validation is done by an if condition. What you need here is a while loop that keeps asking for inputs as long as user's input is less than 2, below is the code snippet that does this:
Scanner scan = new Scanner(System.in);
System.out.println("Please Type a number no smaller than 2");
int inputNumber = scan.nextInt();
while(inputNumber < 2){
System.out.println("you need a number greater than or equal to 2, try again");
inputNumber = scan.nextInt();
}
System.out.println(inputNumber);

java while loop won't print the text after a the stopping condition [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I just started studying Java and I'm required to use while to decided how many players can be goalkeepers based on their number. The loop is supposed to stop after the user entered 0 and print the counted number of players that can be goalkeepers.
public class Q3_201303719 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int num; int count=0;
System.out.println("Enter the players' numbers");
num = input.nextInt();
while ((num != 0) && (num < 31) && (num%2==0) || (num%3==0))
count++;
System.out.println(count+ " players can be goalkeepers.\n");
// Above line should be printed once the user enter 0, but in my case it won't
// print and keeps asking the user to enter a number.
}
}
From the question it is difficult to understand what it is you are trying to achieve. However, we can try to help you understand the code as it is written.
The while loop is currently written as:
while ((num != 0) && (num < 31) && (num%2==0) || (num%3==0))
This could be rewritten as the following and it would not make any difference:
while (num != 0 && num < 31 && num%2==0 || num%3==0)
The additional parenthesis that you included are not required.
In Java the operator precedence is && before ||. This means that the && operators will be evaluated first, followed by the ||. Therefore, the above statement could therefore be rewritten as the following and it would not make any difference:
while ((num != 0 && num < 31 && num%2==0) || num%3==0)
However, it may make the code a little easier to understand.
So when the code executes the following occurs:
The count variable is initialised to 0.
A value is retrieved and stored in the variable num. Lets say that this value is 10.
The while statement is evaluated for the first time:
num != 0 is true as 10 != 0.
num < 31 is true as 10 is less than 31.
num%2==0 is true as 10 divided by 2 is 5 and leaves a remainder of 0.
As these all evaluate to true, the OR part (num%3==0) is not evaluated as it is not neccessary. See short circuit evaluation (http://users.drew.edu/bburd/JavaForDummies4/ShortCircuitEval.pdf).
The count is incremented to 1.
The loop executes again for the second time. num is still 10.
num != 0 is true as 10 != 0.
num < 31 is true as 10 is less than 31.
num%2==0 is true as 10 divided by 2 is 5 and leaves a remainder of 0.
The count is incremented to 2.
And so on... in an infinite loop.
If the variable num was instead set to 9. The loop would evaluate as follows:
num != 0 is true as 9 != 0.
num < 31 is true as 9 is less than 31.
num%2==0 is false as 9 divided by 2 is 4 and leaves a remainder of 1.
Therefore, now the || part is evaluted:
num%3==0 is true as 9 divided by 3 is 3 and leaves a remainder of 0.
Again, this would result in an infinite loop.
If the variable num was instead 0:
num != 0 is false
As the first num!=0 is false, the num<31 and num%2==0 parts are not evaluated as their results would not make any difference.
The num%3==0 is then evaluated:
num%3==0 is true as 0 divided by 3 leaves a remainder of 0.
Again, this would result in an infinite loop.
I hope that this may help to clarify your understanding and allow you to correct the code appropriately.
how many players' numbers do you have to input?
you have a while loop that depends on num value, but you never change the num value. that will end up in endless loop...
if you have more players, create a for loop to enter the numbers, store the numbers in an array or an arraylist and if you use the while loop, use it so that it depends on a value that you change inside the loop. otherwise it will loop forever.
do{
System.out.println("Enter the players' numbers");
num = input.nextInt();
count++;
}while(num!=0);
your code with this should look like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
int count = 0;
do {
System.out.println("Enter the players' numbers");
num = input.nextInt();
count++;
} while (num != 0);
System.out.println(count + " players can be goalkeepers.\n");
// Above line should be printed once the user enter 0, but in my case it
// won't
// print and keeps asking the user to enter a number.
}
If you can't use a do-while-loop as Ubica suggested, then you need to work your way around it:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num=2; // you need to initialize num with a value, that allows you to go inside the while loop at least once
int count = 0;
while((num != 0) && (num < 31) && (num % 2 == 0) || (num % 3 == 0)) {
System.out.println("Enter the players' numbers");
num = input.nextInt(); // user input is here inside the loop
count++; // your count will count every valid input + the user input that ends the loop
}
count--; // if your user entered 0 to exit the loop, count would have still incremented, so you need do subtract one again
System.out.println(count + " players can be goalkeepers.\n");
}
As I commented in the code, first you initialize num with a dummy value, that allows you to enter the loop at least once. Then you listen to the users input and count the loop iterations. But since the loop will execute at least once (even though your user might enter 0 right away to exit the loop) your count would be one higher than the actual number of valid inputs. So you have to subtract that 1 from your count again.
EDIT
I forgot to mention: your loop will not stop when the user enters 0 because
(num % 3 == 0) // is true with num=0
so when the user enters 0 the while condition will evaluate like this:
while( false && true && true || true )
while( false || true )
while( true )
The bracketing for the loop should fix this problem.
You need braces surrounding your while loop block. As a general rule, it is best to overuse braces rather than under-use them.
Your code should look like:
package q3_201303719;
import java.util.Scanner;
public class Q3_201303719 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int num; int count=0;
System.out.println("Enter the players' numbers");
num = input.nextInt();
while((num != 0) && (num < 31)&& (num%2==0)|| (num%3==0)) {
count++;
}
// The braces added above are required for the while loop and will keep your program
// from not outputting your results.
System.out.println(count+ " players can be goalkeepers.\n");
}
}
Best of luck and happy coding. :)
Your code isn't making sense.
1st : The While loop is not modifying the "num" value, resulting in
infinite loop if entered.
2nd : What is the code supposed to do? It is really hard to tell from what you show.
I think placing while loop upper could help you, but still code makes no much sense
public class Q3_201303719 {
public static void main(String[] args) {
int num = 0; int count=0;
while((num != 0) && (num < 31)&& (num%2==0)|| (num%3==0)) {
Scanner input = new Scanner (System.in);
System.out.println("Enter the players' numbers");
num = input.nextInt();
count++;
}
System.out.println(count+ " players can be goalkeepers.\n");
// Above line should be printed once the user enter 0, but in my case it won't
// print and keeps asking the user to enter a number.
}
}
Edit :
This problem occurred because you didn't follow a really simple rule : think before coding.
For this exercise you need to think about what your code should be doing, and then write the code for it. Coding is just a language, if you know what you want to write then it is easier. Here you obviously don't really know what you wanna do, and as you are new with development it was likely that you get stucked

Unsure what the issue is

I'm really new to this whole programming thing, and I'm trying to wrap my head around why the loop ends abruptly and does not continue to the final if statement. Can you guys help me figure out whats wrong?
import java.util.Scanner;
public class FunnyAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many values to read? ");
int top = in.nextInt();
System.out.print("Enter Value: ");
int one = in.nextInt();
int number = 1;
int sum = 0;
sum = sum + one;
while (number <= top) {
if (one % 6 != 0 && one % 17 != 0) {
System.out.print("Enter Value: ");
one = in.nextInt();
number++;
} else if (one % 6 == 0 && one % 17 == 0) {
System.out.print("Enter Value: ");
one = in.nextInt();
number++;
}
}
if (sum / top != 0) {
System.out.print("Average: " + sum / top);
}
System.out.print("None Divisible");
}
}
The final if() condition executes if you give the right input values. I ran your code and gave the below inputs to execute the final if() statement.
How many values to read? 1
Enter Value: 1
Enter Value: 1
Average: 1None Divisible
I dont understand what are you trying in the code, but there are many things missing like i assume you want to capture the sum of the input numbers, but sum is not used in the while loop.
Looks like you end up in the non-present else case (within the while loop). Consequently, number isn't increased and you are stuck in the while loop.
Try reading one within the while loop. This way the user will be prompted to enter a new number in each loop.
Otherwise you will be stuck in the while loop once the user enters a number that isn't conform with your checks.

Categories