Handling user input using Scanner - java

I'm trying to retrieve user input through a single line of input: e.g 5,6,4,8,9 using scanner Delimiter for the comma.How do i retrieve an arbitrary amount of integers using this type of input? That is, without having to ask the user how many integers they wish to enter. Here is the code i have been using, but cannot have the while loop break when i want it to break. Note that i keep System.out to keep track of where the program is currently running. The one part that baffles is that, i can get the user inputs in this format, but the program stops and asks for user input once again, then if input is one integer, it asks for more input until user inputs a longer stream of inputs (at least 2,6 + enter) then outputs the string "called break" then "outside of while loop".
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Lab1 {
/**
* #param args
* #throws IOException
* #throws NumberFormatException
*/
#SuppressWarnings("resource")
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberList;
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(",");
System.out.print("Enter integers: ");
while(scanner.hasNext())//------------------------while loop------
{
if(scanner.hasNextInt())
{
numberList = scanner.nextInt();
numbers.add(numberList);
System.out.println(numbers.toString() + " " + numbers.size());
}
else
{
System.out.println("called break");
break;
}
System.out.println("Inside of while loop");
}//-------------------------------------------------end of while loop------
System.out.println("outside of the while loop now");
}
}
Input: 1,2,3,4,5
Enter integers: 1,2,3,4,5
[1] 1
Inside of while loop
[1, 2] 2
Inside of while loop
[1, 2, 3] 3
Inside of while loop
[1, 2, 3, 4] 4
Inside of while loop
I'm still inside the while loop even though there is no integer after the 5 and the programs is waiting for more input, now if i insert a non integer value in the end i get the same exact thing. after these two result, once the user inputs more value (1,2) the program exits the while loop and completes successfully. How do can i make the while loop break once i'm done entering integer using the comma delimiter method?

I know this not answers your question, but it's another way to do the intended:
Here the split(delimiter) method is used, which will return a String[] array. Then in a for loop, use Integer.parseInt() to convert the Strings into integers:
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberList;
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(",");
System.out.print("Enter integers: ");
String[] parts = scanner.nextLine().split(",");
// Add int's to the array 'numbers'
for (String s : parts) {
numbers.add(Integer.parseInt(s)); // Convert String to Integer
}
}

I would recommend reading comma seperated numbers as a String using scanner.nextLine() , then splitting the String using "," , then using Integer.parseInt() to get integer values of numbers. This way, you can input as many numbers as you want without prior definition of "numberCount".

Related

Java ,Related To scanner

