I am working on a lab for one of my classes, so I am looking for more explanation than for the actual code.
For part of this assignment, I need to read numbers from the user until the -d command is pressed. I have a while loop in a method and I pass the scanner to this method, here is my main method:
Scanner scan = new Scanner(System.in);
System.out.println("Length:");
int length = 0;
if(scan.hasNextInt()){
length = scan.nextInt();
}
if(length<0 || length>100){
System.out.println("Length is not of the proper size");
scan.close();
return;
}
Double[] a1 = new Double[length];
Double[] a2 = new Double[length];
fillWithZeros(a1);
fillWithZeros(a2);
System.out.println("Enter the numbers to be multiplied:");
a1 = fillWithValues(a1,scan);
a2 = fillWithValues(a2,scan);
double total = calculateTotal(a1,a2);
printVector(a1,"a1");
printVector(a2,"a2");
System.out.println("Total: " + total);
scan.close();
Then here is my fillWithValues method:
public static Double[] fillWithValues(Double[] array, Scanner scan) {
int numberOfElements = 0;
while(scan.hasNextDouble()){
if(numberOfElements<array.length){
array[numberOfElements] = scan.nextDouble();
numberOfElements++;
}else{
return array;
}
}
return array;
}
The problem I am facing is that when I press Control-D, it does not end the input stream as it should, but I have the code above, it will end the input stream, so can someone explain why Am I having this problem?
I would just declare the scanner as a global variable, but I am not allowed to use global variables for this purpose.