Мой вопрос очень прост. Я изучаю с помощью Oracle iLearning простую и простую Java, но у них нет решенных вопросов, и я возился со своим мозгом, пытаясь решить это. У меня есть файл .txt, который выглядит так:
128 3.141 Щенки!
Line2 Это Line2. 100002 Это все еще Line2.
Линия3
Line4 444 Синий Бампер 90 120*
И что мне нужно, так это найти два токена (т.е. 90 и 120) после "BlueBumper".
Мой код выглядит примерно так:
import java.util.Scanner;
public class Input04 {
public static void main(String[] args){
Scanner sc = new Scanner(Input04.class.getResourceAsStream("input04text.txt"));
//Edit these lines to advance the scanner
sc.nextLine();
System.out.println(sc.nextLine());
//Does this line contain "BlueBumper"?
System.out.println(sc.findInLine("BlueBumper"));
//Store the next two numbers as xPosition and yPosition
//Print these positions
int x = sc.nextInt();
int y = sc.nextInt();
System.out.println("X: "+ x +", Y: " + y);
sc.close();
}
}
Я пытаюсь сохранить одну переменную x и одну переменную y с каждым токеном. Я действительно не знаю, почему упражнение предложило первую пару System.out.println, чтобы найти экземпляр «BlueBumper», поскольку мне не нужно ничего печатать до последней строки, но мне кажется, что я не Я совершенно не понимаю, как заставить его работать в этом контексте.
Я вижу единственное, что вы делаете неправильно, это то, что вы не переходите к строке 4. вам нужно добавить дополнительный sc.nextLine();. ниже работает нормально для меня.
public class Input04 {
public static void main(String[] args) {
Scanner sc = new Scanner(Input04.class.getResourceAsStream("input04text.txt"));
//Edit these lines to advance the scanner
// below will print, if you print : 128 3.141 Puppies!
sc.nextLine();
// will print : Line2 This is Line2. 100002 This is still Line2.
System.out.println(sc.nextLine());
// will print, if you print : Line3
sc.nextLine();
//Does this line contain "BlueBumper"?
System.out.println(sc.findInLine("BlueBumper"));
//Store the next two numbers as xPosition and yPosition
//Print these positions
int x = sc.nextInt();
int y = sc.nextInt();
System.out.println("X: "+ x +", Y: " + y);
sc.close();
}
}
Я думаю, что наиболее элегантным было бы сопоставление регулярных выражений, таких как
.*BlueBumper ([0-9]+) ([0-9]+).*
.