while loop incrementing an extra time - java

The below while loop runs an extra time. I am trying to perform a user input that accepts 10 valid numbers from the user and prints their sum. However, the while loop executes an extra time and asks for the 11th input.
import java.util.Scanner;
class userInput{
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i++;
System.out.println("Enter number " + "#" +i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
}else{
System.out.println("Invalid Input");
}
}
System.out.println("The sum of your entered numbers are = " + sum);
}
}

In addition to those great comments, you should probably only increment "i" if you get a VALID input:
while(i <= 10) {
System.out.print("Enter number " + "#" +i + ": ");
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
i++;
}else{
System.out.println("Invalid Input");
sc.next();
}
}
Note that when you have a bad input you need to get rid of it with "sc.next()".

First - make sure you're formatted correctly.
(I've indented your loops, moved your output into the main class, fixed up some curly brackets/loop endings).
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i++;
System.out.println("Enter number " + "#" +i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
}
else{
System.out.println("Invalid Input");
}
}
System.out.println("The sum of your entered numbers are = " + sum);
}
Alright - so running the code, I've found there are the correct amount of times asked, but the input prompt is displaying the wrong number with the first input prompt starting on 2, the last one on 11.
The reason for this is the i++ runs before asking for an input, thus it counts up before outputting.
This can easily be fixed by moving said i++ to just underneath the else clause - as follows:
else{
System.out.println("Invalid Input");
}
i++
}

the main problem here is that you're increasing the variable at the start of your while loop. If that's what you're looking for then that's fine, but if you want to stop the loop when it hits 10 you'll need to have it like while(i < 10) if the i++ were at the end of the loop, then you could do while(i <= 10)
Ex:
i = 0;
while(i < 10){
i++;
//code here
}
this will make the code that uses i use the values between 1 and 10. using <= will use the values between 1 and 11.
another example:
i = 0;
while(i < 10){
//code here
i++;
}
this will make the code that uses i use the values between 0 and 9. using <= will use the values between 0 and 10.
another way people do an incremental loop is doing a for loop rather than a while loop
this would look like:
for(int i = 0; i < 10; i++){
//code here
}
this also allows you to create a variable that will only be inside the loop, so rather than making it at the beginning of the method or before the loop, you could make it inside the for loop. This is not good if the variable is used elsewhere though.

Related

How do you check if inputted array values are the same?

My program is supposed to make sure each value the user enters is between 10-100. The value is then stored in the array. That part works fine. The other condition is that the value the user enters has to be different from all the other arrays. ie...array[0]=20 so all of the other arrays can no longer equal to be set to 20. I've been trying to solve this but I'm just not sure where to go. I tried setting statements after my while(userInput < 10 || userInput > 100) to check for any repeats and that worked. The problem was then the user could enter values less than 10 and greater than 100. Any help would be greatly appreciated!
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
for(int x = 0; x < array.length; x++)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
while(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100: ");
userInput = input.nextInt();
}
array[x] = userInput;
System.out.println(array[x]);
counter++;
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
}
You should get rid of the for and second while loop, and check if the value entered is in the desired range.
If it is, you verify for duplicates, store it in the array and increment the counter. If it’s not, you show the bad input message.
Either way, it continues to ask for an valid input until the counter gets to 5.
I hope it helps!
I changed your logic a little bit, see if you can understand it
(There are better ways of doing this, but I think this is more understandable)
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
if(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100.\n");
}
else {
//This is a valid input, now we have to check whether it is a duplicate
boolean isItDuplicate = false;
for(int i = 0; i < counter; i++)
{
if(userInput == array[i])
{
isItDuplicate = true;
}
}
if(isItDuplicate == true)
{
System.out.print("Please enter a number that is not a duplicate.\n");
}
else
{
array[counter] = userInput;
System.out.println(array[counter]);
counter++;
}
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
Don't use variable counter when var x does the same thing for you.
Don't use nested loops when the limiting condition of both loops need to be checked together in each iteration. Merge those loops into one wherever possible.
First of all, get rid of your nested loops. They're redundant. Let's look at your problem's specification. Your input needs to fulfill 3 requirements:
Be greater than or equal to 10
Be less than or equal to 100
Be a unique element inside the array
The first two conditions are simple enough to check. For the final condition, you need to search the values inside the array and see if there are any matches to your input. If so, the input is invalid. A simple way to approach this is to check every member of the array and to stop if a duplicate is found. There are better, more efficient ways to do this. Don't be afraid to search the internet to learn a searching algorithm. Below is a simple solution to your problem. It's far from ideal or efficient, but it's easy enough for a beginner to understand.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
int userInput;
while(counter < 5) {
System.out.print("Enter a number between 10 & 100: ");
userInput = in.nextInt();
if( (userInput >= 10 && userInput <= 100) && !searchDuplicates(array, userInput) ) {
array[counter] = userInput;
counter++;
} else {
System.out.println("Invalid value entered");
}
}
for(int i = 0; i < array.length; i++)
System.out.println("Value " + (i + 1) + ": " + array[i]);
}
private static boolean searchDuplicates(int[] array, int input) {
for(int i = 0; i < array.length; i++)
if(array[i] == input)
return true;
return false;
}
}

