Terminating a user input determined Scanner? - java

I wonder if someone could explain why the scanner keeps waiting on input? I have to stop the process on eclipse before the code block executes and I am unsure why the scanner will keep taking input all day. I expect to press enter and for the code to execute after entering X amount of numbers.
public static void main(String[] args){
Scanner aScanner = new Scanner(System.in);
int sum = 0;
System.out.println("Enter Ints : ");
while(aScanner.hasNextInt()){
sum += aScanner.nextInt();
}
System.out.println(sum);
}

if you want the program to take only X amount of numbers, you could have a counter and break the while loop after it has executed X number of times. Alternatively, you could also use a for loop to make things easier.
You could also use Ctrl+Z in eclipse to stop console from waiting for inputs.

The simplest way to solve it is:
Enter the "end of file" marker, by the combination Ctrl + z (Ctrl + d in UNIX, if I'm not wrong).
Another way would be using a centinel value tu finish the while loop:
Scanner aScanner = new Scanner(System.in);
int sum = 0, input = 0;
System.out.println("Enter Ints (-999 to finish input): ");
while ((input = aScanner.nextInt()) != -999) {
sum += input;
}
System.out.println(sum);
so the input will finish when the user enters -999, of course you can change this value.
Note:
The last approach won't work if you expect any integer (including negatives and extrene values) as input.

Related

How to terminate a Scanner while loop that takes input seperated by both whitespace and linebreaks

I'm trying to terminate this Scanner while loop when there is no more input for it to read. The input is two numbers per line separated by a space. The next line contains the same, and so on, for an undisclosed amount of lines. The output should then be the difference of those two numbers.
The input could for example be
10 12
71293781758123 72784
1 12345677654321
Where the output would then be
2
71293781685339
12345677654320
The code works when simply figuring out the difference, but I am unable to find a way to end the while loop.
If i attempt to set the condition to while (!sc.next().equals("")) it reads the whitespace between every two number as the condition, and skips the second number.
I am not able to create a manual break by doing something like if (sc.next().equals("exit") as the output has to be only the difference and nothing else.
public static void main(String[] args) {
long output;
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
long nr1 = sc.nextLong();
long nr2 = sc.nextLong();
if (nr1 > nr2) {
output = nr1 - nr2;
} else {
output = nr2 - nr1;
}
System.out.println(output);
}
}
Again, I'm looking for a way to terminate it when there are no more lines with two numbers on it.
I've been googling like crazy for this issue, but have not been able to find a solution that fixed my issue. Any and all help is very appreciated!
If you want to terminate the loop when you get "" as input, then just have an input variable in your code.
String input;
while(sc.hasNextLine() && !(input = sc.nextLine()).equals("")) {
//Now you have your input and you need to parse it.
//There are many ways to parse a string.
String[] numbers = input.split(" ");
int num1 = Integer.parseInt(numbers[0]);
int num2 = Integer.parseInt(numbers[1]);
System.out.println( num1 > num2 ? num1 - num2 : num2 - num1);
}

Java Sum of numbers until string is entered

i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.
I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result.
This program stops when the user enters "END"
I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int x = scan.nextInt();
System.out.print("Enter a number: ");
int y = scan.nextInt();
int sum = x + y;
System.out.println("Sum is now: " + sum);
}
}
}
The output is supposed to look like this:
Enter a number: 5
Sum is now: 5
Enter a number: 10
Sum is now: 15
Enter a number: END
One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns false.
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals("")) {
System.out.print("Enter a number (END to quit): ");
val = scan.nextLine();
// Was the word 'end' in any letter case supplied?
if (val.equalsIgnoreCase("end")) {
// Yes, so break out of loop.
break;
}
// Was a string representation of a
// integer numerical value supplied?
else if (val.matches("\\-?\\+?\\d+")) {
// Yes, convert the string to integer and sum it.
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum); // Display Sum
}
// No, inform User of Invalid entry
else {
System.err.println("Invalid number supplied! Try again...");
}
val = ""; // Clear val to continue looping
}
// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED");
EDIT: Based on Comment:
Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.
Do it like this:
public static void main(String[] args) throws Exception {
int sum = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.print("Enter a number: ");
if (scan.hasNextInt())
sum += scan.nextInt();
else
break;
System.out.println("Sum is now: " + sum);
}
System.out.print("END");
}
This will end if the input is not a number (int).
As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:
else if (scanner.next().equals("END"))
break;

