创建确认循环

时间:2018-10-01 07:06:50

标签: java loops

因此,我希望在Java中进行一些基于文本的冒险。我是一个初学者,我想让用户选择他们的姓名,性别等,然后让每一位用户要求确认,然后在确认所有输入后再次询问。

我对循环或类似的东西不是很了解,因此,如果有人可以上一堂迷你课以及关于如何使它工作的建议,我将不胜感激。谢谢!

这纯粹是出于娱乐目的,我欢迎任何建设性的批评将使之更加有效。请不要介意代词的混乱。

import java.util.*;
public class Emu {
    public static void main(String[] args) {
    Scanner menu = new Scanner(System.in);

    System.out.println("What is your hero's name?");                                 
    String name = menu.nextLine();
    System.out.println("So their name is " + name + "? (Y/N)");
    char cc1 = menu.next().charAt(0);
    //If yes, continues, if not, loops back to the question where the name is set
    System.out.println();

    System.out.println("Okay, is " + name + " a male or female? (M/F)");
    char gender = menu.next().charAt(0);
    String genPro, genPos, genRef, genChild, genAdult;
    switch (gender) {
        case 'M':
        genPro = "He";
        genPos = "His";
        genRef = "Him";
        genChild = "boy";
        genAdult = "guy";
        break;
        case 'F':
        genPro = "She";
        genPos = "Hers";
        genRef = "Her";
        genChild = "girl";
        genAdult = "woman";
        break;
        default:
        genPro = "It";
        genPos = "It";
        genRef = "It";
        genChild = "It";
        genAdult = "It";
        break;
    }
    System.out.println("Okay! So " + name + " is a " + genChild + "? (Y/N)");
    char cc2 = menu.next().charAt(0);
    //If yes, continues, if not, loops back to the question where the gender is set

    System.out.println("So " + name + " is a " + genChild + "? (Y/N)");
    char cc3 = menu.next().charAt(0);
    //If yes, continues, if not, loops back to the question where the name is set

    System.out.println(name + " was born a healthy young " + genChild + ", in the city of PLACEHOLDER");

}

}

1 个答案:

答案 0 :(得分:0)

do-while loop是无条件执行一次甚至可能需要回溯的常用循环构造。

根据您要如何处理无效输入(即不是Y或N),您可能需要两个do-while循环。在下面的示例中,它将一直提示“因此,他们的名字是...”,直到输入Y或N,并且仅在输入N时才再次询问姓名。

char confirmation;
String name;
do
{
    System.out.println("What is your hero's name?");
    name = menu.nextLine();
    do {
        System.out.println("So their name is " + name + "? (Y/N)");
        confirmation = menu.nextLine().charAt(0);
    } while (confirmation != 'N' && confirmation != 'Y');
}
while (confirmation == 'N');