gpt4 book ai didi

java - 将用户输入存储在字符串数组中

转载 作者:行者123 更新时间:2023-12-01 07:01:01 25 4
gpt4 key购买 nike

我是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");
}

关于java - 将用户输入存储在字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52026289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com