如何循环整个程序?

时间:2018-08-03 15:04:14

标签: java

我是编码的初学者,所以我想在我想创建的简单程序/游戏中寻求帮助

我正在尝试创建一个简单的争夺游戏,而我差不多已经完成了... 我想循环我的整个程序,但是我遇到了问题。 关于如何循环程序的任何建议?或使用我正在使用的方法进行更正...任何帮助将不胜感激:)

public static void main(String[] args) throws InterruptedException {        
    String[] word = new String[22];


    word[0] = "Package";
    word[1] = "Import";
    word[2] = "Public";
    word[3] = "Private";
    word[4] = "Static";
    word[5] = "Void";
    word[6] = "String";
    word[7] = "Integer";
    word[8] = "Character";
    word[9] = "Boolean";
    word[10] = "Public";
    word[11] = "High-Level";
    word[12] = "Low-Level";
    word[13] = "Class";
    word[14] = "Statements";
    word[15] = "Constructor";
    word[16] = "Default";
    word[17] = "Method";
    word[18] = "Declaration";
    word[19] = "Object";
    word[20] = "Variable";
    word[21] = "Null";

    String rword = word[(int) (Math.random() * word.length)];
    Shuffle srword = new Shuffle();
    srword.shuffle(rword,rword);

}
public void shuffle(String input,String rword) throws InterruptedException{
  Scanner scanner = new Scanner(System.in);

    List<Character> characters = new ArrayList<>();
    for(char c:input.toCharArray()){
        boolean scword = characters.add(c);
    }
    StringBuilder scrmbldword = new StringBuilder(input.length());
    while(!characters.isEmpty()){
        int randPicker = (int)(Math.random()*characters.size());
        scrmbldword.append(characters.remove(randPicker));
    }

    // Game loads the game xD
    System.out.print("\rLoading");
            Thread.sleep(500);
            System.out.print("\rLoading.");
            Thread.sleep(500);
            System.out.print("\rLoading..");
            Thread.sleep(500);
            System.out.print("\rLoading...");
            Thread.sleep(500);
            System.out.print("\rLoading....");
            Thread.sleep(500);
            System.out.print("\rLoading.....");
            Thread.sleep(500);
            System.out.print("\rLoading.....");
            Thread.sleep(100);
            System.out.print("\rCompleted");

    // Game introduces itself to the user.
    Thread.sleep(2000);
    System.out.println("\rWelcome to Scramble PT!");
    Thread.sleep(1000);
    System.out.println("This is a game where you guess a word that is scrambled.");

    // Game request name input from the user
    Thread.sleep(2000);
    System.out.println("First, What is your Name?");
    String name = scanner.next();

    // Game prints name input from the user
    Thread.sleep(2000);
    System.out.println("Hello " + name + ",Please get ready because the game is Starting!");

    // Game ask the user for Y/N input
    Thread.sleep(2000);
    System.out.print("Are you ready?: ");
    String yon = scanner.next();

    switch (yon) {
        case "Yes":
            // Game prints the Scrambled Word
            System.out.print("Scrambled Word: ");
            System.out.print(scrmbldword.toString());
            // Game let user enter it's guess
            System.out.print("\nEnter your Answer: ");
            String answer;
            boolean win;
            win = false;

                while (win == false){
                   answer = scanner.next();  
                if (!answer.equalsIgnoreCase(rword)){                       
                    System.out.println("Wrong, please Try Again!");
                    Thread.sleep(500);
                    System.out.print("Enter your Answer: ");
                    continue;
                }else{     
                    System.out.println("Correct!");
                    Thread.sleep(500);
                    System.out.print(String.format("Thanks for playing %s!",name));
                    win = true;
                    Thread.sleep(500);
                    System.out.println("Would you like to try again?");
                    System.out.println("Enter Yes or No: ");
                    String retry = scanner.next();
                    Thread.sleep(500);

                        if (retry.equalsIgnoreCase("Yes")){
                            System.out.println("Alright! reloading the game");

                            return;
                        }else 
                            if (retry.equalsIgnoreCase("No")){
                            System.out.println(String.format("Goodbye! %s !",name));
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down.");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down..");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down...");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down....");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down.....");
                        }else{
                            System.out.println("I can't understand you.... So.... Bye!");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down.");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down..");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down...");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down....");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down.....");    
                            }break;
             }
                }
        case "No":
            Thread.sleep(500);
            System.out.print("Ok, Please come again!");
            break;
        default:
            Thread.sleep(500);
            System.out.print("Please answer exactly Yes or No!");
            break;
    }
}

}

3 个答案:

答案 0 :(得分:1)

