java - 将用户输入存储在字符串数组中
问题描述
我是java的初学者。我尝试编写一个程序来从命令行参数中读取一系列单词,并找到给定单词的第一个匹配项的索引。喜欢的用户可以输入“我爱苹果”,给定的单词是“苹果”。程序将显示“'apple'的第一个匹配的索引是2”。
到目前为止我所做的没有用。我将输入存储到字符串数组中的方式不正确吗?
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);
}
}
}
}
解决方案
您的解决方案中不需要字符串数组。
尝试这个 :-
System.out.println("enter sentence ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("enter the given word to fin the index ");
sc = new Scanner(System.in);
String toBeMatched = sc.nextLine();
if (input.contains(toBeMatched)) {
System.out.println("index is " + input.indexOf(toBeMatched));
} else {
System.out.println("doesn't contain string");
}
推荐阅读
- python-3.x - QFileDialog:参数 1 具有意外类型“str”
- python - 我连接的这个 python 打印语句的最后一行有什么错误?
- amazon-dynamodb - Dynamodb UnmarshalListOfMaps 返回 InvalidUnmarshalError emptyOrigError
- node.js - 为每个项目单独升级节点版本
- machine-learning - tfidf.idf_ 在代码中这是什么意思
- python - 如何调用此函数来检查是否收到消息然后发送响应?
- r - 如何将时间序列数据填充到数据框中?
- python - Python zmq 连接
- hive - 通过返回 null 和错误的结果来进行 Hive 订单
- java - 仅提示用户输入正数