Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top