我假设这是您要寻找的东西,但是在使用和使用此代码之前,请考虑以下几件事:代码的编写方式并未最大限度地利用面向对象的Java。如果该代码具有多个类,则该代码更易读,并且通常更好。 Main类只能用于初始化另一个类或一组类。好的,现在输入代码。这应该可以解决问题:

    import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Shuffle {
    public static void main(String[] args) {
        startGame();
    }
    public static void shuffle(String input,String rword) throws InterruptedException{
        Scanner scanner = new Scanner(System.in);

        List<Character> characters = new ArrayList<>();
        for(char c:input.toCharArray()){
            boolean scword = characters.add(c);
        }
        StringBuilder scrmbldword = new StringBuilder(input.length());
        while(!characters.isEmpty()){
            int randPicker = (int)(Math.random()*characters.size());
            scrmbldword.append(characters.remove(randPicker));
        }

        // Game loads the game xD
        System.out.print("\rLoading");
        Thread.sleep(500);
        System.out.print("\rLoading.");
        Thread.sleep(500);
        System.out.print("\rLoading..");
        Thread.sleep(500);
        System.out.print("\rLoading...");
        Thread.sleep(500);
        System.out.print("\rLoading....");
        Thread.sleep(500);
        System.out.print("\rLoading.....");
        Thread.sleep(500);
        System.out.print("\rLoading.....");
        Thread.sleep(100);
        System.out.print("\rCompleted");

        // Game introduces itself to the user.
        Thread.sleep(2000);
        System.out.println("\rWelcome to Scramble PT!");
        Thread.sleep(1000);
        System.out.println("This is a game where you guess a word that is scrambled.");

        // Game request name input from the user
        Thread.sleep(2000);
        System.out.println("First, What is your Name?");
        String name = scanner.next();

        // Game prints name input from the user
        Thread.sleep(2000);
        System.out.println("Hello " + name + ",Please get ready because the game is Starting!");

        // Game ask the user for Y/N input
        Thread.sleep(2000);
        System.out.print("Are you ready?: ");
        String yon = scanner.next();

        switch (yon.toLowerCase()) {
            case "yes":
                // Game prints the Scrambled Word
                System.out.print("Scrambled Word: ");
                System.out.print(scrmbldword.toString());
                // Game let user enter it's guess
                System.out.print("\nEnter your Answer: ");
                String answer;
                boolean win;
                win = false;

                while (!win){
                    answer = scanner.next();
                    if (!answer.equalsIgnoreCase(rword)){
                        System.out.println("Wrong, please Try Again!");
                        Thread.sleep(500);
                        System.out.print("Enter your Answer: ");
                    }else{
                        System.out.println("Correct!");
                        Thread.sleep(500);
                        System.out.print(String.format("Thanks for playing %s!",name));
                        win = true;
                        Thread.sleep(500);
                        System.out.println(" Would you like to try again?");
                        System.out.println("Enter Yes or No: ");
                        String retry = scanner.next();
                        Thread.sleep(500);

                        if (retry.equalsIgnoreCase("Yes")){
                            System.out.println("Alright! reloading the game");
                            startGame();
                            return;
                        }else
                        if (retry.equalsIgnoreCase("No")){
                            System.out.println(String.format("Goodbye! %s !",name));
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down.");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down..");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down...");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down....");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down.....");
                        }else{
                            System.out.println("I can't understand you.... So.... Bye!");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down.");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down..");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down...");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down....");
                            Thread.sleep(200);
                            System.out.println("\rGame Shutting down.....");
                        }break;
                    }
                }
            case "no":
                Thread.sleep(500);
                System.out.print("Ok, Please come again!");
                break;
            default:
                Thread.sleep(500);
                System.out.print("Please answer exactly Yes or No!");
                break;
        }
    }

    public static void startGame() {
        String[] word = new String[22];

        word[0] = "Package";
        word[1] = "Import";
        word[2] = "Public";
        word[3] = "Private";
        word[4] = "Static";
        word[5] = "Void";
        word[6] = "String";
        word[7] = "Integer";
        word[8] = "Character";
        word[9] = "Boolean";
        word[10] = "Public";
        word[11] = "High-Level";
        word[12] = "Low-Level";
        word[13] = "Class";
        word[14] = "Statements";
        word[15] = "Constructor";
        word[16] = "Default";
        word[17] = "Method";
        word[18] = "Declaration";
        word[19] = "Object";
        word[20] = "Variable";
        word[21] = "Null";

        String rword = word[(int) (Math.random() * word.length)];
        try {
            shuffle(rword,rword);
        } catch (InterruptedException ignored) {}
    }

}

答案 1 :(得分:0)

初恋: -main方法通常应具有最低限度的代码。主要方法实际上应该只是初始化程序并启动它,因此将其中的一些内容移至构造函数或其他地方

无论如何,您正在做的事情是功能确定的,但请尽量避免养成不良习惯:通过从其他方法内部调用方法,将代码分成较小的块。这将使调试容易得多,并使其他人更容易阅读。但是,您正在做一些不错的事情,例如为变量赋一个体面的名称,并且您是一个初学者,因此使东西具有功能性是第一步,因此您做得很好。

关于您的问题,当您真正想在程序中循环一个关键方法时,您想循环整个程序,而程序本身并不需要循环,这并不是要实现的目标。一个程序无法循环自身,因为要循环执行什么(只有另一个程序可以这样做)?

因此,您需要做的是将初始化内容从main方法中移除,然后将其放入可以从main方法中调用的其他方法中。在这个新方法中,在游戏初始化代码内创建while循环,并在初始化类的实例后调用main方法中的方法(main方法是静态的,因此必须在内部将类创建为变量)。

执行以下操作:

 //Make a new class containing just the main method
 public static void main(String[] args){
  //Substitute Class for the name of your class and initiate it as below
  Class myClass = new Class():
  //
  myClass.initiate();
  }

  //Then in your actual action class 
  public void initiate(){
  while(condition){
   //call the shuffle method inside a while loop, if you want to initiate inside too 
   //then have your array building stuff in a method you call here too
   buildArray();
   shuffle();
   } 
  }

希望这对兄弟有帮助

答案 2 :(得分:0)

惰性选项1:将main()的内容包装在while(true){ main内部的任何内容}

懒惰选项2:在要重新启动的末尾创建一个新线程,即new Thread(new Runnable(){public void run(){main(null);}})。start();

任务可能是做什么的:在末尾添加一些问题,询问您是否要再次玩游戏,如果可以,请以某种方式再次循环游戏。

我不得不问,为什么是假的加载屏幕?