Scanner object executes only one time in while loop

I have a situation where the program will take input for total no of string to be inputted.
Once inputted it will print odd and even indexes of the string in one line separated by a space.
For illustration this should be the output for the follwing input:
2
input
ipt nu
output
otu upt
my logic seems fine but when I am trying to execute the program runs for only one time whatever be the input. Can anyone please let me know what am I missing here.
Code snippet
import java.util.Scanner;
public class javatest
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
String input_string;
int inputs = scan.nextInt();//total inputs to be accepted
int i=0;
while(i<inputs)
{
input_string = scan.nextLine();
//for even places
for (int j = 0; j < input_string.length(); j += 2)
{
if (j % 2 == 0)
{
System.out.print(input_string.charAt(j));
}
}
System.out.print(" ");
//for odd places
for (int k = 1; k < input_string.length(); k += 2)
{
if (k % 2 == 1)
{
System.out.print(input_string.charAt(k));
}
}
i++;
}
}
}
The above code is producing the output as
3
hello
hlo el
(execution ended)
The issue is that scan.nextInt() does not read the enter pressed while inputing the number. Due to this issue your program runs 1 iteration lesser than the input.
I ran your exact code without any modification and it runs twice for input 3.
The first call to scan.nextLine() gives an empty string.
The alternative can be replacing
scan.nextInt() with Integer.valueOf(scan.nextLine());
which will read the enter/new line character also.
By pressing enter upon entering the amount of inputs you are creating a newline \n character which is consumed by the input_string = scan.nextLine(); in your while loop. So directly after entering the amount of inputs the while loop will increment the value of i to 1 as it processes the \n character.
As a workaround you could fetch the amount of expected inputs as a String and parse it to an int like this:
int inputs = 0;
try {
inputs = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
// handle exception gracefully, maybe by showing a message to the user.
}
Also to make it more clear for the user to understand that an input is expected you might want to add a message that makes it clear a new input is expected:
System.out.println("Please provide the next input: ");
input_string = scan.nextLine();

An unused declaration makes my program work Correctly?

So I wrote this code and I wrote " int number = input.nextInt(); " in it as an experiment. The program does exactly what I want it to, but I don't understand why this works. The variable is not used at all later on in the program, but if I remove it, the program stops working. Any ideas? My code below:
import java.util.Scanner;
/*
* Name: Ki
*/
public class Countdown {
public static void main(String[] args) {
//Create a Scanner object to accept the input from user
Scanner input = new Scanner(System.in);
// Prompt the user to enter starting number, I just set it to 5 because
// that's what the program had as standard input.
System.out.println("Enter the beginning number: ");
// I don't know how this works. I had this here as an experiment, but
// the program now doesn't work without it so I guess I'll leave it here.
int number = input.nextInt();
// sets max countdown value
int i=5;
// Make a loop that makes the program countdown until it reaches 2
while(i>1)
{
System.out.print(i + " ... \n");
i--;
}
// Makes the program print 1 without dots and print stopped at the end
if (i==1) System.out.println(i);
System.out.print("Stopped");
}
}
int number = input.nextInt();
// sets max countdown value
// Make a loop that makes the program countdown until it reaches 2
while(number>1)
{
System.out.print(number + " ... \n");
number--;
}
// Makes the program print 1 without dots and print stopped at the end
if (number==1) System.out.println(number);
System.out.print("Stopped");
Here you create Scanner, but it doesn't do anything for the user yet.
Scanner input = new Scanner(System.in);
With nextInt() the program will wait for the user input.
int number = input.nextInt();
But after that you always use i, which is set to 5.
I guess you want to use the input number as the starting number. Change the later half to this:
// You can remove: int i=5;
while(number>1)
{
System.out.print(number + " ... \n");
number--;
}
// Makes the program print 1 without dots and print stopped at the end
if (number==1) System.out.println(number);
System.out.print("Stopped");

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

Categories

Resources