【问题标题】:How to return to a specific line of code in javajava如何返回到特定的代码行
【发布时间】:2014-12-04 21:33:27
【问题描述】:

好的,这是我在这里的第一篇文章。 (对我好点 :)) 我刚学 Java 两周,想创建一个应用程序,可以完成总体、平均和平均评分者的工作。 我的问题是。一个操作结束后如何返回到特定的代码行 例如:我想让代码运行String menu1="输入你想要的操作数";在找到总数或平均值之后。 在此先感谢

import java.util.Scanner;
public class grader
{
    public static void main (String args[])
    {
    Scanner input=new Scanner(System.in);
    System.out.println ("Input your Chemistry marks");
    float a= input.nextFloat();

    System.out.println ("Input your Biology marks");
    float b= input.nextFloat();

    System.out.println ("Input your Physics marks");
    float c= input.nextFloat();

    String menu1="Input the number of the operation you desire ";
    String op1="1. Total ";
    String op2="2. Average ";
    String op3="3. Grade ";
    String op4="4. Exit ";
    System.out.println (menu1+op1+op2+op3+op4);

    Scanner menuselect=new Scanner(System.in);
    int option= input.nextInt();

            float tot=(a+b+c);
            float avg=((a+b+c)/3);
    if (option==1)
        System.out.println ("Your total is "+tot);

    else if (option==2)
        System.out.println ("Your average is "+avg);

    else if (option==3)
        if (avg<0.0)
            System.out.println ("Please input proper data");
        else if (avg<=49.9)
            System.out.println ("Fail");
        else if (avg<=69.9)
            System.out.println ("Pass");
        else if (avg<=100.0)
            System.out.println ("Excellent");
        else 
            System.out.println ("Please input proper data");
    }
}

【问题讨论】:

标签: java repeat


【解决方案1】:

我建议使用 do-while 循环。 do while 循环至少运行一次,这是必要的,因为您的程序需要至少运行一次。将 Input the operation number 中的所有语句放到 do while loop 下的计算语句中。它应该工作得很好。

【讨论】:

  • 此解决方案已由其他回答者发布。明确您的帖子所提供的附加价值广告
【解决方案2】:

在您的情况下,您应该使用 while 循环和 continuebreak。第二种选择,您可以使用标记为 break 的语句(解释为 here)。

顺便说一句,在 java 语言中有一个 goto 关键字。但它没有实施(或删除)。阅读here了解更多详情。

【讨论】:

    【解决方案3】:

    您应该使用do-while 循环。它的工作原理是执行一些代码,检查条件是否计算为true,如果是,则再次执行代码。

    do {
        //your code here
    }
    while (/*some condition*/);
    

    【讨论】:

      【解决方案4】:

      通常当您想要重复一行或多行代码时,您会使用循环来执行此操作。一般来说,一个循环是这样设置的:

      while(loopGuard){
      
          //code to repeat
      
      }
      

      loopGuard 是一些在循环内更新的布尔语句。循环内的代码将继续执行,直到您的 loopGuard 语句不再为真。

      在您的情况下,您可能希望循环直到用户按下某个按钮,直到它运行了一定次数,或者您选择的任何其他任意原因。要记住的主要事情是确保您的循环保护最终会变为错误,否则您会发现自己处于无限循环中。

      【讨论】:

        猜你喜欢
        • 2015-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多