Java : Get only 1 line of integers from the console? - java

I recently picked up Java and I am having an issue with some console input.
Basically, I want to read in an array of ints from the console in a format like this :
1 2 3 4 5 6
I looked through some examples on the forums and decided to do this by using the scanner nextInt() method.
My code currently looks like this :
Scanner get = new Scanner(System.in);
List<Integer> elements = new ArrayList<>();
while (get.hasNextInt()) {
elements.add(get.nextInt());
}
The problem with this code is that the while loop doesn't stop when I hit "Enter" on the console.
Meaning that after I enter some numbers (1 3 5 7) and then hit enter, the program doesn't continue with execution, but instead waits for more integers. The only way it stops is if I enter a letter to the console.
I tried adding !get.hasNextLine() as a condition in my while loop, but this didn't help.
I would be very greatful, if anyone has an idea how can I fix this.

If you want to read only one line the simpliest answer may be the best :)
Scanner in = new Scanner(System.in);
String hString = in.nextLine();
String[] hArray = hString.split(" ");
Now, in array hArray you have all elements from input and you can call them like hArray[0]

You can read one line, and then use that to construct another Scanner. Something like,
if (get.hasNextLine()) {
String line = get.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextInt()) {
elements.add(lineScanner.nextInt());
}
}
The Scanner(String) constructor (per the Javadoc) constructs a new Scanner that produces values scanned from the specified string.

Scanner get = new Scanner(System.in);
String arrSt = get.next();
StringTokinizer stTokens = new StringTokinizer(arrSt," ");
int [] myArr = new Int[stTokens.countTokens()];
int i =0;
while(stTokens.hasMoreTokens()){
myArr[i++]=Integer.parseInt(stTokens.nextToken());
}

java-8
You may use the following. User just has to enter each integer without pressing enter and press enter at the end.
Scanner get = new Scanner(System.in);
List<Integer> elements = Stream.of(get.nextLine().split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());

Related

JAVA: Signal start of new input with space instead of enter

I have an assignment to create a program that will take input and print it to the console. Pretty simple. There is one issue though. I have to store the information in separate variables but the input looks like this.
Input:
Blah 123 Green
I'm aware that I can create a single scanner input tied to a single variable that will store all of that as one String but for the assignment Blah, 123, and Green would all have to be stored in different variables. Normally what I would do if I could use the enter key to signal new input would be
Scanner scan = new Scanner(System.in);
String first = scan.nextLine();
int second = Integer.parseInt(scan.nextLine());
String third = scan.nextLine();
but in this case, the spaces have to act as the enter key instead. how would I go about this?
You could use next() to read individual inputs:
String first = scan.next();
int second = scan.nextInt());
String third = scan.next();

double print before allowed to respond

I'm still new to programming and have been trying to learn how to fix this code
im trying to input and record a username and password depending on how many users I input, but when i run it it prints out the "whats your username?" question twice before i'm allowed to give a response. I've narrowed the problem down to the user[i]=in.nextLine() part
public static void main(String[] args){
System.out.println("How many Users?");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
String[] user;
user = new String[x];
String[] pass;
pass = new String[x];
for(int i=0; i<x;i++){
System.out.println("What is your Username?");
user[i] = in.nextLine();
Add in.nextLine(); after int x = in.nextInt(); to consume and ignore the new line character left over by call to nextInt()
When you use a scanner it consume only the bytes needed for the requested token.
If the first call is to get the number of users (nextInt) it reads only the minimum number of digits composing it and leave the \n (new line character) not consuming it.
Because you are asking for the next line on the loop the first nextLine use only the \n.
So the best solution to make your code correct is to add a
in.nextLine();
before the for loop.

Accepting multiple integers on a single line using Scanner

The user needs to enter a certain number of integers. Rather them enter an integer at a time, I want to make it so they can enter multiple integers on a single line, then I want those integers to be converted in an array. For example, if the user enters: 56 83 12 99 then I want an array to be created that is {56, 83, 12, 99}
In other languages like Python or Ruby I would use a .split(" ") method to achieve this. No such thing exist in Java to my knowledge. Any advice on how to accept user input and create an array based on that, all on a single line?
Using the Scanner.nextInt() method would do the trick:
Input:
56 83 12 99
Code:
import java.util.Scanner;
class Example
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] numbers = new int[4];
for(int i = 0; i < 4; ++i) {
numbers[i] = sc.nextInt();
}
}
}
At #user1803551's request on how Scanner.hasNext() can achieve this:
import java.util.*;
class Example2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (sc.hasNextInt()) { // this loop breaks there is no more int input.
numbers.add(sc.nextInt());
}
}
}
The answer by Makoto does what you want using Scanner#nextLine and String#split. The answer by mauris uses Scanner#nextInt and works if you are willing to change your input requirement such that the last entry is not an integer. I would like to show how to get Scanner#nextLine to work with the exact input condition you gave. Albeit not as practical, it does have educational value.
public static void main(String[] args) {
// Preparation
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers:");
// Get the input
while (scanner.hasNextInt())
numbers.add(scanner.nextInt());
// Convert the list to an array and print it
Integer[] input = numbers.toArray(new Integer[0]);
System.out.println(Arrays.toString(input));
}
When giving the input 10 11 12 upon first prompt, the program stores them (Scanner has a private buffer), but then keeps asking for more input. This might be confusing since we give 3 integers which loop through hasNext and expect that when the 4th call is made there will be no integer and the loop will break.
To understand it we need to look at the documentation:
Both hasNext and next methods [and their primitive-type companion methods] may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
(emphasis mine) and hasNextInt
Returns: true if and only if this scanner's next token is a valid int value
What happens is that we initialized scanner with an InputStream, which is a continuous stream of data. On the 4th call to hasNextInt, the scanner "does not know" if there is a next int or not because the stream is still open and data is expected to come. To conclude from the documentation, we can say that hasNextInt
Returns true if this scanner's next token is a valid int value, returns false if it is not a valid int, and blocks if it does not know what the next token is.
So what we need to do is close the stream after we got the input:
// Get the input
numbers.add(scanner.nextInt());
System.in.close();
while (scanner.hasNextInt())
numbers.add(scanner.nextInt());
This time we ask for the input, get all of it, close the stream to inform scanner that hasNextInt does not need to wait for more input, and store it through iteration. The only problem here is that we closed System.in, but if we don't need more input it's fine.
String#split exists, but you have to do more work, since you're only getting strings back.
Once you've got the split, convert each element into an int, and place it into the desired array.
final String intLine = input.nextLine();
final String[] splitIntLine = intLine.split(" ");
final int[] arr = new int[splitIntLine.length];
for(int i = 0; i < splitIntLine.length; i++) {
arr[i] = Integer.parseInt(splitIntLine[i]);
}
System.out.println(Arrays.toString(arr)); // prints contents of your array
Scanner scan2= new Scanner(System.in);
ArrayList l2=new ArrayList();
System.out.print("How many numbers do you want in your list: ");
int numbers=scan2.nextInt();
while(numbers!=0){
int age=scan2.nextInt();
l2.add(age);
numbers-=1;
}
System.println(l2);

