-4

I have a string 'line' in java containing numbers , for example , "34 55 64 "

I want to store these 3 numbers in int x , y ,z

when I do ,

x = Integer.parseInt(line[0]) 

y = Integer.parseInt(line[1])

I get an error saying a "array required but string found " . I do not understand why it needs an array

x,y,z are declared integers and line is declared as a string

Emil L
  • 20,219
  • 3
  • 44
  • 65
user2623946
  • 55
  • 1
  • 13

3 Answers3

4

something like this

StringTokenizer st = new StringTokenizer("34 55 64");
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
z = Integer.parseInt(st.nextToken());

As pointed out in comments, StringTokenizer is a legacy class (Not deprecated though) and can be replaced with the following code

String line = "34 55 64 ";
String []splits = line.trim().split("\\s+");
x = Integer.parseInt(splits[0]);
y = Integer.parseInt(splits[1]);
z = Integer.parseInt(splits[2]);
remudada
  • 3,751
  • 2
  • 33
  • 60
  • 2
    Note the [javadoc](http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html) says _StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code_ – Reimeus Mar 29 '14 at 17:29
3

First split the string into array for the spaces(\\s+):

String line = "34 55 64 ";
String []splits = line.trim().split("\\s+");

Then perform Integer.parseInt(splits[0])

Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
1

Why would you want to do such thing? This is a very specific code and will work in a very limited inputs whichmakes the ccode very fragile. Anyhow, splitting the string to string array first as Sabuj suggested sounds like the best option for such requirement

danny
  • 21
  • 1