Aria
Aria

Reputation: 33

Java- making int array or double array

I'm trying to make a program the asks use for min and max and length of array and depending on user input for max and min (int or double) it will create an array of int or double. The problem with my code is when I try to run it, the compiler says the variables have not been initialized. I'm assuming it's better to make an overloaded method but I'm not sure how.

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");   

  }
}   

Upvotes: 0

Views: 127

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44854

If you declare variables within curly braces as in

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

then they are only visible within this scope.

So as a minimum you need to change to

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

Now as you are also using the same for doubles then maybe created a new variable for doubles such as

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

Note

I am not sure about your logic for generating arrays, but if you were to generate an array for doubles between two numbers, then you will have an infinite number of values.

To do things properly I suggest that you write your own class that extends Number, for simplicity, the constructor of your class could take a boolen value to say if it is a double or an int.

Upvotes: 2

denvercoder9
denvercoder9

Reputation: 3021

You have initialized the min and max variables inside the if statements. Outside the scope of if statement you cannot access the variables that have been initialized inside.

Upvotes: -1

Related Questions