Java scanner count numbers that are in an interval

I'm new with java and i have to write a code that asks the user two numbers an interval. Then the user must introduce n numbers and the program must return how many numbers belong to that interval.
I've tried to do this and this is what i have:
import java.util.*;
public class NumsInter {
public static void main(String[] args) {
Scanner sc;
int a,b,nums,count;
sc = new Scanner (System.in);
System.out.print ("Write two numbers a and b(a<=b)(interval): ");
a=sc.nextInt();
b=sc.nextInt();
count=0;
System.out.println("write a number: ");
while(sc.hasNextInt()){
nums=sc.nextInt();
if (a<=nums && nums>=b){
count= count + 1;
} else {
count= count;
}
}
System.out.println(count +" numbers are included in ("+a+","+b+")");
}
}
Example: If the user writes 2 and 6, and then 4,4,3,1 the output should be 3.
As I am a newbie i don't know how can i do this the good way, can someoen help?
PD: How can i break the loop so i can get the output?
Thank You!
Try something like this
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter the numbers you want to test, enter 'stop' to stop");
boolean userInput = true;
while(input.hasNextInt() && userInput){
if(input.hasNext("stop")){userInput = false;}
numbers.add(input.nextInt());
}
Where you have a loop that checks if there is a next int while at the same time checking to see if the user is done or not.
And them something like this to print your answer
for(int i =0; i < numbers.size(); i++){
testNum = numbers.get(i);
if(testNum > lowerLimit && testNum < upperLimit){
count++;
}
}
System.out.println(count + " valid numbers have been entered!");
take an int [] no_between_max&min after take the input from user and store in this array. after that take a for loop and compare the value of array with max and min ant increase the count variable.
int noOfItem=sc.nextInt();
int [] no_between_max_min = new int[noOfItem];
for(int i=0;i<noOfItem;i++){
no_between_max_min[i]=sc.nextInt();
}
for(int i=0;i<no_between_max_min.length;i++){
if(no_between_max_min[i]>=a&&no_between_max_min[i]<=b){
count++;
}
}

How to put IF statement in given scenario?

I'm a beginner programmer Java:
I want to get 10 values from user and put if statement, if some one enters grade value above 100, it may get "Enter right value < 100"
But i don't want to use any array etc.
When i use the following code, it shows the error message but for 1 wrong value, it calculates other 09 values and don't repeat the wrong value, given if statement skips the wrong
int i, number, total=0;
Scanner sc = new Scanner(System.in);
for (i=1; i<=10; i++)
{ System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100);;
{total = total + number;}
}
int number, total=0;
int i = 1;
Scanner sc = new Scanner(System.in);
while (i<=10)
{
System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100){
total = total + number;
i++;
}else{
System.out.println("invalid value");
}
}
This will work, using a while loop
You just had few typo errors in your code also , to make the for loop more simple you don't need to define i at top just define the i when you need to use the for loop . And its avoid overwrite outside of the for loop .
To make using for loop more professional also considering that maybe sometimes you need to use it for arrays its better to always start the loop with i=0 thats the better practice.
After if(condition) don't need to put any ;
int number, total=0;
Scanner sc = new Scanner(System.in);
for (int i=1; i<=10; i++)
{ System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100){
total = total + number;
}
}

unable to get loop to work properly

