I need to get multiple lines of input which will be integers from the console for my class problem. So far I have been using scanner but I have no solution. The input consists of n amount of lines. The input starts with an integer followed by a line of series of integers, this is repeated many times. When the user enters 0 that is when the input stops.
For example
Input:
3
3 2 1
4
4 2 1 3
0
So how can I read this series of lines and possible store each line as a element of an array using a scanner object? So far I have tried:
Scanner scan = new Scanner(System.in);
//while(scan.nextInt() != 0)
int counter = 0;
String[] input = new String[10];
while(scan.nextInt() != 0)
{
input[counter] = scan.nextLine();
counter++;
}
System.out.println(Arrays.toString(input));
You need 2 loops: An outer loop that reads the quantity, and an inner loop that reads that many ints. At the end of both loops you need to readLine().
Scanner scan = new Scanner(System.in);
for (int counter = scan.nextInt(); counter > 0; counter = scan.nextInt()) {
scan.readLine(); // clears the newline from the input buffer after reading "counter"
int[] input = IntStream.generate(scan::nextInt).limit(counter).toArray();
scan.readLine(); // clears the newline from the input buffer after reading the ints
System.out.println(Arrays.toString(input)); // do what you want with the array
}
Here for elegance (IMHO) the inner loop is implemented with a stream.
You could use scan.nextLine() to get each line and then parse out the integers from the line by splitting it on the space character.
As mWhitley said just use String#split to split the input line on the space character
This will keep integers of each line into a List and print it
Scanner scan = new Scanner(System.in);
ArrayList integers = new ArrayList();
while (!scan.nextLine().equals("0")) {
for (String n : scan.nextLine().split(" ")) {
integers.add(Integer.valueOf(n));
}
}
System.out.println((Arrays.toString(integers.toArray())));
Related
Instead of having to press Enter after each value input with Scanner, is there a way to type all values at once, and then press enter and be done?
import java.util.Arrays;
import java.util.Scanner;
class Arrayex {
public static void main(String[] args)
{
int [] numbers = new int[5];
Scanner s=new Scanner(System.in);
System.out.println("Current array: " + Arrays.toString(numbers));
System.out.println("Type in the numbers: ");
for(int i=0; i< numbers.length; i++)
{
numbers[i] = s.nextInt();
}
System.out.println("Array elements are: " + Arrays.toString(numbers));
}
}
Current array input by pressing Enter after every number
How I want to type in the numbers into the array
My friend told me I can use a String array and convert it to int array and type the string as "1,2,3,4,5".
Wouldn't this only use up the location at numbers[0] instead of numbers[0] to numbers[5]?
Enter all int elements in one line using space, it will use as separate int values.
it will look like this.
No need to take input as String and parse it to an integer.
(White)space as delimiter
As others have noted, if you just use space as separator, then you could leverage the Scanner to convert the input to ints. The input 2 3 5 7 11 will yield an int[] with the given integers als elements.
Comma as delimiter
If you want to use comma as delimiter instead, the current code won't work. The input 2,3,5,7,11 will indeed try to shove 2,3,5,7,11 into numbers[0], which obviously will fail, and an InputMismatchException will be thrown at you.
Instead, you could set the delimiter:
Scanner s = new Scanner(System.in);
s.useDelimiter("[,\n]")
This will cause the Scanner to process the tokens between each comma or newline as separate elements.
Note that we couldn't just use , alone, because then the Scanner keeps reading from System.in indefinitely.
I need to read maximum 10 lines, with each lines having only characters * and . also with other conditions like begin with * and length 10. the last line that should be read should have a line following it with the word END. I want to know if there is a better way to solve it than below. If I can check all the conditions within the while loop
Scanner keyboard = new Scanner(System.in);
int countLine = 0;
String line = "";
while (countLine < 10) {
line = keyboard.nextLine();
countLine++;
if (line.matches("[*.]+") && !line.equals("END") && line.startsWith("*") && line.length() < 10
) {
// do something
} else {
break;
}
}
keyboard.close();
One way you can do this is:
read the entire document into your application.
parse each (row/column) into arrayLists (so the first 10 lines of the document)
perform necessary calculations (still in the while loop).
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.
I'm trying to take in a string input which consists of multiple lines of numbers separated by ',' and ';' .
Example:
1,2;3,4;5,6;
9,8;7,6;
0,1;
;
Code:
ArrayList<Integer> alist = new ArrayList<>();
String delims = ";|\\,";
int i = 0;
Scanner input = new Scanner(System.in);
input.useDelimiter(delims);
while (input.hasNext()) {
alist.add(i, input.nextInt());
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
i++;
}
System.out.print('x');
When I run this in eclipse:
1,2;3,4;5,6; ( <= what i typed in console)
321133123413351436153716 ( <= output)
I'd expect something more like:
0 1
1 2
2 3
3 4
4 5
5 6
x
Why am I getting this sort of output?
One problem is that System.in is basically an infinite stream: hasNext will always return true unless the user enters a special command that closes it.
So you need to have the user enter something that tells you they are done. For example:
while(input.hasNext()) {
System.out.print("Enter an integer or 'end' to finish: ");
String next = input.next();
if("end".equalsIgnoreCase(next)) {
break;
}
int theInt = Integer.parseInt(next);
...
For your program, you might have the input you are trying to parse end with a special character like 1,2;3,4;5,6;end or 1,2;3,4;5,6;# that you check for.
And on these lines:
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
It looks like you are trying to perform String concatenation but since char is a numerical type, it performs addition instead. That is why you get the crazy output. So you need to use String instead of char:
System.out.print(i + " ");
System.out.print(alist.get(i) + "\n");
Or just:
System.out.println(i + " " + alist.get(i));
Edit for comment.
You could, for example, pull the input using nextLine from a Scanner with a default delimiter, then create a second Scanner to scan the line:
Scanner sysIn = new Scanner(System.in);
while(sysIn.hasNextLine()) {
String nextLine = sysIn.nextLine();
if(nextLine.isEmpty()) {
break;
}
Scanner lineIn = new Scanner(nextLine);
lineIn.useDelimiter(";|\\,");
while(lineIn.hasNextInt()) {
int nextInt = lineIn.nextInt();
...
}
}
Since Radiodef has already answered your actual problem(" instead of '), here are a few pointers I think could be helpful for you(This is more of a comment than an answer, but too long for an actual comment):
When you use Scanner, try to match the hasNextX function call to the nextX call. I.e. in your case, use hasNextInt and nextInt. This makes it much less likely that you will get an exception on unexpected input, while also making it easy to end input by just typing another delimiter.
Scanners useDelimiter call returns the Scanner, so it can be chained, as part of the initialisation of the Scanner. I.e. you can just write:
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
When you add to the end of an ArrayList, you don't need to(and usually should not) specify the index.
int i = 0, i++ is the textbook example of a for loop. Just because your test statement doesn't involve i does not mean you should not use a for loop.
Your code, with the above points addressed becomes as follows:
ArrayList<Integer> alist = new ArrayList<>();
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
for (int i = 0; input.hasNextInt(); i++) {
alist.add(input.nextInt());
System.out.println(i + " " + alist.get(i));
}
System.out.println('x');
Edit: Just had to mention one of my favorite delimiters for Scanner, since it is so suitable here:
Scanner input = new Scanner(System.in).useDelimiter("\\D");
This will make a Scanner over just numbers, splitting on anything that is not a number. Combined with hasNextInt it also ends input on the first blank line when reading from terminal input.
im struggling with the input part of the below question.
Question: The input stream contains a set of integer numbers Ai (0 ≤ Ai ≤ 1018). The numbers are separated by any number of spaces and line breaks. A size of the input stream does not exceed 256 KB.
how do i read the input from the user which are separated by line breaks, spaces etc. how do i make sure the input stream doesnot exceed 256 KB?
and how do i make sure that a particular input will be the last value entered by the user so that the program and proceed for execution?
the input can be given in anyway, any number not exceeding 10^8,EX: first input can be given as say 1 and in the same line the second input can be given as 34 separated by 3 spaces from the first input. then 2nd line and the 3rd line are empty and again in the fourth line, there can a number say 225345 which is the 3rd input. so once all the inputs are given by the user, i have to take them, arrange them into one list or array and perform some operations on them.
example:
1427 0
876652098643267843
5276538
kindly help. thanks
This should do the trick if there is at least one space between each number
Scanner scanner = new Scanner(new File("data.txt")); // or new Scanner(System.in) for reading from command line.
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNext()) {
int number = scanner.nextInt();
if (number<0||number>1018)
break;
list.add(number);
}
scanner.close();
System.out.println(list);
Example: (data.txt)
145 358
94 2
13 1205 158 489
Output:
[145, 358, 94, 2, 13, 1205, 158, 489]
Use a java.util.Scanner to read the sequence of longs (because 10^18 > Integer.MAX_VALUE):
Scanner scanner = new Scanner(input);
while (scanner.hasNextLong()) {
long number = scanner.nextLong();
if (number < 1 || number > 1_000_000_000_000_000_000L)
throw new RuntimeException("input out of range: " + number);
}
To validate the input stream size you can reuse the CountingInputStream from Guava or Commons IO, or code your own. Note that, due to internal buffering in Scanner, you may end up reading more than 256 KB of input.
CountingInputStream input = new CountingInputStream(System.in);
Scanner scanner = new Scanner(input);
while (scanner.hasNextLong() && input.getCount() < 256 * 1024) { ... }
Ensuring that a particular input will be the last value requires you to pick a delimiter. I'd use a number out of the acceptable input, say, -1:
CountingInputStream input = new CountingInputStream(System.in);
Scanner scanner = new Scanner(input);
while (scanner.hasNextLong() && input.getCount() < 256 * 1024) {
long number = scanner.nextLong();
if (number == -1)
break;
if (number < 1 || number > 1_000_000_000_000_000_000L)
throw new RuntimeException("input out of range: " + number);
}
Hope this helps.