2009-03-30 1 views
-3

하나의 파일을 사용하여 명령 창에서 메뉴를 만드는 중입니다. 사용자는 이러한 메뉴 옵션을 선택합니다. 번호를 입력하라는 메시지가 나타납니다. 숫자는 오버로드 된 두 개의 메서드에 전달되어 숫자가 정수인지 부동인지 여부를 확인합니다. 계산이 완료되면 결과가 화면에 인쇄되고 메뉴가 다시 나타납니다. 내 두 파일의 코드는 다음과 같습니다.Java 오버로드 된 메서드

MyMathOpsTest 클래스 :

import java.util.Scanner; // import Scanner class 
public class MyMathOpsTest 
{ 
    //method to pause until a key is pressed 
    public static void pause() 
    { 
     try 
    { 
     System.out.print("Press <Enter> to continue..."); 
     System.in.read(); 
    } 
     catch (Exception e) 
     { 
      System.err.printf("Error %s%c\n",e.getMessage(),7); 
     } 
}//end pause 

public static void main(String args[]) 
{ 
    //variables to capture keyboard input 
    Scanner keyBd = new Scanner(System.in); 
    char selection; 
    //int selection; 

    do{//display menu 
     System.out.println("1. Square a Number"); 
     System.out.println("2. Cube a Number"); 
     System.out.println("3. Raise a Number to a Power"); 
     System.out.println("4. Maximum of Three Numbers"); 
     System.out.println("5. Minimum of Three Numbers"); 
     System.out.println("6. Exit"); 
     System.out.print("Selection[1-6]: "); 

     //get menu selection 
     selection = keyBd.next().charAt(0); 
     //selection = keyBd.nextInt(); 

     //process menu selection 
     switch (selection){ 
      case '1': 
       MyMathOpsTest.squareTheNumber(); 
       pause(); 
       break; 
      case '2': 
       MyMathOpsTest.cubeTheNumber(); 
       pause(); 
       break; 
      case '3':     
       MyMathOpsTest.raiseTheNumber(); 
       pause(); 
       break; 
      case '4':     
       MyMathOpsTest.maximumNumber(); 
       pause(); 
       break; 
      case '5':     
       MyMathOpsTest.minimumNumber(); 
       pause(); 
       break; 
       case '6': 
       //recognize as valid selection but do nothing 
       break; 
      default : 
       System.out.printf("%c\n",7); 
       System.out.println("Invalid Selection"); 
     }//end switch 

    }while(selection != '6'); 
} // end method main 

public static void squareTheNumber() 
{ 

} 

public static void cubeTheNumber() 
{ 
} 

public static void raiseTheNumber() 
{ 
} 

public static void maximumNumber() 
{ 
MyMathOps.maximum(); 
} 

public static void minimumNumber() 
{ 
} 

} // end class MyMathOpsTest 

MyMathOps 클래스 :

import java.util.Scanner; 

public class MyMathOps 
{ 
public static int square(x:Integer):Integer 
{ 
} 

public static double square(x:Double):Double 
{ 
} 

public static int cube(x:Integer):Integer 
{ 
} 

public static double cube(x:Double):Double 
{ 
} 

public static int maximum(x:Integer, y:Integer, z:Integer):Integer 
{ 
    // create Scanner for input from command window 
    Scanner input = new Scanner(System.in); 
    // obtain user input 
    System.out.print("Enter three integer values separated by spaces: "); 
    int numberl = input.nextInt(); 
    // read first integer 
    int number2 = input.nextInt(); 
    // read second double 
    int number3 = input.nextInt(); 
    // read third double 
    // determine the maximum value 
    int result = maximum(numberl, number2, number3); 
    // display maximum value 
    System.out.println("Maximum is: " + result); 
} // end method maximum 

public static double maximum(x:Double, y:Double, z:Double):Double 
{ 
    // create Scanner for input from command window 
    Scanner input = new Scanner(System.in); 
    // obtain user input 
    System.out.print("Enter three floating-point values separated by spaces: "); 
    number1 = input.nextDouble(); 
    // read first double double 
    number2 = input.nextDouble(); 
    // read second double 
    double number3 = input.nextDouble(); 
    // read third double 
    // determine the maximum value 
    double result = maximum(numberl, number2, number3); 
    // display maximum value 
    System.out.println("Maximum is: " + result); 
} // end method maximum 

public static int minimum(x:Integer, y:Integer, z:Integer):Integer 
{ 
    // create Scanner for input from command window 
    Scanner input = new Scanner(System.in); 
    // obtain user input 
    System.out.print("Enter three integer values separated by spaces: "); 
    int numberl = input.nextInt(); 
    // read first integer 
    int number2 = input.nextInt(); 
    // read second double 
    int number3 = input.nextInt(); 
    // read third double 
    // determine the minimum value 
    int result = minimum(numberl, number2, number3); 
    // display minimum value 
    System.out.println("Minimum is: " + result); 
} // end method minimum 

public static double minimum(x:Double, y:Double, z:Double):Double 
{ 
    // create Scanner for input from command window 
    Scanner input = new Scanner(System.in); 
    // obtain user input 
    System.out.print("Enter three floating-point values separated by spaces: "); 
    number1 = input.nextDouble(); 
    // read first double double 
    number2 = input.nextDouble(); 
    // read second double 
    double number3 = input.nextDouble(); 
    // read third double 
    // determine the minimum value 
    double result = minimum(numberl, number2, number3); 
    // display minimum value 
    System.out.println("Minimum is: " + result); 
} // end method minimum 

} // end class MyMathOps 

