繁体   English   中英

Try-Catch选项无法在Java中运行

[英]Try-Catch option does not run in Java

我试图用Java编写一个十进制和二进制转换器。 我正在尝试使用try&catch选项进行错误处理。 例如,如果任何一个输入“ a”为二进制数,它将打印“错误的输入”。 我已经为此功能使用了parse和try-catch。 但这是行不通的。 我试图找出问题所在,但未能找到问题。 有人可以帮我这个代码吗? 当我写“ 1”进行二进制到十进制的转换时,它将到达代码的末尾。 整个代码在这里:

package binary.with.decimal;

import java.util.Scanner;

public class RiaJava {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int binaryp = 0;
        int n;
        int base = 2;
        int result = 0;
        int multiplier = 1;

        System.out.println("1.Binary to Decimal \n 2.Decimal to Binary");
        System.out.println("Enter Your Option Number:");
        n = scan.nextInt();

        switch (n) {
        case 1:
            System.out.println("Input Binary Number:");

            String binary = scan.nextLine();
            scan.close();
            try {
                binaryp = Integer.parseInt(binary);
            }

            catch (NumberFormatException e) {
                System.out.println("Wrong Input!!!");
            }

            while (binaryp > 0) {
                int residue = binaryp % base;
                binaryp = binaryp / base;
                result = result + residue * multiplier;
                multiplier = multiplier * 10;
            }
            System.out.println("Decimal....." + result);

            break;
        case 2:
            System.out.println("Input Decimal Number:");
            int decimal = scan.nextInt();
            scan.close();

            while (decimal > 0) {
                int residue = decimal % base;
                decimal = decimal / base;
                result = result + residue * multiplier;
                multiplier = multiplier * 10;
            }
            System.out.println("Binary....." + result);
            break;
        default:
            System.out.println("you have selected wrong option number");
            break;
        }
    }
}

scan.nextLine()应该是scan.next()

nextLine()不等待用户输入,而是读取剩余的缓冲区,直到下一行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM