【问题标题】:Can I use "return" in here or any ideas?我可以在这里使用“return”或任何想法吗?
【发布时间】:2015-10-10 02:13:09
【问题描述】:

我真的是 Java 新手,我的大部分知识都是自学的。你能帮我解决这个问题吗?

我们的老师要我们制作一个关于 Java 的菜单。像这样的输出在哪里..

菜单 1 - Java 历史 2- Java 关键字 3 - Java 数组等。 .

你想读一个吗(是/否): //如果是的话

请输入菜单号: // 然后它会显示一个信息..

//我的问题是如何将新输入的值连接到第一个方法,这样我就不用重新写了...

这是我的想法.. 但我卡住了..

import java.util.Scanner;

public class Program {

public static void main (String [] args) {

System.out.println("Please enter a number:");
int x = nextInt();

if (x == 1) {

     for (int x = 5; x == 5;x++) // array of 1(first menu)

System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")

// return to if with it's new entered value....

     }
    else if (x == 2)  {
    for loop of array 2

    System.out.println ("Do you want to read another? (Yes/No):");
    System.out.println ("Please enter a menu number:")

    // return to if with it's new entered value....


}   

else if (x == 3) {
    for loop of array 3

    System.out.println ("Do you want to read another? (Yes/No):");
    System.out.println ("Please enter a menu number:")

    // return to if with it's new entered value....


else if (x ==4) { 
    for loop of array 4

else if (x == 5) {
    for loop of array 5

else if (x == 6) {
    for loop of array 6

else if (x == 7) {
    for loop of array 7

else if (x == 8) {
    for loop of array 8

else if (x == 9) {
    for loop of array 9

else if (x == 10) {
    for loop of array 10

 else {
   //exit the program

【问题讨论】:

  • 你需要一个while循环吗?

标签: java if-statement return


【解决方案1】:

如果我理解正确,您可能希望在程序中实现 While 或 do while 语句。 Example of While and Do While Loops

我不太确定你想用你的程序完成什么,但这里有一个小例子,我很快就如何在你的情况下使用 for 循环。 `import java.util.Scanner;

public class main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        boolean keepGoing = true; //As long as this is true the while statement will continue;
        while (keepGoing) {
            System.out.println("Enter a number");
            int x = scan.nextInt();

            //logic
            if (x == 1) {
                System.out.println("X is equal to 1");
            } else if (x == 2)
                System.out.println("X is equal to 2");


            //prompts the user if they want to keep going.
            System.out.println("Would you like to keep going? Y/N");

            String decision = scan.next();
            if (decision.equalsIgnoreCase("y")) {
                keepGoing = true;
            } else {
                System.out.println("Quitting...");
                keepGoing = false;

            }
        }
    }
}
`

【讨论】:

  • 是的,但我不知道该怎么做
  • 这段代码就是这样做的。它将不断提示用户输入要处理的新号码,直到他/她决定退出。这是 While 循环的工作。
  • 是的,它成功了!!!非常感谢你!!这是一个很大的帮助..我完成了我的代码..下次给你看。如果你没问题,我会把你放在我的致谢中..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多