이 코드는 내 텍스트 책에서 자신과 예제 코드를 입력 코드의 조합입니다. 이것은 jGRASP에서 컴파일되지 않습니다. 이 오류가 발생합니다.

MyMathOps.java:10: <identifier> expected 
    public static int square(x:Integer):Integer 
          ^
MyMathOps.java:96: ')' expected 
    } // end method minimum 
    ^
2 errors 

----jGRASP wedge: exit code for process is 1. 
----jGRASP: operation complete. 

여기서 내가 뭘 잘못하고 있니? 나는이 일을하고 교과서를 읽는데 몇 시간을 보냈다. 이 권리가 없다면. 나는 나쁜 성적을 얻을 것이다. 이 학급에서 좋은 성적을 받아야 컴퓨터 공학 대학에 입학 할 수 있습니다. 당신의 도움을 주셔서 감사합니다.

내 강사 또는 솔트 레이크 커뮤니티 칼리지의 관리자가이 질문을 건너 오게되는 경우에는 제 의도를 분명히하겠습니다. 이 질문은 학문 정직의 가장 위대한 정신으로 게시됩니다. 이 질문을 통해 일반적인 조언을 구하고 Java 프로그래밍 언어를 사용하는 적절한 방법을 이해하는 데 도움을 얻을 수 있습니다. 나는 결코 다른 사람들의 일을 사용하지 않으며 그것을 내 자신의 일로 표현합니다. 나는 여기에 제공된 답을 나의 이해를 돕기 위해 사용한다. 나는 내 모든 일을하고 내 질문에 대답하는 사람들이 제공하는 일을 복사하지 않습니다. 이 같은

+0

구문 적으로 올바른 Java 코드를 게시 할 수 있습니까? 문제가있는 행을 주석 처리하고 명확하게 표시하십시오. 여기에 도움이 될 수도 ... – Jon

+0

나는 이것에 대해 조금 혼란스러워. 왜 JGrasp를 사용하고 있습니까? 왜 MyTextOps 클래스에 var : Type 구문을 사용하고 있습니까? – Uri

+0

자신에게 또 다른 호의를 베풀고 모든 끔찍한 의견을 삭제하십시오. 그들은 새로운 정보를 전혀 추가하지 않습니다. 그들은 이미 읽기 힘든 코드를 혼란스럽게합니다. – duffymo

답변

7

선은 유효한 자바 구문 수 없습니다 :

public static int square(x:Integer):Integer 
public static int maximum(x:Integer, y:Integer, z:Integer):Integer 
... 

이것은 UML이나 의사 코드 구문처럼 보인다. "x : Integer"는 x가 Integer 유형 (Java에서 int 또는 Integer 객체에 매핑 됨)임을 의미하는 "언어에 구애받지 않는"표기법입니다. 마지막에 ": Integer"는 메서드가 이미 올바르게 수행하고있는 Integer 형식을 반환한다는 것을 의미합니다. 모든 메소드 선언을 변경

시도는 다음과 같이합니다 :

public static int square(int x) // Or "Integer x" if you want to use the Integer class, rather than the primitive int 
public static int maximum(int x, int y, int z) 
.... 
+0

"int"예, "Integer"아니오. 다른 이유가없는 한 박스형 프리미티브 (래퍼) 유형보다 항상 기본 유형을 선호해야합니다. –

1

또한, 첫 번째 방법의 일시 정지(), 다른 중괄호가 필요 말 :

public static void pause() 
{ 
    try 
    { 
     System.out.print("Press <Enter> to continue..."); 
     System.in.read(); 
    } 
    catch (Exception e) 
    { 
     System.err.printf("Error %s%c\n",e.getMessage(),7); 
    } 
}<-- this one is missing in yours 

희망이 도와 줘요!

+0

그는 그걸 가지고있는 것처럼 보이지만 제대로 들여 쓰기가되지 않습니다. 클래스를 닫고있는 것 같지만 실제로 pause() 메소드를 닫습니다. 그러나 그는 수업을 끝내기 위해 중괄호가 빠져있다. –

2

저는 파스칼 (또는 파생물)에 익숙하다고 생각합니다.

공공 정적 INT 광장 (X : 정수) : 정수

자바입니다

코드는 "MyMathOpsTest"의 내부에 있기 때문에 공공 정적 INT 광장 (INT의 X) 또한

메소드 호출 앞에 "MyMathOpsTest."를 붙일 필요가 없습니다.

