While loop ignoring my parameters. Basic below 10 above zero - java

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.

Related

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.

Java program infinite loop in sum of even integers

I am creating a program that prints the sum of the even numbers from a range of 0 to the number that the user entered. For example, if the user entered the number 20, the program would calculate the sum of all of the even numbers between 0 and 20.
When I tested the program out with the number 10, it worked. But I tried using a different number, 35, and it was just stuck in an infinite loop. I would appreciate any and all help. The code will be posted below:
(Edit) Thanks for the feedback everyone! After talking with a friend, we realized that the solution is actually pretty simple. We were just making it complicated. Still, thanks for all of the suggestions.
//**************************************************************
// Prints the sum of the even numbers within a range of 0
// and the integer that the user enters.
//
// #me
// #version_1.0_11.7.17
//**************************************************************
import java.util.Scanner;
public class EvenNumbersSum
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int user_num = 2; // variable that stores the user's number
int sum; // stores the sum of the needed values
System.out.print("Enter an integer greater than or equal to, 2: "); // prompt user for input
user_num = input.nextInt();
// checks to see if the value entered is valid or not.
while (user_num < 2)
{
System.out.println("Invalid entry. Must enter an integer greater than or equal to, 2.\n");
System.out.print("Enter an integer greater than or equal to, 2: ");
user_num = input.nextInt();
}
// starts adding the values
for (sum = 0; sum <= user_num;)
{
if (user_num % 2 == 0) // checks if the number is even
sum+=user_num; // add the number to sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
System.out.println(); // extra line for cleanliness
System.out.printf("The sum of the even numbers between 0 and %d is %d.", user_num, sum); // prints the result
}
}
Why are you writing loop for this, there are efficient way to do it.
Sum of numbers between 1-N = (N(N+1))/2
Sum of even numbers between 1-N = (N(N+2))/4
where N = user given input number till which you would like to add even numbers
NOTE: you can add validation on input number that it’s even by (n%2 == 0) and return error if it’s not
The variable you have used in condition (i.e. sum & user_num) no one changes in case of odd number and your code stuck in never-ending loop.
You should use counter variable ( e.g. i from 1 to user_num) and use that number in the condition. Example:
// starts adding the values
sum = 0;
for (int i = 0; i <= user_num; i++)
{
if (i % 2 == 0) // checks if the number is even
sum+=i; // add the number to sum
}
Your for loop should be like this.
int total_sum = 0;
for (int sum = 0; sum <= user_num; sum++)
{
if (sum % 2 == 0) // checks if the number is even
total_sum+=sum; // add the number to total sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
// note print total sum
System.out.println(totalsum);
your initial program just kept on checking entered number is even or odd.
And the entered number to sum.
So sum was always double of the entered number is even.
If entered number is odd it would go to infinite loop as entered_num(odd) % 2 == 0 always false and execute else statement.

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

Array guessing game

I'm a java noob and for a class assignment I had to create a guessing game. I have not finished the game yet but I want some advice when it comes to simplifying my array for the keyboard input. I was able to create the array for a random "5" digit number but I don't know how to simplify the array for keyboard input in the same manner for the random numbers.
Here is the part that i need advice on:
Scanner input = new Scanner(System.in);
Random number = new Random();
int x,y,z,a,b;
x=number.nextInt(9); //The 9 limits the randomized number to values between between -1 & 10
y=number.nextInt(9);
z=number.nextInt(9);
a=number.nextInt(9);
b=number.nextInt(9);
int secretNum[] = {x,y,z,a,b};
int numOfGuess = 3;
boolean win = false;
System.out.println("Try to guess the five digit number");
{
while (win || numOfGuess > 0)
{
int guess[]=new int[5];
guess[0]=input.nextInt(9);
guess[1]=input.nextInt(9);
guess[2]=input.nextInt(9);
guess[3]=input.nextInt(9);
guess[4]=input.nextInt(9);
numOfGuess--;
First, you can simplify the number generation from your complicated method to simply:
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
If you set max = 99999 and min = 10000, it will give you a random 5 digit number.
For accepting user input, you're far better of using
Scanner scan = new Scanner(System.in);
guess = scan.nextLine();
Then use an if statement to see if the number is within the 5 digit constraints.
In terms of the loop, the comment suggested using a for loop instead of a while loop. It would be far better imo to follow his advice. i.e.
for (int i=0;i<maxGuesses;i++)
Listen for input
If correct, set won=1 break
else do nothing
end for loop
if won=1 Print you won
Else print You suck at guessing 5 digit numbers
Simple code is usually the best way to go:
In pseudocode:
secret = 10000 + number.nextInt(90000);
for (int i = 0; i < numOfGuess; i++) {
read guess (a single int)
if guess == secret then user wins (and exit)
}
user loses

java program outputting even/odd numbers

My task is to write a java program that first asks the user how many numbers will be inputted, then outputs how many odd and even numbers that were entered. It is restricted to ints 0-100. My question is: What am I missing in my code?
import java.util.Scanner;
public class Clancy_Lab_06_03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
n++;
}
int odd = 0;
int even = 0;
while (n >= 0 || n <= 100) {
n = input.nextInt();
if (n % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println(even + "even" + odd + "odd");
}
}
Second while loop is infinite. Relplace it with something like this:
for (int i = 0; i < n; i++) {
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also I don't understand why are you incrementing n in first loop. For example when you will first give -5, you will be asked to re-enter the number. Then you type -1, but it gets incremented and in fact program processes 0, altough user typed -1. In my opinion it is not how it suppose to work and you should just remove this n++.
As you asked in comment - the same using while loop:
while(n > 0) {
n--;
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also it is good idea to close input when you no longer need it (for example at the end of main method)
input.close();
You had two issues - first you were incrementing n in the first loop, rather than waiting for the user to enter a valid number.
In the second loop, you weren't comparing the number of entries the user WANTED to make with the number they HAD made - you were over-writing the former with the new number.
This version should work, although I've not tested it as I don't have java on this machine.
Note that we now sit and wait for both inputs, and use different variable names for the "how many numbers will you enter" (n) and "what is the next number you wish to enter" (num) variables? Along with a new variable i to keep track of how many numbers the user has entered.
import java.util.Scanner;
public class Clancy_Lab_06_03
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int n;
System.out.println ("How many numbers will be entered?");
n = input.nextInt();
//Wait for a valid input
while (n < 0 || n > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
//Setup variables for the loop
int odd = 0;
int even = 0;
int num;
//Keep counting up until we hit n (where n is the number of entries the user just said they want to make)
for(int i = 0; i < n; i++)
{
//Changed this, because you were over-writing n (remember, n is the number of entries the user wants to make)
//Get a new input
while (num < 0 || num > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
num = input.nextInt();
}
//Check whether the user's input is even or odd
if (num % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println(even + " even. " + odd + " odd.");
}
}
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
System.out.println("Enter an Integer number:");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
My suggestion to you is to have a clear separation of your requirements. From your post, you indicate you need to prompt the user for two distinct data items:
How many numbers will be entered (count)
The values to be analyzed
It is a good practice, especially when you are learning, to use meaningful names for your variables. You are using 'n' for a variable name, then reusing it for different purposes during execution. For you, it is obvious it was difficult to figure out what was 'n' at a particular part of the program.
Scanner input = new Scanner (System.in);
int count;
System.out.println ("How many numbers will be entered?");
count = input.nextInt();
//Wait for a valid input
while (count < 1 || count > 100)
{
System.out.println ("ERROR! Valid range 1-100. RE-Enter:");
count = input.nextInt();
}
Additionally, a count of zero should not be valid. It does not make sense to run a program to evaluate zero values (don't bother a program that does nothing). I believe the lowest count should be one instead.
int odd = 0;
int even = 0;
int value;
do
{
System.out.print("Enter a number between 0 and 100: ");
value = input.nextInt();
while (value < 0 || value > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
value = input.nextInt();
}
if (value % 2 == 0)
{
even++;
}
else
{
odd++;
}
count--; // decrement count to escape loop
} while (count > 0);
System.out.println(even + " even. " + odd + " odd.");
This example uses a do/while loop because in this case, it is OK to enter the loop at least once. This is because you do not allow the user to enter an invalid number of iterations in the first part of the program. I use that count variable directly for loop control (by decrementing its value down to 0), rather than creating another variable for loop control (for instance , 'i').
Another thing, slightly off topic, is that your requirements were not clear. You only indicated that the value was bounded to (inclusive) values between 0 and 100. However, how many times you needed to repeat the evaluation was not really clear. Most people assume 100 was also the upper bound for your counter variable. Because the requirement is not clear, checking a value greater or equal to 1 for the count might be valid, although highly improbable (you don't really want to repeat a million times).
Lastly, you have to pay attention to AND and OR logic in your code. As it was indicated, your second while loop:
while (n >= 0 || n <= 100) {}
Is infinite. Because an OR evaluation only needs one part to evaluate to TRUE, any number entered will allow the loop to continue. Obviously, the intent was not allow values greater than 100. However, entering 150 allows the loop to continue because 150 >= 0. Likewise, -90 also allows the loop to continue because -90 <= 100. This is when pseudocode helps when you are learning. You wanted to express "a VALUE between lower_limit AND upper_limit." If you reverse the logic to evaluate values outside the limit, then you can say " value below lower_limit OR above upper_limit." These pseudocode expressions are very helpful determining which logical operator you need.
I also took the liberty to add a message to prompt the user for a value. Your program expects the user to enter two numbers (count and value) but only one prompt message is provided; unless they enter an out of range value.
extract even numbers from arrayList
ArrayList numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
numberList.stream().filter(i -> i % 2 == 0).forEach(System.out::println);

Categories