有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java扫描器可读取13个单词

所以我做了这个扫描器,我希望它能用1到3个字符串。1是它可以接受的最小字符串数,3是最大字符串数。到目前为止,我的输出是:

You can search 1 - 3 words only : 3
Type a name: word1 
Type a name: word2
Type a name: word3

相反,由于我的程序将执行多个字符串搜索,是否有一种方法可以将这些单词放在多个数组中

public static void main(String[]args) throws IOException{

    int nnames;
    String[] stringSearch;

    System.out.print("You can search 1 - 3 words only : ");
    Scanner in = new Scanner(System.in);
    nnames = Integer.parseInt(in.nextLine().trim());

    stringSearch = new String[nnames];
    for (int i = 0; i < stringSearch.length; i++){
            System.out.print("Type a name: ");
            stringSearch[i] = in.nextLine();

    }

共 (1) 个答案

  1. # 1 楼答案

    像这样的

        public static void main(String[]args) throws IOException{
            int nnames;
            int ind = 0;
            int maxSearch = 10000;//this is max times we can do searching
            String[][] stringSearch = new String[maxSearch][];
    
            System.out.print("You can search 1 - 3 words only(else means stop search) : ");
            Scanner in = new Scanner(System.in);
            nnames = Integer.parseInt(in.nextLine().trim());
    
            while(nnames>=1 && nnames<=3){
                stringSearch[ind] = new String[nnames];
                for (int i = 0; i < stringSearch.length; i++){
                    System.out.print("Type a name: ");
                    stringSearch[ind][i] = in.nextLine();
                }
                ind++;
                nnames = Integer.parseInt(in.nextLine().trim());
            }
        }