как использовать попробуйте и поймать в этом коде (java) - PullRequest
1 голос
/ 02 мая 2020
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);
    }
 }

-

Я не понимаю, попробуйте и поймать java, пожалуйста, помогите мне добавить их в этот код, чтобы я мог понять больше.

Ответы [ 2 ]

1 голос
/ 02 мая 2020

Пожалуйста, попробуйте это, я надеюсь, это поможет вам выйти.

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
    }

 }

или вы можете поймать исключение, как показано ниже

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());
}
    }
0 голосов
/ 02 мая 2020

Другой ответ здесь:

Ваш код convertBinary метод не завершен. Он может конвертировать только положительные целые числа. Таким образом, вы должны выбросить Exception, если пользователь введет 0 или отрицательные целые числа.

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

И затем ваш основной метод требуется (Eclipse или другими IDE) для реализации предложения try-catch.

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

Так работает try-catch предложение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...