2013-08-28 3 views
0

방금 ​​JDK를 다운로드하고 JGrasp를 설치했으며 첫 번째 Java 프로그램 (삼각형의 빗변)을 작성하려고했습니다. 여기에 내 프로그램이있다 :Java에서 간단한 오류가 발생하지 않습니다

public class Hypot { 

    public static void main(String args[]) { 
     double hypotenuse; 
     double d1; 
     double d2; 

     if (args.length != 2) { 
      System.out.println("You need to enter two arguments!"); 
      System.exit(1); 
     } 

     try { 
      d1 = new Double.parseDouble(args[0]); 
      d2 = new Double.parseDouble(args[1]); 
     } catch (NumberFormatException nfe) { 
      System.out.println("Arguments need to be numbers!"); 
      System.exit(2); 
     } 


     hypotenuse = Math.sqrt((d1 * d1) + (d2 * d2)); 
     System.out.print("The hypotenuse of the right angle triangle with sides of " + d1 + "and" + d2 + "is" + hypotenuse); 
    } 
} 

나는이 두 가지 오류가있다. 나는 그들이 무엇인지 이해하지 못한다.

Hypot.java:16: error: cannot find symbol 
    d1= new Double.parseDouble(args[0]); 
       ^
    symbol: class parseDouble 
    location: class Double 
Hypot.java:17: error: cannot find symbol 
    d2= new Double.parseDouble(args[1]); 
       ^
    symbol: class parseDouble 
+1

그냥 거기에서'new'을 제거하십시오. –

답변

0

이 문

d1= new Double.parseDouble(args[0]); 

의 문제는 당신이이 문장은 컴파일시 그래서 parseDouble

에서 반환되는 원시 이중의 인스턴스를 만들려고한다는 것입니다 되기

d1 = new double; 

이것은 구문 상 올바르지 않습니다. 당신은 단순히 new 연산자를 사용하지 않고 D1 더블 변수에 할당 할 수 있도록 parseDouble 더블을 반환으로

:

d1 = Double.parseDouble(args[0]); 

은 또한 점에 유의 static 변수/메서드에 액세스를, 당신은을 만들 필요가 없습니다 클래스의 인스턴스. 다음과 같이 클래스 이름을 사용하여 액세스 할 수 있습니다. Double.parseDouble (args [0]);

편집

이 시도 :

public class Hypot{ 
    public static void main(String args[]) 
    { 
    double hypotenuse; 
    double d1 = 0.0d; 
    double d2 = 0.0d; 

    if(args.length!=2) 
    { 
    System.out.println("You need to enter two arguments!"); 
    System.exit(1); 
    } 

    try 
    { 
    d1= Double.parseDouble(args[0]); 
    d2= Double.parseDouble(args[1]); 
    } 
    catch(NumberFormatException nfe) 
    { 
    System.out.println("Arguments need to be numbers!"); 
    System.exit(2); 
    } 




    hypotenuse=Math.sqrt((d1*d1)+(d2*d2)); 
    System.out.print("The hypotenuse of the right angle triangle with sides of "+d1+"and"+d2+"is"+hypotenuse); 
    } 
} 
+0

덕분에, 나는 그런 종류의 일을했지만, 그런 다음 d1과 d2가 초기화되지 않을 수 있다는 오류가 발생하여 왜 거기에 'new'를 쓰려고했는지 – Snedden27

+0

@ Snedden27 메서드 로컬 변수를 초기화해야하므로 오류가 발생합니다 . 그래서 그것들을 정의하는 동안 디폴트 값 double d1 = 0.0d를 할당한다; –

+0

그래, 내가 말하면 초기화하지 않겠다. d1 = new Double.parseDouble (args [0]); d2 = new Double.parseDouble (args [1]); – Snedden27

3

그것은 정적 메서드의이 새로운 쓰지 않는다. new를 사용하여 클래스를 인스턴스화합니다. "parseDouble"은 내부 클래스가 아니므로 new를 사용할 수 없습니다. 메소드가 방금 호출됩니다. "팩토리 패턴"은 정적 메서드를 사용하여 인스턴스를 반환합니다. 즉 정적 메서드에 인스턴스화 (새 인스턴스)가 포함되어 있음을 의미합니다.

2

Double.parseDouble은 정적 방법이기 때문에 을 사용하려면 Double을 인스턴스화 할 필요가 없습니다. Double이 보이는 정적이 아닌 메서드를 호출하고 싶다면 new Double(string).doubleValue();

관련 문제