import java.util.Random;
import java.util.Scanner;
public class addinggamedowhile
{
public static void main (String[]args)
{
Random r = new Random ();
Scanner s = new Scanner(System.in);
int x = r.nextInt(20)+1;
int y = r.nextInt(20)+1;
int sum = x + y;
int guess;
System.out.println("===========");
System.out.println("Adding Game");
System.out.println("===========");
System.out.println();
int tries = 0;
for (int games = 0; games < 10; games++)
{
do
{
System.out.print (x + " + " + y + " = ");
guess = s.nextInt();
if (guess != sum && tries < 2)
{
System.out.println("Not quite. Try again!");
System.out.println();
tries++;
}
else
System.out.println("Not quite. The answer is " +sum+ ".");
System.out.println();
}
while (guess != sum);
System.out.println("Congratulations. You got it!");
System.out.println();
}
}}
I'm having trouble with this loop. I cannot get the loop to terminate when I want it to. It's supposed to last for only ten "guesses". In addition, when the user gets the question right, my else statement is also executed. The other thing is that once the user gets the question correct, or does not get the question correct in the three times it is allowed, a new set of numbers are supposed to appear. I have not been able to get that to execute properly either. I've tried different things that worked well, but the requirement for the project is to use a do while loop.
How about something like this?
do {
//your code here
} while (guess != sum && tries <= 10);
The loop will keep going until the sum is correct or the number of tries is exhausted. Increment tries by one every time the loop iterates.
Then, after completion (i.e. outside the loop), do a check to see if the guess is the correct sum or if the tries were exhausted and print out the response accordingly.
Alternatively you can use the break keyword when the guess is correct or no more tries. Also, you should probably reset your tries variable inside the outer for loop (so that it get's reset at the beginning f each game).

Reading user input

I'm trying to ask the user to enter any number of numbers up to 5, each number seperated by space.
for example
enter up to 5 numbers : 3 4 5
I'm going to add them in the integer sum and then later divide them by counter
to get the average of these numbers.
However, my loop does not seem to end. What's wrong with my code?
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt());{
counter++;
sum += scan.nextInt();
}
System.out.println(counter);
System.out.println(sum);
You put a ; between while and {, so it loops. Remove it.
Scanner.hasNextInt() does not do what you seem to think it does. It does not tell you whether there is an integer available in already typed input (it does not have any conception of what has "been typed"), but rather whether the input waiting can be read as an integer. If there is no input already waiting, it will block until there is, so your loop is simply sitting there forever, blocking for more input.
What you probably want to do instead is to read a whole line, and then split it explicitly into space-separated parts, and only then parse those as integers. For example, like this:
String input = scan.nextLine();
for(String part : input.split(" "))
sum += Integer.parseInt(part);
Serge Seredenko's answer is also correct, however, but that's another problem.
Everything in your code is fine except the semicolon(;) just after the while loop, of course it will lead to an infinite loop.
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt()){
counter++;
sum += scan.nextInt();
if(counter >=5)
break;
}
System.out.println(counter);
System.out.println(sum);
scan.close();
First, you need to remove ';' located after while(scan.hasNextInt()) and before {; For the ; means the while statement is complete.
Second, when you use your code, you need CTRL + Z to end up your input. By adding
if(counter >=5)
break;
your input will end up when you input 5 numbers.
If you want to read entire line and then do arithmetic operation later then you dont need to have while loop with hasNextInt() method.
I would suggest you to read line then split by space and iterate over string array. Check out code snippet.
package com.gaurangjadia.code.java;
import java.util.Scanner;
public class SO19204901 {
public static void main(String[] args) {
int counter = 0,
sum = 0;
System.out.println("enter up to 5 numbers");
Scanner scan = new Scanner(System.in);
String strInput = scan.nextLine();
String[] arrayNumbers = strInput.split(" ");
for (int i = 0; i < arrayNumbers.length; i++) {
int n;
try {
n = Integer.parseInt(arrayNumbers[i]);
}
catch (NumberFormatException e) {
n = 0;
}
sum = sum + n;
counter++;
}
System.out.println(sum);
}
}
DataInputStream in = new DataInputStream(System.in);
String[]label = {"quiz #","Total","Average"};
int counter = 0;
int theSum = 0;
System.out.print("Enter up to 5 number : ");
String[]tempNum = in.readLine().trim().split("\\s+");
System.out.println();
while (counter <= tempNum.length)
{
if ( counter == tempNum.length)
{
System.out.printf("%10s %12s\n",label[1],label[2]);
counter = 0;
break;
} else {
System.out.printf("%10s",label[0] + (counter+1) );
}
counter++;
}
while(counter <= tempNum.length)
{
if ( counter == tempNum.length)
{System.out.printf("%10d %10.2f\n",theSum,(double)(theSum/counter));
} else
{System.out.printf("%10d",Integer.valueOf(tempNum[counter]));
theSum += Integer.valueOf(tempNum[counter]);
}
counter++;
}

Categories

Resources