【问题标题】:Using Try and Catch but can't retry使用 Try and Catch 但无法重试
【发布时间】:2018-03-29 23:02:39
【问题描述】:

我正在使用 try-catch 捕获并显示重试消息,但错误仍然存​​在,它只是显示消息但不给我们重试的机会。我不明白为什么。

import java.util.Scanner;

public class F_to_Celsius {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(
                "Bonjoir lol \n Convertire de Celsius à Fahrenheit tape 1 \n Convertire de Fahrenheit à Celsius tape 2 ");
        int choix;
        try {
            choix = sc.nextInt();
        } catch (java.util.InputMismatchException e) {
            System.out.println("Caractere non numerique § erreur ");
            choix = sc.nextInt();
        }
        System.out.println("D'accord");
        if (choix != 1 | choix != 2) {
            while (choix != 1 && choix != 2) {
                System.out.println("Reassayez , tapez soit 1 soit 2 !!!!!");
                try {
                    choix = sc.nextInt();
                } catch (java.util.InputMismatchException e) {
                    System.out.println("Caractere non numerique 1 ou 2");
                    choix = sc.nextInt();
                }

            }
        }

        if (choix == 1) {
            System.out.println("Entrez la temperature en Celsius ");
            int tempc = sc.nextInt();
            System.out.println(celtofar(tempc) + " F°");
        } else if (choix == 2) {
            System.out.println("Entrez la temperature en Fahrenheit ");
            int tempf = sc.nextInt();
            System.out.println(fartocel(tempf) + "C°");
        }
    }

    public static double celtofar(int x) {
        double y = (x * 1.8) + 32;
        return y;

    }

    public static double fartocel(int x) {
        double y = (x - 32) / 1.8;
        return y;
    }
}

【问题讨论】:

  • 请不要使用代码图片和不正确的问题标签。如果您使用误导性标签,您只会受到负面关注。我已经为您删除了 C 和 Python 标签。请注意,我们无法复制、粘贴和运行代码的图像,因此您需要将代码与您的问题一起发布,并使问题更加具体。
  • 好的,但仍然需要帮助,你能帮我点亮这个吗?
  • 请尝试更好地格式化您的代码,以便我们阅读并帮助您。并请发布您收到的错误消息,也许还有这段代码的逻辑/背景。

标签: java try-catch


【解决方案1】:

将您的代码 sn-p 放入 IntelliJ,它立即警告我您的 if (choix != 1 | choix != 2) { 行始终正确。因为您在这里使用了按位| 来处理两种情况,其中一种情况总是正确的……嗯,它总是正确的。我认为您可以完全删除该条件并让 while 循环运行 0 次或更多次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    相关资源
    最近更新 更多