How to finish program with "Scanner.hasNext" in Java - java

I'm wondering how the program with "java scanner" can be finished
especially when I use this with System.in and scanner.hasNext()
Scanner sc = new Scanner(System.in);
For example, when I run the code below on some IDE
public static void main(String[] args){
Scanner sc = new Scanner(System.in)
int[] arr = new int[3];
int i = 0;
// put all the number from scanner to the array.
while(sc.hasNext()){
arr[i++] = sc.nextInt();
}
System.out.println(Arrays.toString(arr));
and input some numbers(for the inputs for scanner) in the console,
it doesn't stop receiving the numbers.
I wanted to use sc.hasNext() for the purpose of after finishing getting some input for the user, putting all the numbers received, as I commented on the code.
How can I finish the scanner getting the input on console?

Your code will run while stdin (System.in in Java) is open. You could close it programmatically if you want but it's usually done by pressing Ctrl+d
in the terminal that program is running (Shortcut is for Linux/macOS in Windows console it's Ctrl+z I think).

The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
However, to put the input from the user in your array, can be done by replacing your while condition with this:
while (sc.hasNext() && i!=arr.length) {
arr[i++] = sc.nextInt();
}

Since your store the user's input inside a fixed size (4) structure, you can use a for loop,
after all this is the case to use it:
when the number of repetitions is predefined
for (int i = 0; i < arr.length; i++){
arr[i] = sc.nextInt();
}

You don't need to put the condition for hasNext as it will always return true after entering an input.
You should have a condition on array length.
try this
int[] arr = new int[3];
int i = 0;
while(i<arr.length)
arr[i++] = sc.nextInt();
System.out.println(Arrays.toString(arr));

just add a condition in while as you limit your array to a specific length so when it reach this length t can't take any more input and it will just close the loop and print your array
like this:
Scanner sc = new Scanner(System.in);
int[] arr = new int[3];
int i = 0;
// put all the number from scanner to the array.
while(sc.hasNext() && i < arr.length){
arr[i++] = sc.nextInt();
}
System.out.println(Arrays.toString(arr));

You can change your while loop and put a conditional break when your number of integers reach array length. Try this,
while (sc.hasNext()) {
arr[i++] = sc.nextInt();
if (i == arr.length) {
break;
}
}
Or you can write it as a simple for loop,
// int i = 0;
for (int i = 0; i<arr.length;i++) {
arr[i] = sc.nextInt();
}
Here it will be useful for you to understand how sc.nextInt() works.
Whenever sc.nextInt() gets executed, the scanner objects sc looks for an integer and returns the next integer it finds in the stream scanned by sc object. If it doesn't find an integer in the stream, it will throw some Exception.
Now coming to your code, when your while loop gets executed, every time the code gets inside while loop, it calls sc.nextInt() and one integer is read and assigned into the array but as you have declared your array size as 3 only you need to break the loop else it will try to access an index greater than 3 in your array and will result into ArrayIndexOutOfBounds exception which you will not want. Due to which I have put that condition in while loop and it breaks as soon as the index reaches 3. Similar thing is achieved in the for loop. Hope my explanation helps. Let me know if you have any queries further.
Another thing you could have done is, change sc.hasNext() to sc.hasNextInt() in your while loop as hasNext() captures any data (integer or non-integer) from the stream and returns true and you would not want it to return true if the next incoming data is not an integer else that will run into exception.
Once you change sc.hasNext() to sc.hasNextInt() in while loop condition, your program will automatically end once you provide 3 integers as input to your program but if user tried to enter more than 3 integers, it will run into ArrayIndexOutOfBounds exception as your array length is limited to 3 only. Hence you need that condition if (i==arr.length) { break; } So your while loop can also be like this,
while (sc.hasNextInt()) {
arr[i++] = sc.nextInt();
if (i == arr.length) {
break;
}
}

Related

Adding user input in Arraylist

I am new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}

Convert input strings into int array

I want to read in five numbers from the console. To convert the input strings into int[x] for each number i tried to use a for loop. But it turns out that #1 incrementation is dead code and #2 my array is not initialized, even though i just did.
I'm on my first Java practices and would be happy to hear some advices.
My code:
public static void main(String[] args) throws IOException {
System.out.println("Type in five Numbers");
int [] array;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
for(int x=0; x<5; x++){
String eingabe = br.readLine();
array[x] = Integer.parseInt(eingabe);
break;
}
reserve(array); }
First off, you didn't initialize your array, you only declared an array variable (named array). I highly suggest reading and practicing this fundamental concept of Java before proceeding further, because otherwise you will likely be confused later on. You can read more about the terms declaration, initialization, and assignment here.
Another issue, as Andrew pointed out, is that you used the keyword break in your first iteration of the loop. This keyword terminates a block of code, so your loop will only run once and then exit for good.
This code can be greatly simplified with a Scanner. A Scanner reads input from a specified location. The scanner's constructor accepts two inputs: System.in, for the default input device on your computer (keyboard), or a File object, such as a file on your computer.
Scanners, by default, have their delimeter set to the whitespace. A delimeter specifies the boundary between successive tokens, so if you input 2 3 5 5, for example, and then run a loop and invoke the scanVarName.nextInt() method, it will ignore the white spaces and treat each integer in that single line as its own token.
So if I understand correctly, you want to read input from the user (who will presumably enter integers) and you want to store these in an integer array, correct? You can do so using the following code if you know how many integers the user will enter. You can first prompt them to tell you how many integers they plan to enter:
// this declares the array
int[] array;
// declares and initializes a Scanner object
Scanner scan = new Scanner(System.in);
System.out.print("Number of integers: ");
int numIntegers = scan.nextInt();
// this initializes the array
array = new int[numIntegers];
System.out.print("Enter the " + numIntegers + " integers: ");
for( int i = 0; i < numIntegers; i ++)
{
// assigns values to array's elements
array[i] = scan.nextInt();
}
// closes the scanner
scan.close();
You can then use a for-each loop to run through the items in your array and print them out to confirm that the above code works as intended.

Why is output shown only alternately?

public class Two {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
while(obj.nextInt() > 5)
{
System.out.println(obj.nextInt());
}
}
}
If i input the number ( > 5) for first time there is no output on the console but if i input a number on second try there is output on the console.
So I get an output alternatively.
Can anyone explain why is it so?
The java.util.Scanner.nextInt() method Scans the next token of the input as an int and returns it. After the token is read another nextInt()-Call will read (as the name says) the next Integer.
I think you were expecting something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int read;
while((read = scanner.nextInt()) > 5)
{
System.out.println(read);
}
}
Now the read Integer is stored in the variable read and is printed, if it was greater than five.
The reason you're getting output every other input is because you're prompting the Scanner object to gather input twice within your loop system. Every time you call a next... method on your Scanner you are prompting the user.
So in your condition for the while loop you are asking the user to input a value integer value which is then compared against 5. THEN, in your print statement you call the nextInt() method again, which will then prompt the user again for another value integer input.
So given a series of 6 integer inputs for your current loop, 6 2 10 4, you loop will only print 2 and 4.
Instead, you should prompt and store once outside of your loop, then test with the condition and reprompt after the print within the loop like so...
int input = obj.nextInt();
while (input > 5){
System.out.println(input);
input = obj.nextInt();
}