또한 "MathOperationsTest"대신 "MyMathOps"라고 부르는 이유는 무엇입니까? 물론 그것은 당신 것입니다 - 그것은 나 또는 다른 누구에게도 길지 않습니다!의미있는 이름을 선택하고, 작업하는 분야에 공통적 인 경우가 아니라면 "Ops"와 같은 약식을 피하십시오. URL은 좋은 것입니다 ("Ops"는 그렇지 않습니다).

그리고

지금은 초보자를위한 generl 프로그래밍 조언 :

  • 코드의 라인은 다음 작업을 컴파일하면
  • 을 컴파일하는 코드의 라인을 얻을 코드
  • 의 한 줄을 쓰기 one
  • 컴파일 할 코드의 다음 줄을 얻고
  • 프로그램을 완료 할 때까지 그렇게하십시오.

동일한 실수를 반복해서 반복하는 것은 의미가 없습니다. 여러분이 잘하는 것은 실수를 저지르는 것이고, 그리 재미있는 것은 아닙니다.

public class MathOperations 
{ 
    public static int maximum(final int x, final int y, final int z) 
    { 
    } 
} 

(위의 코드를 컴파일)

2 단계 :

public class MathOperations 
{ 
    public static int maximum(final int x, final int y, final int z) 
    { 
     final Scanner input; 
    } 
} 

그래서

1 단계 ... 당신이 시작하는 (위 컴파일 코드)

3 단계 :

public class MathOperations 
{ 
    public static int maximum(final int x, final int y, final int z) 
    { 
     final Scanner input; 

     intput = new Scanner(System.in); 
    } 
} 

은 (위의 코드를 컴파일)

다음 한 번에 하나 개의 라인을 계속. 한 번에 한 번에 한 줄 씩 실행하면 실수를했을 때 즉시 표시됩니다. 다음 라인으로 넘어 가기 전에 모든 실수를 고쳐야합니다.

+0

클래스의 이름은 과제의 요구 사항입니다. 이 과제는 입문 과정을위한 것이기 때문에 보통 결정하기 위해 내게 맡겨져있는 많은 것들이 과제 설명에 의해 지정됩니다. –

+0

아 ... 너무 나쁜 사람들은 실제로 "내"물건을 가르칩니다. – TofuBeer

0

나는 운동의 요점 (수학 연산, 과부하 또는 메뉴)을 알지 못합니다. 그러나 당신의 기초로서 이것들을 시작하는 것이 좋습니다.

public class MyMathOps 
{ 
    public static int square(int x) 
    { 
     return x*x; 
    } 

    public static double square(double x) 
    { 
     return x*x; 
    } 

    public static int cube(int x) 
    { 
     return x*x*x; 
    } 

    public static double cube(double x) 
    { 
     return x*x*x; 
    } 

    public static int maximum(Integer... values) 
    { 
     Integer maxValue = Integer.MIN_VALUE; 

     for (Integer value : values) 
     { 
      if (value.compareTo(maxValue) > 0) 
      { 
       maxValue = value; 
      } 
     } 

     return maxValue; 
    } 

    public static double maximum(Double... values) 
    { 
     Double maxValue = Double.MIN_VALUE; 

     for (Double value : values) 
     { 
      if (value.compareTo(maxValue) > 0) 
      { 
       maxValue = value; 
      } 
     } 

     return maxValue; 
    } 

    public static int minimum(Integer... values) 
    { 
     Integer minValue = Integer.MAX_VALUE; 

     for (Integer value : values) 
     { 
      if (value.compareTo(minValue) < 0) 
      { 
       minValue = value; 
      } 
     } 

     return minValue; 
    } 

    public static double minimum(Double... values) 
    { 
     Double minValue = Double.MIN_VALUE; 

     for (Double value : values) 
     { 
      if (value.compareTo(minValue) < 0) 
      { 
       minValue = value; 
      } 
     } 

     return minValue; 
    } 

} 

및 테스트 클래스 (간체) : 적어도 그들은 컴파일하고 실행

public class MyMathOpsTest 
{ 
    public static void main(String args[]) 
    { 
     Integer [] intValues = { 1, 2, 3, }; 
     Double [] doubleValues = { 11.0, 14.0, -6.0 }; 

     for (Integer value : intValues) 
     { 
      System.out.println("value : " + value); 
      System.out.println("squared: " + MyMathOps.square(value)); 
      System.out.println("cubed : " + MyMathOps.cube(value)); 
      System.out.println("min : " + MyMathOps.minimum(intValues)); 
      System.out.println("max : " + MyMathOps.maximum(intValues)); 
     } 

     for (Double value : doubleValues) 
     { 
      System.out.println("value : " + value); 
      System.out.println("squared: " + MyMathOps.square(value)); 
      System.out.println("cubed : " + MyMathOps.cube(value)); 
      System.out.println("min : " + MyMathOps.minimum(doubleValues)); 
      System.out.println("max : " + MyMathOps.maximum(doubleValues)); 
     } 
    } 
} 

이 실행이 완료되면, 당신은 당신의 방법이 올바른지 알 수 있습니다. 첫 번째 시도에서 값을 읽는 어려움을 잊지 마십시오.