Scanner problems in Java

I have a method that returns a scanner to a text file that has lines of input (I can't get this to display properly, but like - Hi (new line) This (\n) Is (\n) Me (\n)). Then in main, I used the scanner to count the number of lines of input there are, and then resetted the scanner. I later used the scanner to put the lines of input into an array (I don't want an ArrayList), but Java says "java.util.NoSuchElementException: No line found"...
while(scanner.hasNextLine()){
numOfStrings++;
scanner.nextLine();
}
scanner.reset();
String[] stringsOfInput = new String[numOfStrings];
for(int i = 0; i < numOfStrings; i++){
String s = scanner.nextLine(); //returns "No line found" error message
stringsOfInput[i] = s;
}
Does anyone know how to fix this so it does what it should?
The most versatile way to do this would be to add the lines into an ArrayList<String> then make that into an Array(String[] stringsOfInput = myArrayList.toArray(new String[myArrayList.size()]);)
You may want to try putting the content of the for loop within the while. That way you can get the number of strings and each string in one loop through the file.
EDIT:
Sample with ArrayList
ArrayList<String> stringsOfInput = new ArrayList<String>();
while(scanner.hasNextLine())
{
stringsOfInput.add(scanner.nextLine());
numOfStrings++;
}

Read multiple lines from console and store it in array list in Java?

Can anyone please help me with the code as how to read multiple lines from console and store it in array list?
Example, my input from the console is:
12 abc place1
13 xyz place2
and I need this data in ArrayList.
So far I tried this code:
Scanner scanner = new Scanner(System.in);
ArrayList informationList = new ArrayList<ArrayList>();
String information = "";
int blockSize = 0, count = 1;
System.out.println("Enter block size");
blockSize = scanner.nextInt();
System.out.println("Enter the Information ");
while (scanner.hasNext() && blockSize >= count) {
scanner.useDelimiter("\t");
information = scanner.nextLine();
informationList.add(information);
count++;
}
Any help is greatly appreciated.
Input line from console is mix of string and integer
You've got a few problems.
First of all, the initialization line for your ArrayList is wrong. If you want a list of Object so you can hold both Integers and Strings, you need to put Object inside the angle braces. Also, you're best off adding the generic type argument to the variable definition instead of just on the object instantiation.
Next, your count is getting messed up because you're initializing it to 1 instead of 0. I'm assuming "block size" really means the number of rows here. If that's wrong leave a comment.
Next, you don't want to reset the delimiter your Scanner is using, and you certainly don't want to do it inside your loop. By default a Scanner will break up tokens based on any whitespace which I think is what you want since your data is delimited both by tabs and newlines.
Also, you don't need to check hasNext() in your while condition. All of the next*() methods will block waiting for input so the call to hasNext() is unnecessary.
Finally, you're not really leveraging the Scanner to do what it does best which is parse tokens into whatever type you want. I'm assuming here that every data line is going to start with a single integer and the be followed by two strings. If that's the case, just make a call to nextInt() followed by two calls to next() inside your loop and you'll get all the data parsed out into the data types you need automatically.
To summarize, here is your code updated with all my suggestions as well as some other bits to get it to run:
import java.util.ArrayList;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Object> list = new ArrayList<>();
System.out.println("Enter block size");
int blockSize = scanner.nextInt();
System.out.println("Enter data rows:");
int count = 0;
while (count < blockSize) {
list.add(scanner.nextInt());
list.add(scanner.next());
list.add(scanner.next());
count++;
}
System.out.println("\nThe data you entered is:");
System.out.println(list);
}
}

Categories

Resources