0

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?

10th Apr 2021, 2:13 PM
Manfred h
1 ответ
+ 1
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] = sc.next(); 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
10th Apr 2021, 2:52 PM
Leonardo Bishop