我如何使用do-while循环来提示和读取用户的字符串?阵列清单

 收藏

我的代码一直在出现错误,特别是在

ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];

错误告诉我“;预期”,我在这里做错了什么?

Scanner scnr = new Scanner(System.in);   
        System.out.println("how many lines of text do you want to enter");

        int numLines = 0;
        numLines = scnr.nextInt();
        System.out.println();

        ArrayList lines = new ArrayList();
        scnr.nextLine();

        int i = 0;
        do{

            System.out.println("Enter your text: ");
            String text = scnr.nextLine();
          ArrayList<String> input = new ArrayList<String>();
            i++;


        for (i = 0; i < numLines; i++)
        {
           ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
        }

        for (String element: ArrayList<String> Lines)
        {
            System.out.println(element);
        }
            } while(i != 0); 
回复
  • 如你所愿

    ArrayList<String> input = new ArrayList<String>();
    

    within your loop, it means that it will get re-declared and initialised for every iteration of that loop, so move this declaration to before your do

    Next, to add to this loop, use add method

    String text = scnr.nextLine();
    input.add (text);
    

    To simplify, you do not need a do as you have a number of times that you want to loop

        Scanner scnr = new Scanner(System.in);   
        System.out.println("how many lines of text do you want to enter");
    
        int numLines = scnr.nextInt();
        System.out.println();
    
        scnr.nextLine();
    
        ArrayList <String> lines = new ArrayList <> ();
    
        for (int i = 0; i < numLines; i++) {
            System.out.println("Enter word...");
            String text = scnr.nextLine();
            lines.add(text);
        }