我应该添加什么来使此输出未定义?

时间:2015-12-13 15:38:27

标签: java

有人可以帮我解决我应该添加的代码,当答案是未定义时,它会显示" Undefined"

实施例。 2/0答案将输出Undefined

import java.util.Scanner;
public class SimpleCalcu
{
  public static void main(String[] args)
  {

    int n1,n2;
    String operation;

    Scanner v  = new Scanner(System.in);

    System.out.println("Please Enter The First Number");
    n1 = v.nextInt();

    System.out.println("Please Enter The Second Number");
    n2 = v.nextInt();

    System.out.println("Please Enter The Operation");
    operation = v.next();
    v.close();

    if (operation.equals("+"))
    {
        System.out.println("Your Answer is "+(n1 + n2));
    }
    else if (operation.equals("-"))
    {
        System.out.println("Your Answer is "+(n1 - n2));
    }       
    else if (operation.equals("*"))
    {
        System.out.println("Your Answer is "+(n1 * n2));
    }   
    else if (operation.equals("/"))
    {
        System.out.println("Your Answer is "+(n1 / n2));
    }
  }
}

2 个答案:

答案 0 :(得分:1)

添加for (std::map<int, std::set<int> >::const_iterator i = haha.begin(); i != haha.end(); ++i) { int key = i->first; const std::set<int>& values = i->second; } 的条件检查并打印消息。

n2 == 0

答案 1 :(得分:0)

在您的代码中做同样的事情,

else if (operation.equals("/"))
    {
       System.out.println((n2==0)?"Undefined":"Your Answer is :"+(n1 / n2));
    }
  

它可以保护您在分割器时不会出现ArithmaticException   得到零,

     

这意味着&#39; n2&#39;得到零只是打印&#34; Undefined&#34;