2017-04-13 77 views
0

我的計算器不奏效的平方根,我找不出問題出Java的計算器平方根不上的NetBeans 8.2上運行

我的完整代碼:

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' 

當我運行的代碼上面,我無法計算出數字的平方根,我的代碼有問題。 我是編程新手,所以如果你解釋什麼是錯的,那麼將非常感激。

+4

這是一個錯字,'System.out.printf( 「你的回答是%.2f,N1」)'應該是'System.out.printf( 「你的回答是%.2f」, N1)' – Berger

回答

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

這會拋出一個MissingFormatArgumentException。你的錯誤是你已經在'格式'字符串中包含了所需的參數。爲了解決這個問題,你需要在'format'字符串後添加參數。就像這樣:

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