【问题标题】:Java programming how to run both integer and floatJava编程如何同时运行整数和浮点数
【发布时间】:2015-09-14 03:27:49
【问题描述】:

我的 java 作业需要帮助,我有大部分代码并且它可以运行,但是我的老师希望能够输入整数或浮点数,目前它只处理整数并在你输入时出错浮点数

public class ErrorHandling {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i1 = 0;
        while (true) {
            try {
                System.out.print("Enter a number: ");
                i1 = sc.nextInt();
                break;
            } catch (InputMismatchException e) {
                System.out.println("try again");
                sc.nextLine();
            }
        }
        System.out.println("you entered: " + (i1));
    }
}

【问题讨论】:

  • 请阅读帮助部分以了解如何发布代码,然后请尝试重新发布您的格式化代码。
  • float 也可以采用整数,因此只需使用它即可。它不能以其他方式工作,即int 不能容纳float

标签: java


【解决方案1】:

你的代码应该是这样的:

public class ErrorHandling {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    float i1 = 0;
    while (true) {
        try {
            System.out.print("Enter a number: ");
            i1 = sc.nextFloat();
            break;
        } catch (InputMismatchException e) {
            System.out.println("try again");
            sc.nextLine();
        }
      }
      System.out.println("you entered: " + (i1));
   }
 }

因为float 变量也可以接受整数值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2014-09-12
    • 2017-07-26
    • 2011-01-10
    • 1970-01-01
    相关资源
    最近更新 更多