我是java初學(xué)者。我嘗試編寫一個程序來從命令行參數(shù)中讀取一系列單詞,并找到給定單詞的第一個匹配項的索引。喜歡用戶可以輸入“我愛蘋果”,給定的詞是“蘋果”。程序?qū)@示“'apple' 第一個匹配項的索引為 2”。到目前為止我所做的不起作用。這是我將輸入存儲到字符串?dāng)?shù)組中的方式不正確嗎?import java.util.Scanner;public class test { public static void main(String [] args) { System.out.println("Enter sentence: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); int num=1; String sentence[]=new String[num]; for(int i=0; i< num; i++) { sentence[i] = input; // store the user input into the array. num = num+1; } System.out.println("Enter the given words to find the index of its first match: "); Scanner sc2 = new Scanner(System.in); String key = sc2.next(); for(int j=0; j<num; j++) { while (sentence[j].equals(key)) { System.out.println("The index of the first match of "+key+" is "+j); } } } }
添加回答
舉報
0/150
提交
取消