2016-11-07 3 views
0

최소 및 최대 및 배열 배열 및 최대 및 최소 (int 또는 double)에 대한 사용자 입력에 따라 asks 사용하도록 프로그램을 만들려고 해요 배열 배열을 만듭니다. int 또는 double. 내 코드의 문제는 실행하려고 할 때 컴파일러에서 변수가 초기화되지 않았다고하는 것입니다. 오버로드 된 메서드를 만드는 것이 더 낫다고 가정하고 있지만 확실하지 않습니다.Java 만들기 int 배열 또는 double 배열

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

    }//end of main 
public static void randomArray(){ 
    Scanner input = new Scanner(System.in); 
    System.out.println("Please enter the length of desired array: "); 
    int length = input.nextInt(); 
    int [] randomNumbers = new int [length]; 
    System.out.println("Please enter the highest number: "); 
    if (input.hasNextInt()){ 
    int max = input.nextInt(); 
    } 
    else if (input.hasNextDouble()){ 
    double max = input.nextDouble(); 
    } 
    System.out.println("Please enter the Lowest number: "); 
    if (input.hasNextInt()){ 
    int min = input.nextInt(); 
    } 
    else if (input.hasNextDouble()){ 
    double min = input.nextDouble(); 
    } 
    arrayReturn(max, min); 
    } //end of randomArray 
public static void arrayReturn(int max, int min){ 
    System.out.println("This will return "+max+"min :"+ min +"in int"); 
    } 
public static void arrayReturn(double max, double min){ 
    System.out.println("This will return "+max+"min :"+ min +"in double"); 

    } 
} 

답변

-1

당신은 if 문 내부의 minmax 변수를 초기화했다. if 구문의 범위를 벗어나면 내부에서 초기화 된 변수에 액세스 할 수 없습니다.

+0

이것은 코멘트 일 것입니다. –

+0

문제는 if 문 밖에서 초기화하면 int 또는 double 중 하나의 변수 유형으로 제한된다는 것입니다. – Aria

+0

"초기화 됨"과 "선언 됨"을 혼동하지 마십시오. 외부에 선언했다면 내부에서 초기화하는 것이 좋습니다. 이 대답은 실제로 옳지 않습니다. 그리고이 코드보다 원래 코드의 문제가 훨씬 많습니다. –

2

당신은 그 때이 범위 내에서만 볼 수 있습니다

if (input.hasNextInt()){ 
    int max = input.nextInt(); 
} 

같이 중괄호 내에서 변수를 선언합니다.

그래서 최소한 당신은 어쩌면 doubles 같은

double maxD = 0.0; 
else if (input.hasNextDouble()){ 
    maxD = input.nextDouble(); 
    } 

같은 주에 대한 새로운 변수를 만들어 당신은 또한 doubles 위해 동일을 사용하는 것처럼 이제

int max = 0; 
if (input.hasNextInt()){ 
    max = input.nextInt(); 
} 

로 변경해야

arrays을 생성하는 논리가 확실하지 않지만, y ou는 두 숫자 사이에 double을위한 배열을 생성 할 것이고 무한 개수의 값을 가질 것입니다.

올바르게 작업하기 Number를 확장 한 클래스를 작성하는 것이 좋습니다. 클래스의 생성자는 double 또는 int 일 경우 boolen 값을 사용할 수 있습니다.

+0

당신이 볼 수 있듯이 오버로드 된 메서드를 사용하고 있습니다. public static void arrayReturn (int max, int min) { System.out.println (""+ max + "min :"+ min + "in int "); } public static void arrayReturn (double max, double min) { System.out.println ("이 경우"+ 최대 + "분 :"이중 + "+"를 반환합니다. } – Aria

+0

네, 번호를 확장하는 고유 한 클래스를 만드는 것이 좋습니다 https://docs.oracle.com/javase/7/docs/api/java/lang/Number.html –