如何在此代码中使用 try 和 catch(Java)

huangapple go评论97阅读模式
英文:

how to use try and catch in this code (java)

问题

package zed;

import java.util.Stack;

public class decTobin {
    public void convertBinary(int num) {
        Stack<Integer> stack = new Stack<Integer>();
        try {
            while (num != 0) {
                int d = num % 2;
                stack.push(d);
                num /= 2;
            }

            while (!stack.isEmpty()) {
                System.out.print(stack.pop());
            }
        } catch (Exception e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        int decimalNumber = 123;
        System.out.print("binary of " + decimalNumber + " is :");
        new decTobin().convertBinary(decimalNumber);
    }
}
英文:
package zed;

import java.util.Stack;

public class decTobin {
	public void convertBinary(int num) {
		Stack&lt;Integer&gt; stack = new Stack&lt;Integer&gt;();
		while (num != 0) {
			int d = num % 2;
			stack.push(d);
			num /= 2;
		}

		while (!(stack.isEmpty())) {
			System.out.print(stack.pop());
		}
	}

	public static void main(String[] args) {
		int decimalNumber = 123;
		System.out.print(&quot;binary of &quot; + decimalNumber + &quot; is :&quot;);
		new decTobin().convertBinary(decimalNumber);
	}
 }

I do not understand try and catch in java, please help me to add them in this code so I can understand more.

答案1

得分: 1

请尝试这个,我希望这会帮助你找到方法。

while (num != 0) {

try { // 检查代码是否有异常
        int d = num % 2;

            stack.push(d);

            num /= 2
        
        break; // 如果没有异常,跳出循环
    } 
    catch (Exception e) { // 如果出现异常,打印下面的消息
        System.err.println("请输入一个数字!" + e.getMessage());
        continue; // 如果发现异常,继续循环
    }

 }

或者你可以像下面这样捕捉异常

public static void main(String[] args) {

        int decimalNumber = 123;

        System.out.print("十进制数 " + decimalNumber + " 的二进制表示为:");

 try { // 检查代码是否有异常
        new decTobin().convertBinary(decimalNumber);

  } 
        catch (Exception e) { // 如果出现异常,打印下面的消息
System.err.println("请输入一个数字!" + e.getMessage());
}
    }
英文:

Please try this I hope this will help you to way out.

while (num != 0) {

try { // checks code for exceptions
        int d = num % 2;

            stack.push(d);

            num /= 2
        
        break; // if no exceptions breaks out of loop
    } 
    catch (Exception e) { // if an exception appears prints message below
        System.err.println(&quot;Please enter a number! &quot; + e.getMessage());
        continue; // continues to loop if exception is found
    }

 }

or you can catch the exception like below

public static void main(String[] args) {

        int decimalNumber = 123;

        System.out.print(&quot;binary of &quot; + decimalNumber + &quot; is :&quot;);
 try { // checks code for exceptions
        new decTobin().convertBinary(decimalNumber);

  } 
        catch (Exception e) { // if an exception appears prints message below
System.err.println(&quot;Please enter a number! &quot; + e.getMessage());
}
    }

答案2

得分: 0

另一个答案在这里:

你的代码的convertBinary方法是不完整的。它只能转换正整数。因此,如果用户输入了0或负整数,你应该抛出Exception

public void convertBinary(int num) throws Exception {
    if (num < 1) {
        throw new Exception("数字超出范围(num > 0)");
    }
    
    Stack<Integer> stack = new Stack<Integer>();

    while (num != 0) {
        int d = num % 2;
        stack.push(d);
        num /= 2;
    }

    while (!stack.isEmpty()) {
        System.out.print(stack.pop());
    }
}

然后,你的主方法需要(由Eclipse或其他IDE)实现try-catch语句块。

public static void main(String[] args) {
    int decimalNumber = -123;
    System.out.println("十进制数 " + decimalNumber + " 的二进制表示为:");
    try {
        new decTobin().convertBinary(decimalNumber);
    } catch (Exception e) {
        System.err.println(e.toString());
    }
}

这就是try-catch语句块的工作方式。

英文:

Another answer is here:

Your code's convertBinary method is incomplete. It can convert only positive integer numbers. So you should throw Exception if user would input a 0 or negative integer numbers.

public void convertBinary(int num) throws Exception {
	if (num &lt; 1) {
		throw new Exception(&quot;Number out of range (num &gt; 0)&quot;);
	}
	
    Stack&lt;Integer&gt; stack = new Stack&lt;Integer&gt;();

    while (num != 0) {
        int d = num % 2;
        stack.push(d);
        num /= 2;
    }

    while (!(stack.isEmpty())) {
        System.out.print(stack.pop());
    }
}

And then, your main method is required (by Eclipse or other IDEs) to implement try-catch clause.

public static void main(String[] args) {
    int decimalNumber = -123;
    System.out.println(&quot;binary of &quot; + decimalNumber + &quot; is :&quot;);
    try {
		new decTobin().convertBinary(decimalNumber);
	} catch (Exception e) {
		System.err.println(e.toString());
	}
}

This is how try-catch clause works.

huangapple
  • 本文由 发表于 2020年5月2日 13:48:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/61555051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定