当前位置: 首页 > 知识库问答 >
问题:

“尝试-捕获”选项在 Java 中不起作用

纪勇军
2023-03-14

我在试着写一个小数

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;
        }
    }
}

共有1个答案

彭烨熠
2023-03-14

<代码>扫描。nextLine()应该是scan.next()

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

 类似资料:
  • 我有一个PowerShell脚本,它从文件中获取文件名列表,在文件夹中搜索文件名,将其存档,然后执行其他操作。 try-catch没有像预期的那样工作。文件列表中有一个文件名不在$some_path中。我期望try-catch停止执行并执行写主机。相反,它不运行写主机,而是继续执行< code > $ data = Get-Content $ current _ file 步骤,这将抛出一个终止错

  • 我有一个存储过程似乎没有正确记录错误。 代码有错误,但 catch 块似乎未生效。 try块相当长,但错误部分很简单,并且在最后出现,所以我已经对此进行了预测。 proc失败的错误是我们的老朋友“列名或提供的值的数量与表定义不匹配”。我已经修复了这个错误 - 这是一个愚蠢的懒惰错误 - 但我感到困惑为什么我的错误日志记录过程似乎没有工作 - 没有行入到我的 ExtractsErrorLog 表中。

  • 问题内容: 根据我的经验,php服务器会向日志或服务器端抛出异常,但是node.js只会崩溃。因为尝试都是异步完成的,所以用try- catch包围我的代码也不起作用。我想知道其他人在生产服务器中做什么。 问题答案: 您可以从Node自己的文档中(http://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexcepti

  • 我在每个if()语句之前以及createUserBackEailAndPassword函数之前调用了try捕获,捕获永远不会工作,错误确实会发生。也通过从Firebase文档中复制代码,而且它也不起作用。 我做错了什么?我想抓住'auth/email-已经在使用'的错误代码(和任何其他)。 我添加了没有try-catch的代码。 });

  • 问题内容: Python 2.7.5 (default, Feb 26 2014, 13:43:17) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type “help”, “copyright”, “credits” or “license” for more information. >>> import sys >>> try: … sy

  • 问题内容: 您可以尝试/捕获Java中的堆栈溢出异常吗?它似乎在向任一方向投掷自己。当程序溢出时,我想“惩罚”该值。 问题答案: 似乎可以工作: