I am not able to understand Scanner or I should say the inputs from console
public class Calculate {
public static void main(String[] args) throws IOException {
System.out.println("enter the lines");
Scanner s = new Scanner(System.in);
ArrayList<String> result = new ArrayList<String>();
String line = "";
while((line = s.nextLine()) != null) {
result.add(line);
}
for(String ss : result){
System.out.println(ss);
}
}
}
Console :
enter the lines
[Inputs on console:]
aa
bb
cc
When I run in debug mode, the string aa and bb are added to List result, but when cc is read from scanner, it is not added to List I am not sure, what I am missing. looks silly to me, but some how I am not able to think what I am missing
This (slightly) amended code works as expected (you can exit the program by entering an empty string):
public static void main(String[] args) {
System.out.println("enter the lines");
Scanner s = new Scanner(System.in);
ArrayList<String> result = new ArrayList<String>();
String line = "";
while ((line = s.nextLine()) != null) {
if (line.isEmpty()) break;
result.add(line);
}
for (String ss : result) {
System.out.println(ss);
}
}
It outputs exactly what is inputed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.