Java Calculator平方根不适用于NetBeans 8.2

时间:2017-04-13 13:02:32

标签: java netbeans

我的计算器没有计算出平方根,我无法解决问题

我的完整代码:

package calculator; // package 
import java.util.*;       
public class Calculator { // start public access
// main method starts here
public static void main (String[] args) {
   // declaring the variables to be used and the data types 
   double n1, n2;
   String s1, s2;
   String operation;
   // prepare a new scanner for user input
   Scanner scan = new Scanner(System.in);
   // prompt user to input a valeu
        System.out.println("Enter a number or press 0 to cancel: ");
        n1 = scan.nextDouble();
        s1 = String.valueOf(n1);
    // check to see if 0 has been entered, if yes, then program will end
        if (n1 != 0) {
    // user has entered a valeu, prompt user for another value within the option to cancel the program        
        System.out.println("Enter a second nmber or press 0 to opt out: ");
        n2 = scan.nextDouble();
        s2 = String.valueOf(n2);
   // check to see if 0 has been entred, if yes, then program will end     
    if (n2 != 0) {
    // prompt user for operatoin to be carried out, +,-, *,/ and square root     
    Scanner op = new Scanner(System.in);
    System.out.println("Enter +,-,/,qr: ");
    operation = op.next();
    // operation carried out depending on user input, result is displayed on the screen
    switch (operation)  {
            case "+":
                System.out.println("Your answer is " + (n1 + n2));
                break;
            case "-":
                System.out.println("Your answer is " + (n1 - n2));
                break;
            case "/":
                System.out.println("Your answer is " + (n1 / n2));
                break;
             case "*":
                System.out.println("Your answer is " + (n1 * n2));
                break;
             case "qr":
                n1 = Math.sqrt(n1);
                System.out.printf("Your answer is %.2f, n1");
                break;
             default: 
                 System.out.println("You are finished.");         
       } // end switch
     } // end second if statement
  }// end first if statement
   } // end main 
} // end the class'

当我运行上面的代码时,我无法计算出数字的平方根,我的代码是否有问题。 我是编程的新手,所以如果你解释什么是错的,那么我将非常感激。

1 个答案:

答案 0 :(得分:0)

System.out.printf("Your answer is %.2f, n1");
                                        ^ here is the error

这将抛出MissingFormatArgumentException。你的错误是你已经将所需的参数包含在'format'字符串中。要解决此问题,您需要在'format'字符串后添加参数。像这样:

System.out.printf("Your answer is %.2f", n1);