Java ,Related To scanner - java

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.

Related

Giving input separated by spaces

Input:
1 10
How can I provide a space between two inputs so that compiler can take both the inputs differently.
I tried to use
st1=in.nextInt();
in.next();
st2=in.nextInt();
Simply remove the in.next(); call. nextInt() already "ignores" whitespaces. And there is no need to create an array by using split() and to convert the number "manually". Just let the Scanner handle this by using nextInt() like you do already:
Scanner s = new Scanner("1 10 9 5");
while(s.hasNextInt()) {
int number = s.nextInt();
System.out.println(number);
}
The good thing about that is, that you won't get a NumberFormatException like in the other answers if the user does not provide numbers (e.g. a b c).
The following line will give you a String array containing the two numbers as strings:
String[] numbersFromUser = in.nextLine().split(" ");
Assuming that the user properly formats the input.
This would of course also work for a number of arguments greater than 2.
You can then go on to convert numbersFromUser[0] and numbersFromUser[1] into the int values you need:
int st1 = Integer.valueOf(numbersFromUser[0]).intValue();
int st2 = Integer.valueOf(numbersFromUser[1]).intValue();
Use:
data = line.split("\s");
first = data[0];
second = data[1];
third = data[2];
System.out.println(first)
System.out.println(second);
System.out.println(third);
Input:
1 5 6
Output:
1
5
6

Reading a multi datatype file into an ArrayList in Java

I am trying to read a file, which the user inputs, and the file has numbers and characters. I only want to store the numbers in an Arraylist but I keep getting stuck, help would be greatly appreciated. This is what I have. Sorry if this has been answered, I am new to the site.
import java.util.*;
import java.io.*;
public class ArrayListClient {
public static final int SIZE = 100;
public static void main(String[] args) throws FileNotFoundException {
String fileName, fileName2;
UnorderedArrayList list1 = new UnorderedArrayList(SIZE);
Scanner input = new Scanner(System.in);
System.out.print("Please input the name of the file to be opened for the first list: ");
fileName = input.nextLine();
System.out.println();
Scanner inputFile = new Scanner(new File(fileName));
int num = inputFile.nextInt();
while(inputFile.hasNextInt()) {
int num2 = inputFile.nextInt();
list1.insertEnd(num);
num = num2;
}
list1.print();
}
}
the input file is 13 c v b 25 34 x x 67 56 10 a a 20 27 2 a s 5 1 45 59
The loop you provided is correct, although you don't need this line outside of the while loop:
int num = inputFile.nextInt();
If the file you provided didn't have a Integer then this would crash your program.
I think you can simply write this and it should work:
while (inputFile.hasNextInt()) {
int num = inputFile.nextInt();
list1.insertEnd(num);
}
The loop checks to see if there is another Integer left in the file (inputFile.hasNextInt()) and then gets it to add to the list (inputFile.nextInt()).
This sounds like it could be a homework question, so I'm hesitant to just give the answer, but if I were you, I would consider writing a filter function (make it a lazy filter if you have to consider files that are very large/won't fit in memory). Your filter function can try Integer.parseInt(yourString); and catch any NumberFormatExceptions that occur because it tried to parse a letter. This approach has the obvious danger of using exceptions to control program flow (normally considered bad practice), but you won't have to traverse the list twice.
Your other obvious option is to write a filter that filters the characters out so that you are only left with number strings, and then just run parseInt over those number strings to turn them into integer values. If performance is a concern, you can avoid double-traversing the list by writing functions that validate a single string value (reject if it's not a number), and then parse it into an int if it is a number, and then add the parsed integers into your array as you go within a foreach loop.
You are most of the way there already since integer detection is built into the Scanner class and the Integer class contains the parseInt() method. Just mutate an array which you define outside of a for each loop and you're good to go.

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

Handling user input using Scanner

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".

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