Reading user input - java

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++;
}

Related

while loop incrementing an extra time

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.

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;
}
}

Java: RuntimeException when run on spoj.com

Following is the question for prime number generator problem (from spoj.com):
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input :
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output :
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example :
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Following is my code for the same:
package competitivecoding;
import java.util.Scanner;
class problem2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Scanner st = new Scanner(System.in);
int t = sc.nextInt(); // inputs the "no." of lines that users want to enter
int a,b, flag, count;
String line[] = new String[t];
String[] number=new String[2];
for(int i=0; i<t; i++){
line[i] =st.nextLine();
}
for(count=0; count<t; count++){
number = line[count].split(" ");
a = Integer.parseInt(number[0]);
b = Integer.parseInt(number[1]);
for(int i=a; i<=b; i++){
for(int j=2; j<=i; j++){
if(i%j==0){
if(i==j)
System.out.println(i);
else break;
}
}
}
System.out.println();
}
}
}
Error: The code when submitted, produces RuntimeException on spoj.com, although it works completely fine on my system.
package abc;
import java.util.Scanner;
class problem2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int a,b, flag, count;
String line[] = new String[t];
String[] number=new String[10];
for(int i=0; i<t; i++){
line[i] =sc.nextLine();
}
for(count=0; count<t; count++){
number = line[count].split(" ");}
a = Integer.parseInt(number[0]);
b = Integer.parseInt(number[1]);
for(int i=a; i<=b; i++){
for(int j=2; j<=i; j++){
if(i%j==0){
if(i==j)
System.out.println(i);
else break;
}
}
}
}
}
//try this
Always handle the exception that can be raised (ideally, any exceptional behaviour that you can recover from, accoding to the Oracle documentation for Exception) and never consider user input as safe:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = 2;
try {
/* for each line */
for (int i = 0; i < t; i++) {
/* read the line */
String line = br.readLine();
/* split the line */
String[] numbers = line.split(" ");
if (numbers.length != 2)
throw new ArrayIndexOutOfBoundsException();
/* parse values */
int min = Integer.parseInt(numbers[0]);
int max = Integer.parseInt(numbers[1]);
/* do your check */
__find_prime_numbers__
}
}
catch (NumberFormatException ex) {
/* notice the user -> input format isn't correct, for example: "1 m" */
}
catch (ArrayIndexOutOfBoundsException ex) {
/* notice the user -> input format isn't correct, for example: "1 " or "1 2 3" */
}
It works for me. Print the error so we have more info.
You can also do Scanner.nextInt().
Things like multiple spaces , tabs can mess stuff
Are you using sc.nextInt() before the first sc.nextLine()? because if that's the case, you could have a '\n' character in the buffer after using it. So when you use nextLine() for the first time, you actually get the '\n' character instead of the next line. And when you try to parse to integer it fails.
See here Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
If this is the case, the solution is simple. Just fire a call sc.nextLine() that does nothing except to 'eat' that character from the buffer.

2 or more digit numbers with delimiters in java

I have this basic program that works pretty well when entering single digit numbers. But when calculating an expression with multiple digits, like 1337 - 456 + 32, the program doesn't move on...it acts likes I did nothing.
It doesn't freeze or output an error message, it just stops.
here's the code:
import java.io.*;
import java.util.*;
public class Tester {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter number: ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*");
int sum = 0;
int temp = 0;
int intbefore = 0;
if (sc.hasNext("\\-")) {
sc.next();
if (sc.hasNextInt()) {
intbefore = sc.nextInt();
int temper = intbefore * 2;
intbefore = intbefore - temper;
}
}
if (sc.hasNextInt()) {
intbefore = sc.nextInt(); //now its at the sign (intbefore = 5)
}
sum = intbefore;
while (sc.hasNext()) {
if(sc.hasNext("\\+")) { //does it have a plus sign?
sc.next(); //if yes, move on (now at the number)
System.out.println("got to the next();");
if(sc.hasNextInt()) { //if there's a number
temp = sc.nextInt();
sum = sum + temp; //add it by the sum (0) and the sum of (5) and (4)
System.out.println("added " + sum);
}
}
if(sc.hasNext("\\-")) {
sc.next();
System.out.println("got to the next();");
if (sc.hasNextInt()) {
temp = sc.nextInt();
sum = sum - temp; //intbefore - temp == 11
System.out.println("intbefore: " + intbefore + " temp: " + temp);
System.out.println("subtracted " + sum); // subtracted by 11
}
}
}
System.out.println("Sum is: " + sum);
}
}
Help with why this happens and what to do to fix it?
(I'm using netbeans if that helps)
Also, I'm assuming that the input has a space between each number Ex: 123 + -23 - 5
I tried to execute your code and this is what i found.
Suppose your input was 12+1.
Not sc.hasNextInt() will give you 1 which you are assigning to intbefore.
Next the while loop in your code is going to infinite loop cos sc.hasNext() will always be true (and returning 2 in this case ) and it doesn't match the two if conditions inside the while loop thus making your code run in infinite loop. Now go ahead and work on that. All the best.
Try to change the dilimeter as "\\s+" in the first place or just use the default one

Categories

Resources