1

I'm learning Java and was wondering if it's possible to type numbers in the same line without going over the counter?

for (int i = 0; i < 5; i++) {              
    int a = sc.nextInt();
    if (i == 4){
        break;
    }
}

If I press enter after every number I type in then i can have only 5 numbers and they are in a column, but if I want to type the numbers in a line, then I can have more than 5 numbers. So is there a way to do that, is there anything similar to \a in C++?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Oky
  • 11
  • 2
  • You could take inspiration from [this question](https://stackoverflow.com/questions/8430022/what-is-the-java-equivalent-of-sscanf-for-parsing-values-from-a-string-using-a-k) and its answers. – Federico klez Culloca Sep 25 '19 at 12:38
  • Do you want to limit user input to 5 numbers or do you want to process only the first 5 numbers regardless of how many are entered? – nicomp Sep 25 '19 at 12:40
  • even in a loop, you don't necessarily have to stop at five. You can also stop when the user inputs 'q' (for quit). the fact that it can have "only" five is because you wrote the code to have it like that. – Stultuske Sep 25 '19 at 12:41
  • You don't need to `break` the loop. It will automatically `break` when the loop condition evaluates to `false`. – Mushif Ali Nawaz Sep 25 '19 at 12:46
  • 1
    @Stultuske If a user enters `'q'` and we use `sc.nextInt()` then it will throw an exception. Because this is not an `int` value. For that, he needs to take input as `String` using `sc.next()`. – Mushif Ali Nawaz Sep 25 '19 at 12:48
  • @MushifAliNawaz well, duh. that goes without saying. If he wants all his inputs on one line, he won't be able to use nextInt(); either. he should use nextLine(); My point is, if he changes his code, it can be done. whether he uses a loop is not the defining aspect that decides how many times the iteration will be executed, it's how he built his loop that does. – Stultuske Sep 25 '19 at 13:00
  • @Stultuske `nextInt()` can be used if he inputs the numbers in one line. Because for `nextInt()` the default delimiter is a whitespace. You don't have to press the enter key for that. – Mushif Ali Nawaz Sep 25 '19 at 13:01
  • so he'll read the very first one. nextInt() still only reads one single int. or, he needs to know up front how many times to call nextInt(), same problem – Stultuske Sep 25 '19 at 13:03
  • @Stultuske He obviously means he loops `nextInt()` to read all values using a `while(sc.hasNext())` or something along those lines... – Nexevis Sep 25 '19 at 13:05
  • @Nexevis indeed, makes sense. though personally I wouldn't. But, even in that case, it is clear there is need of a loop, and that loop doesn't set the number of times it'll row as hardcoded. problem is, you risk getting in an endless loop easily like that. I would prefer the single 'nextLine()' if only to avoid that. – Stultuske Sep 25 '19 at 13:08

2 Answers2

0

Use nextLine() method of scanner.

It will read full line and return a string.

Split string using white space and store in string array.

Iterate over string array. Pick an index and parse it with the help of Integer class parseInt method.

Store in array or use in any way you want/need.

Input pattern :- 12 13 14 15 16 16 18

You can have N number of integer in 1 line.

Note:- You should be sure that user only enter integer in input. Else you need to write if and else logic just before converting string into integer. So that your code will not throw an exception.

String a = sc.nextLine();
String arr[] = a.split("\\s+"):
int input[] = new int[arr.length];

for( int i = 0 ; i < arr.length ; i++){
    input[i] = Integer.parseInt(arr[i]);
}
SSP
  • 2,650
  • 5
  • 31
  • 49
  • You take the values as a `String` then parse every value into an `int`. This will will throw an `Exception` for every single non `integer` value such as any character. Also should be `a.split("\\s+);`, wrong variable name and a colon used on that line. – Nexevis Sep 25 '19 at 12:57
  • @Nexevis Thanks buddy. I thought questioner was just curious. so replied in lame way. sorry about that. – SSP Sep 25 '19 at 13:04
0

You can use BufferedReader also. Here is an example. The .split() method will return you an array object with the input values you entered splited by white space in this case. After that you need to parse the entries because they are String objects.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String... args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            String[] input = br.readLine().split(" ");   
            int[] a = new int[input.length];
            for (int i = 0; i < input.length; i++)
                a[i] = Integer.parseInt(input[i]);
            for (int i = 0; i < input.length; i++) System.out.printf("%d ", a[i]);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}