我得到了这个练习,但我无法找到一种方法来捕捉新的线路。你能帮我吗?
编写一个程序,读取用户输入直到出现空行。对于每个非空字符串,程序将字符串按空格分割,然后打印包含 av 的片段,每个片段占一个新行。 这是我的代码:
public class AVClub {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> str = new ArrayList();
String line;
while (!(line = scanner.nextLine()).equals("")){
str.add(line);
}
for(int i=0; i<str.size();i++){
if(str.get(i).contains("av")){
System.out.println(str.get(i));
}
}
}
}
最佳答案
您的代码中错误地实现了以下要求:
For each non-empty string, the program splits the string by spaces and then prints the pieces that contain av, each on a new line.
应该是:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> str = new ArrayList();
String line;
System.out.print("Enter sentences (blank line to terminate): ");
while (!(line = scanner.nextLine()).equals("")) {
str.add(line);
}
System.out.println("Words containig 'av' are: ");
for (int i = 0; i < str.size(); i++) {
line = str.get(i);
String[] words = line.split("\\s+"); // Split the string on spaces
for (String word : words) {
if (word.contains("av")) {
System.out.println(word);
}
}
}
}
}
说明:你必须检查每个句子中的每个单词是否包含av
。您的代码会检查每个句子中是否有 av
。
示例运行:
Enter sentences (blank line to terminate): harry is a good boy
my name is avinash
Is there any seats available in the aviation training
hello world
Words containig 'av' are:
avinash
available
aviation
注意:如果您需要以不区分大小写的方式检查 av
,请按 if (word.toUpperCase().contains("AV"))
。
关于java - 如何检测输入中的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60821573/