首页 > 解决方案 > 将用户输入存储在字符串数组中

问题描述

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

标签: javaarraysstringjava.util.scanner

解决方案


您的解决方案中不需要字符串数组。

尝试这个 :-

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

推荐阅读