Strings assign with scanner | Sololearn: Learn to code for FREE!


Strings assign with scanner

I have 4 Strings and i need to assign them. If there is no next line a exception for eachstring should be thrown. Can i do that anyhow with a loop instead of 4 if else statements?

4/10/2021 2:13:17 PM

Manfred h

2 Answers

New Answer


You could store your strings as an array: String[] strings = new String[4]; Scanner sc = new Scanner(/* ... */); int index = 0; while (sc.hasNext()) { if (index >= strings.length) break; strings[index] =; index++; } // beware: // if this loop terminates because hasNext is false, the remaining strings will be null // Access strings as you normally would access an array String firstString = strings[0]; // ... and such