I have one query regarding Scanner in java.
I want to take input from user and perform same operation based on inputs.
If user inputs 1 2 in first line, 3 4 5 in second line, 6 7 8 9 in third line ... so it should call function(1,2); function(3,4,5); function(6,7,8,9); ... based on user input (which are different in parameter size) I want to call same function.
Can anyone suggest me optimal way to do this?
This is my program so far ...
import java.util.Scanner;
public class HelloWorld {
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int length = sc.nextInt(); // length of array
int query = sc.nextInt(); // how many queries you want to perform
int arr[] = new int[length];
for(int i=0;i<length;i++);
{
int arr[i] = sc.nextInt();
}
for(int j=0;j<query;j++) {
/* here i want to take input from user and if user inputs 2 integer than pass it like function(param1,param2) if he inputs 3 parameter than pass it like function(param1,param2,param3)
}
Note: For function I am using varargs: function(int... a) .
Use
while(scannerInstance.hasNextLine) to keep reading input and in the loop
Use String value = scannerInstance.nextLine() to read the entire line
Then value.split("\\s+") to split the input string based on
one or more whitespaces.
Parse each string as an Integer using Integer.toString().
Pass the integers got in step 4 to your method.
End while 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);

How to read comma separated integer inputs in java

import java.io.*;
import java.util.*;
class usingDelimiters
{
public static void main(String args[])
{
Scanner dis=new Scanner(System.in);
int a,b,c;
a=dis.nextInt();
b=dis.nextInt();
c=dis.nextInt();
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}
}
This program is working fine when my input is 1 2 3 (separated by space)
But, how to modify my program when my input is 1,2,3 (separated by commas)
You can use a delimiter for non-numerical items, which will mark any non-digit as delimiter.
Such as:
dis.useDelimiter("\\D");
The useDelimiter method takes a Pattern or the String representation of a Pattern.
Full example:
Scanner dis=new Scanner(System.in);
dis.useDelimiter("\\D");
int a,b,c;
a=dis.nextInt();
b=dis.nextInt();
c=dis.nextInt();
System.out.println(a + " " + b + " " + c);
dis.close();
Inputs (either or)
1,2,3
1 2 3
Output
1 2 3
Note
Don't forget to close your Scanner!
See the API for Patterns for additional fun delimiting your input.
you can use the nextLine method to read a String and use the method split to separate by comma like this:
public static void main(String args[])
{
Scanner dis=new Scanner(System.in);
int a,b,c;
String line;
String[] lineVector;
line = dis.nextLine(); //read 1,2,3
//separate all values by comma
lineVector = line.split(",");
//parsing the values to Integer
a=Integer.parseInt(lineVector[0]);
b=Integer.parseInt(lineVector[1]);
c=Integer.parseInt(lineVector[2]);
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}
This method will be work with 3 values separated by comma only.
If you need change the quantity of values may you use an loop to get the values from the vector.

Scanner not detecting empty line and Counter not accurate

This should be a very basic program but I'm new to Java. I want to be able to input multiple strings into the console using Scanner to detect them. So far I've been able to get the input part right, I wanted the program to run in such a way that the results are displayed when an empty space is entered as opposed to a string. Strangely enough I've only been able to get results when i hit return twice, however, when there are more than 4 inputs hitting return once works. My counter should count the number of "Courses" entered and display them in the results but it gives inaccurate readings.
import java.util.Scanner;
public class Saturn
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("For each course in your schedule, enter its building");
System.out.println("code [One code per line ending with an empty line]");
String input;
int counter = 0;
while (!(userInput.nextLine()).isEmpty())
{
input = userInput.nextLine();
counter++;
}
System.out.println("Your schedule consits of " + counter + " courses");
}
}
You're calling Scanner#nextLine twice - once in the while loop expression and again in the body of the loop. You can just assign input from the while loop expression. In addition you can use Scanner#hasNextLine to defend against NoSuchElementException occurring:
while (userInput.hasNextLine() &&
!(input = userInput.nextLine()).isEmpty()) {
System.out.println("Course accepted: " + input);
counter++;
}

Scanner is not stopping

Please have a look at the following code. It is my attempt to manage the given numbers in ascending order.
import java.io.*;
import java.util.*;
import java.util.ArrayList;
public class TurboSort
{
public static void main(String[]args)
{
List<Integer> numbers = new ArrayList();
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt())
{
numbers.add(scan.nextInt());
}
Collections.sort(numbers);
System.out.println(numbers);
}
}
insert the input as 2,1,6,7,3
Hit enter.
Now, the scanner hasn't exited from the while loop because it is not giving any output. What am I doing here wrong? Even if you manage to get it, the output is surrounded by brackets like " [1] [2] [3] ". Why is that? Is that is because I didn't call 'Integer.parseInt()' ?. Please help me with those 2 questions.
Thanks.
The result of hitting enter will be a line separator, whose characters are treated as delimiters (by default, see Character.isWhitespace()) and are skipped. Thus the Scanner is waiting for further input, which never arrives and the hasNextInt() will block. Enter something which is not an integer, like a . for example, to cause the loop to terminate:
1 2 5 3 7 .
This loop will never exit (as long as you enter integers) as there is no break condition
while(scan.hasNextInt()){
numbers.add(scan.nextInt());
}
If you want your loop to stop, say for example you need to acquire only 5 integers then you could do this:
while(scan.hasNextInt()){
numbers.add(scan.nextInt());
if(numbers.size() == 5) break;
}
The Scanner continues to scan until the end of input has reached, or until it fails to read (e.g. when a non integer is detected in the text).
Hit ctrl + D after you hit enter.
You can separate the numbers any white space.
If you want to have the input on only 1 line like 2,1,6,7,3, probably would be easier to use nextLine() of the scanner:
Scanner scan = new Scanner(System.in);
String consoleInput = scan.nextLine();
This will terminate the scanner, once you hit enter. At this point, you have the input in a String, you have to parse that string and get out all the numbers.
Also note that you have forgotten to parameterize your ArrayList().
Here's a possible adaptation of your source code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String consoleInput = scan.nextLine();
List<Integer> numbers = new ArrayList<Integer>();
if (consoleInput.length() > 0 && consoleInput.contains(",")) {
String[] numbersAsStrings = consoleInput.split(",");
for (String tNumberAsString : numbersAsStrings) {
try {
int tNumber = Integer.parseInt(tNumberAsString);
numbers.add(tNumber);
} catch (NumberFormatException nfe) {
System.out.println(tNumberAsString + " is not a number");
}
}
Collections.sort(numbers);
System.out.println(numbers);
} else {
System.out.println("Nothing to sort!");
System.out.println(numbers);
}
}
}
Your code should work. You just need to add a way to break out of the loop. It also is a good idea to keep your scanned value in a local variable in case you need to reference it again.
maybe add:
while(scan.hasNextInt()){
int i=scan.nextInt();
if(i==-1)
break;
numbers.add(i);
}

Categories

Resources