Reading a java program

162
July 27, 2019, at 4:00 PM

I am trying to read a java program.

I am using this line of code.

String[] words = line.split(" ");

Does it also split the ';' from the previous variable name?

for Example

int x = test;

How would the split, SPLIT that?

Answer 1

If the line was int x = test; and you specified line.split(" "), it would split on the " " character (empty space), so

words=["int","x","=","test;"]

You specify the character that you want to split the line on inside of the split method. So if my line was "Hi#I'm;#Bob" and I ran String[] words = line.split("#"), the result would be

words = ["Hi","I'm;",Bob"]. 

It won't effect the ';' character unless you specify

Answer 2

No, line.split(" ") only separate each word by the space character. In your case,

int x = test;

Space characters are between "int" and "x", "x" and "=", "=" and "test;", so the output will be,

word[0]="int";
word[1]="x";
word[2]="=";
word[3]="test;";

If you want to split by both space and semicolon, then use regular expression,

String[] words = line.split("[ ;]");
READ ALSO
Best place to validate constructor input

Best place to validate constructor input

I'm not sure what the best practice for the location of validating input for my constructor would be, I could put logic outside of the constructor or accept the input and do logic to check inside the constructor

167
Why cant print 2 char with sysem.out.print command [duplicate]

Why cant print 2 char with sysem.out.print command [duplicate]

This question already has an answer here:

154
How to print only time in java? [duplicate]

How to print only time in java? [duplicate]

This question already has an answer here:

209