I'm completely stuck having tried for hours.
Say I want to scan in a program, eg
// my program in C++
#include <iostream>
/** playing around in
a new programming language **/
using namespace std;
int main ()
{
cout << "Hello World";
cout << "I'm a C++ program"; //use cout
return 0;
}
I want to go through this input and save it in an ArrayList<String>
Here is my code:
public static void main(String[] args) {
ArrayList<String> testCase = new ArrayList<String>();
int count = 0;
Scanner s = new Scanner(System.in);
testCase.add(s.nextLine());
while (s.hasNext() && s.next().length() > 1) {
testCase.add(s.nextLine());
}
System.out.println("\n\n\n\n----------------Output from loop------------------");
for (String tc : testCase) {
System.out.println(tc);
}
}
This outputs:
----------------Output from loop------------------
// my program in C++
<iostream>
playing around in
The scanning is supposed to stop if 2 blank lines occur in a row.
Any help is greatly appreciated.
The problem in your code is that you're using s.next()
in your condition. This methods consumes the next token, which cannot be consumed anymore.
I don't know what s.next().length() > 1
is meant to check, but if you remove that part of the condition, you will consume every line without any issue.
The following code will scan every line, and stop whenever two consecutive empty lines are met :
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("C:\\Users\\Simon\\Desktop\\a.txt"));
ArrayList<String> testCase = new ArrayList<String>();
int emptyLines = 0;
String line;
Scanner s = new Scanner(System.in);
testCase.add(s.nextLine());
while (s.hasNext() && emptyLines < 2) {
line = s.nextLine();
if (line.isEmpty()) {
emptyLines++;
} else {
emptyLines = 0;
}
testCase.add(line);
}
System.out.println("\n\n\n\n----------------Output from loop------------------");
for (String tc : testCase) {
System.out.println(tc);
}
}
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.