0

Suppose I have an input of six integers separated by spaces.

2 7 10 34 2 11

If I want to pick up into six variables int a,b,c,d,e,f;.

In C I can do it like the following directly

scanf("%d %d %d %d %d %d",&a,&b,&c,&d,&e,&f);

In Java,the methods (that I know) I really irritating,as far as to me.You have to either use

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Then we can use String s=br.readLine(); and then s.split(" ") to pick individual values.Another alternative is to use scanner which does the same.Command-line arguments provides some relief but we cannot use it during runtime.

I want to ask isn't there any direct one line method to pick these space-seperated integers?

(There is a similar titled question but its the basic and off-topic so I raised this question) (There

Community
  • 1
  • 1
Naveen
  • 7,944
  • 12
  • 78
  • 165
  • 1
    Why wouldn't you put them in a collection? Easier, and more general. – Dave Newton Oct 06 '13 at 12:08
  • @DaveNewton:Can you please provide an example or code-snippet for the completeness of this question – Naveen Oct 06 '13 at 12:10
  • The approach you showed is the best alternative. You can chain `String[] s = br.readLine().split(" ");` if you really hate lines, but that's it. – Jeroen Vannevel Oct 06 '13 at 12:10
  • These are good solutions and less code than using reader, http://stackoverflow.com/questions/10541157/sscanf-equivalent-in-java http://stackoverflow.com/questions/8430022/what-is-the-java-equivalent-of-sscanf-for-parsing-values-from-a-string-using-a-k – melc Oct 06 '13 at 12:21

1 Answers1

0
import java.util.Scanner; //in the beginning of your code

Scanner scan = new Scanner(System.in); //somewhere along you're code

here, there's 2 ways of doing it. Usually everything you enter in System.in is saved, and methods like .nextInt() or next() will take the first value seperated by a space, and everytime you use that method, you can input more values but it will place it after the first ones you entered:

Ex: you use scan.nextInt(), and enter: "1 2 3", it will take 1, but you still have "2 3" using scan.nextInt() again will allow you to enter more values, and saying you entered "4 5 6", the .nextInt() will take 2, but you will now have "3 4 5 6"

The method i like to use is the following:

String str = scan.nextLine();
int[] array = new int[6]
int count = 0;
Scanner strScan = new Scanner(str);
while(strScan.hasNext())
{
    array[count]=Integer.parseInt(str.next());
    count++;
}

But you can also use:

String str = scan.nextLine();
Scanner strScan = new Scanner(str);
a = Integer.parseInt(scan.next());
b = Integer.parseInt(scan.next());
...
f = Integer.parseInt(scan.next());
ThaBomb
  • 702
  • 6
  • 11