excess spaces in front of printed text java

I am trying to write a program to reverse the letters/words in an inputted string, I thought I finally had it but I can't figure out why there are so many excess spaces in front of my output text. Any help would be greatly appreciated.
Also on a side note I attempted to make the scope of the array an incremented variable but it would not run, however I can use an incremented variable for the index position without any issues; why is that?
This is what I have so far and it seems to do exactly what I want it to do minus all the excess white space in front of the output.
Scanner in = new Scanner(System.in);
System.out.println("please enter string");
String strName = in.nextLine();
int ap = 0;
char strArray[] = new char[99];
for(int i=0;i < strName.length();i++)
{
strArray[ap] = strName.charAt(i);
ap++;
}
for (int e=strArray.length-1;e >= 0;e--)
{
System.out.print(strArray[e]);
}
Try this
Scanner in = new Scanner(System.in);
System.out.println("please enter string");
String strName = in.nextLine();
int ap = 0;
char strArray[] = new char[strName.length()];
for(int i=0;i < strName.length();i++)
{
strArray[ap] = strName.charAt(i);
ap++;
}
for (int e=strArray.length-1;e >= 0;e--)
{
System.out.print(strArray[e]);
}
The issue is you are initializing that char array to size 99. For a string of size 4... we have to print 95 nulls THEN the 4 chars in reverse order. This will be fixed by initializing the array to the actual size of the input string. No nulls to print then (printing nulls results in a white space).
Also on a side note I attempted to make the scope of the array an incremented variable but it
would not run, however I can use an incremented variable for the index position without any
issues; why is that?
Hmmm. Not sure what you mean? The word "scope" has specific meaning in CS that I don't think is the meaning you are referring to!

A simple Java code that doesn't work well

The following simple code in Java behaves somewhat in a strange way that I can not understand.
final public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("\nHow many names? ");
int n = sc.nextInt();
String[] a = new String[n];
a[0] = sc.nextLine(); //This line serves no purpose at all. It's useless and should be removed.
for (int i=0; i<n; i++)
{
System.out.print("\nEnter the name:->");
a[i] = sc.nextLine(); //request for input only inside the loop.
}
for (int i=0; i<a.length; i++)
{
System.out.println(a[i]);
}
}
}
The above is working well with no problem at all and displays the number of names inputted into the array a[] on the console but when I remove the line a[0] = sc.nextLine(); //This line serves no purpose at all. It's useless and should be removed., it displays for number of users first. let's say 3. there is no problem but when the loop starts iterating, it will ask for the name and first time the message Enter the name:-> is displayed twice
and the output would be something like shown below.
How many names? 3
Enter the name:-> Don't allow to enter the name here.
Enter the name:->Tiger
Enter the name:->Pitter
Tiger
Pitter
Although I entered 3 for "How many names?", it allows only two names to enter. Why?
Note again that the code shown above is working well. The problem occurs only when the line specified with bold latters in the above paragraph is commented out.
When you use Scanner.nextInt(), it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a Scanner.nextLine(). You can discard the result instead of assigning it to a[0]:
int n = sc.nextInt();
sc.nextLine();
It's for this reason that I suggest always using nextLine (or BufferedReader.readLine()) and doing the parsing after using Integer.parseInt().
You are reading three lines. The problem you have is that nextInt() reads an int value, it doesn't read and consume the end of the line. (A common mistake)
You need the nextLine() after it to say that you want to ignore the rest of the line.
The nextInt call reads from input until the end of the int, but does not read the newline character after the int. So, the first iteration displays "enter the name", then calls nextLine() which reads the end of the line where you typed the number of players (an empty string). Then the second iteration starts and displays "enter the name", and nextLine() blocks until you type a newline character.

Categories