2013-09-17 3 views
-2

Как это сделать, когда wholenumber2 = zero будет отображаться другое сообщение, если число_объектов равно < или> но не = ноль, будет отображаться другое сообщение? Я пытаюсь предотвратить основную ошибку погружения на 0.JAVA - Разделение на нуль и возврат правильного ответа = Не определено

package SumDifProPACKAGE;  // Assigns package code. 
import java.util.Scanner;  // Program uses class Scanner. 
public class SumDifProCLASS { // Public class. 
    public static void main(String[] args){ 
     // Displays Welcome, information on calculations & creators name. 
     System.out.printf("%s\n%s\n%s\n", 
     "--Welcome to JAVA Calculator!--", " --Sum, Difference, Product--", " --??--"); 
     // Creates a Scanner to obtain input from the command window. 
     Scanner input = new Scanner(System.in); 
     // Listed integers: 
     int wholenumber1; // First whole number input. 
     int wholenumber2; // Second whole number input. 
     int sum;   // Sum of First & Second whole number input. 
     int difference; // Difference of First & Second whole number input. 
     int product;  // Product of First & Second whole number input. 
     int quotient;  // Quotient of First & Second whole number input. 
     int remainder; // Remainder of the Quotient. 
     int zero = 0; 
     // Requests input for First whole number. 
     System.out.print("Please enter first whole number..."); 
     wholenumber1 = input.nextInt(); 
     // Requests input for Second whole number. 
     System.out.print("Please enter first whole number..."); 
     wholenumber2 = input.nextInt(); 
     // Displays the sum of First & Second input. 
     sum = wholenumber1 + wholenumber2; 
     System.out.printf("Sum  = %d\n", sum); 
     // Displays the difference of First & Second input. 
     difference = wholenumber1 - wholenumber2; 
     System.out.printf("Difference = %d\n", difference); 
     // Displays the product of the First & Second input. 
     product = wholenumber1 * wholenumber2; 
     System.out.printf("Product = %d\n", product); 
     // Displays the quotient without the remainder of the First & Second input. 
     quotient = wholenumber1/wholenumber2; 
     System.out.printf("Quotient = %d", quotient); 
     // Displays the remainder, continuation of quotient. 
     remainder = wholenumber1 % wholenumber2; 
     System.out.printf("r%d\n", remainder); 
    } 
+0

Используйте, если заявление для проверки 'wholenumber2 == 0' – nhahtdh

ответ

0

Один простой способ - это оператор if.

// Displays the quotient without the remainder of the First & Second input. 
if(wholenumber2 != 0){ 
    quotient = wholenumber1/wholenumber2; 
    System.out.printf("Quotient = %d", quotient); 
} 
else{ 
    System.out.printf("Cannot divide by zero"); 
} 

кстати: как комментарий к некоторым из других ответов, вы должны воздерживаться формами использования исключений для управления потоком выполнения.

+0

Это сработало отлично. Это только мой второй день в программировании классов в JAVA, без опыта. Я понимаю, что вы здесь делали сейчас. Я должен буду использовать эти строки в будущем. Благодарю. –

+0

Приятно слышать, удачи в изучении Java :) – Chippen

0

Как сделать так, когда wholenumber2 = нулю, то она будет отображать другое сообщение, то если wholenumber является < или>, но не ноль = он отобразит другое сообщение? Я пытаюсь предотвратить основную ошибку погружения на 0.

Простой Если вам нужна проверка.

if (wholenumber2 != 0) { 
    // calculate 
}else{ 
    //show error message 
} 
0

Деление целого числа на ноль дает ArithmeticException .so Вы можете поймать его и отобразить сообщение, которое вы хотите.

try{ 
    quotient = wholenumber1/wholenumber2; 
    System.out.printf("Quotient = %d", quotient); 
}catch(ArithmeticException ae){ 
    System.out.print("Result is Undefined"); 
} 
+1

Это тоже сработало. Спасибо за помощь. –

1

вы можете использовать try catch для обработки (деление на ноль) ArithmeticException или вы можете проверить, если wholenumber2 равен нулю или не

if(wholenumber2==0){ 
    // handle the case 
} else{ 
    // handle the else case 
} 

проверка this link а это предложить несколько способов справиться с этой ситуацией

0

Добавить условие при запросе вход ->

int wholenumber2 = 0 
while (wholenumber2 < 1) { 
    System.out.print("Please enter second whole number..."); 
    wholenumber2 = input.nextInt(); 
} 
+0

Это поможет вам проверить ввод и предотвратить такую ​​ситуацию. – dganesh2002

0
Long division_operation (Long a, Long b) throws Exception 
{ 
    Long t = new Long (1); 

    try 
    { 
     t = (a.longValue()/b.longValue()); 
    } 
    catch (ArithmeticException e) 
    { 
     t = null; 
    } 
    finally 
    { 
     return t; 
    } 
} 
0

Учитывая тот факт, что вы делаете все операции сразу же, я предлагаю вам проверить значение wholenumber2, как только он вошел т.е.

Scanner input = new Scanner(System.in); 

int wholenumber2 = input.nextInt(); 

while(wholenumber2==0) 
{ 
System.out.println("Whole Number cannot be zero!!"); 
System.out.print("Please enter Second whole number..."); 
wholenumber2 = input.nextInt(); 
} 
Смежные вопросы