如何在此代码中使用try和catch(java) package-zed; 导入java.util.Stack; 公共级decTobin{ public void convertBinary(int num){ 堆栈=新堆栈(); while(num!=0){ int d=num%2; 堆栈推送(d); num/=2; } 而(!(stack.isEmpty()){ System.out.print(stack.pop()); } } 公共静态void main(字符串[]args){ 整数小数=123; 系统输出打印(“二进制的“+小数+”是:”; 新decTobin().convertBinary(小数); } }
-如何在此代码中使用try和catch(java) package-zed; 导入java.util.Stack; 公共级decTobin{ public void convertBinary(int num){ 堆栈=新堆栈(); while(num!=0){ int d=num%2; 堆栈推送(d); num/=2; } 而(!(stack.isEmpty()){ System.out.print(stack.pop()); } } 公共静态void main(字符串[]args){ 整数小数=123; 系统输出打印(“二进制的“+小数+”是:”; 新decTobin().convertBinary(小数); } },java,Java,- 我不懂java中的try and catch,请帮助我在代码中添加它们,以便我能理解更多内容。请尝试一下,我希望这能帮助您解决问题 package zed; import java.util.Stack; public class decTobin { public void convertBinary(int num) { Stack<Integer> stack = new Stack<Integer>(); while
我不懂java中的try and catch,请帮助我在代码中添加它们,以便我能理解更多内容。请尝试一下,我希望这能帮助您解决问题
package zed;
import java.util.Stack;
public class decTobin {
public void convertBinary(int num) {
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());
}
}
public static void main(String[] args) {
int decimalNumber = 123;
System.out.print("binary of " + decimalNumber + " is :");
new decTobin().convertBinary(decimalNumber);
}
}
或者,您也可以像下面这样捕获异常
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("Please enter a number! " + e.getMessage());
continue; // continues to loop if exception is found
}
}
另一个答案是: 您的代码的
convertBinary
方法不完整。它只能转换正整数。所以,如果用户输入0或负整数,您应该抛出Exception
public static void main(String[] args) {
int decimalNumber = 123;
System.out.print("binary of " + decimalNumber + " is :");
try { // checks code for exceptions
new decTobin().convertBinary(decimalNumber);
}
catch (Exception e) { // if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
}
}
这就是
try-catch
子句的工作方式。在示例代码中,没有方法抛出异常。因此,没有什么可以尝试或捕获的。您需要切换continue的位置代码>和中断代码>语句。
public void convertBinary(int num) throws Exception {
if (num < 1) {
throw new Exception("Number out of range (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());
}
}
public static void main(String[] args) {
int decimalNumber = -123;
System.out.println("binary of " + decimalNumber + " is :");
try {
new decTobin().convertBinary(decimalNumber);
} catch (Exception e) {
System.err.println(e.toString());
}
}