【发布时间】:2021-06-13 02:21:39
【问题描述】:
我一直在尝试制作一个简单的菜单,用户可以在其中输入要添加到段落中的行,然后搜索他们输入的单词。 但是,在搜索单词的情况下(案例 3),如果他们搜索的单词不在第一行,它就不起作用(我没有收到错误),但我的代码在一个单独的文件中使用手动输入工作。
这是我的课
public class Paragraph {
String[] lines;
int lineCount;
public Paragraph(String[]lines,int lineCount) {
this.lines = lines;
this.lineCount = lineCount;
}
public static void main(String[] args) {
int lineCount=0 , i = 0;
String[] lines = new String[10];
String curline ,search;
boolean loop= true;
Paragraph parag = new Paragraph(lines, lineCount);
while(loop) {
Scanner myScanner = new Scanner(System.in);
System.out.println();
System.out.printf("%s\n","1) Enter a new line");
System.out.printf("%s\n","2) Display the paragraph");
System.out.printf("%s\n","3) Search for word");
System.out.printf("%s\n","4) Exit");
int choice= myScanner.nextInt();
myScanner.nextLine();
switch(choice) {
case 1:
System.out.println("Enter your line:");
curline = myScanner.nextLine();
lineCount = i;
System.out.println("Done!!");
parag.lines[i] = curline + " ";
parag.lineCount = i;
i++;
break;
case 2:
int index;
for(index=0; index<i; index++) {
System.out.printf("(%d) %s\n",index+1, lines[index]);
}
break;
case 3:
System.out.println("Enter pharese to be searched:");
search = myScanner.nextLine();
String toBeSearched = search;
String[] divide = toBeSearched.split(" ");
for(int i1 = 0; i1 < divide.length ; i1 ++) {
String word = divide[i1];
for(int y = 0; y < lineCount; y++) {
if(lines[y].contains(word)) {
System.out.println(word + " found at line: "+ y);
}
}
}
break;
case 4:
loop = false;
}
}
}
}
我在想我在案例 1 中采用线的方式可能会导致问题,但这是我测试案例 3 的另一个文件,它在这里不起作用
这是我测试案例 3 的单独文件
public static void main(String[] args) {
String toBeSearched;
boolean intIndex = false ;
String paragraph[] = {"Hello my name is","Jack the reaper", "what up"};
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int i = 0; i < divide.length ; i ++) {
String word = divide[i];
for(int y = 0; y < paragraph.length ; y++) {
if(paragraph[y].contains(word)) {
System.out.println(word + " found at line: "+ y);
}
}
}
}
当我在这里搜索“Hello Jack”时,它给了我
你好在第 0 行找到 杰克在第 1 行找到
但在我上面的课程中它没有任何想法?
【问题讨论】:
-
@Typhon 它也可以是多个词输出 Hello 在第 1 行找到,Jack 在第 2 行找到
标签: java arrays class search find