我想在这里发生的是让用户输入“开始”。如果用户输入启动,则程序必须从数组中给出一个随机词,然后要求用户输入“ next”,当用户输入“ next”时,程序将给出另一个随机词,则程序将要求“ next”再次输入,依此类推...您就知道了。

这是一些代码,我以为会产生这种效果,但是它所做的只是打印“键入开始看到一个很酷的单词”
用户输入“开始”
然后程序什么也不返回。

任何建议将不胜感激,如果您能告诉我为什么我的代码正在这样做,我将非常感激,因为我可以从中学习。
谢谢

这是我写的代码:

   import java.util.Scanner;
import java.util.Random;
public class Words {
    public static void main(String[]args){


        Scanner scan = new Scanner(System.in);
        String words[] = {"Iterate:","Petrichor:"};
        String input = "";

        System.out.println("type *start* to see a cool word");
        input = scan.nextLine();

        while(!input.equals("start")){
        String random = words[new Random().nextInt(words.length)];
        System.out.println(random);
        System.out.println();
        System.out.println("type *next* to see another cool word");
        while(input.equals("next"));
        }
    }
}

最佳答案

您想将输入读数包装成一个循环:

import java.util.Scanner;

import java.util.Random;
public class Words {
  public static void main(String[]args){
    Scanner scan = new Scanner(System.in);
    String words[] = {"Iterate","Petrichor"};
    String input = "";

    while ( !input.equals("start") ) {
       System.out.println("type *start* to begin");
       input = scan.nextLine();
    }

    String random = (words[new Random().nextInt(words.length)]);
  }
}


请注意,在您的特定示例中,循环条件适用于if语句,因此无需if语句。

更新资料

如果您需要在用户键入下一步时保持运行状态,则可以将所有内容包装在do .. while循环内,这样它至少执行一次:

导入java.util.Scanner;

import java.util.Random;
public class Words {
   public static void main(String[]args){
      Scanner scan = new Scanner(System.in);
      String words[] = {"Iterate","Petrichor"};
      String input = "";
      do {
         do {
            System.out.println("type *start* to begin");
            input = scan.nextLine();
         } while ( !input.equals("start") );

         String random = (words[new Random().nextInt(words.length)]);
         System.out.println("type *next* to repeat");
         input = scan.nextLine();
      }
   } while ( input.equals("next") );
}

10-07 19:43
查看更多