This is a Student class I have which creates a student that has a name, grade, and ID number. The Student is used as the key in a TreeMap, while the student's grade is used as the value. I wrote compareTo as I am implementing Comparable, but this error pops up upon entering in the first student:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Student.<init>(Student.java:25)
at Main.main(Main.java:50)
Java Result: 1
I think it is coming from the splitting of the student's name into a String[], but I've tested those lines that call the first and last names, as well as the line that splits the name and they all seem to work as intended, except for when they are called in compareTo.
Any help would be much appreciated.
public class Student implements Comparable<Student>{
private String name, grade, first, last;
private String[] stuName;
private int id;
/**
* Constructs a new Student with a name, ID Number, and a grade.
* #param n name
* #param i ID Number
* #param g grade
*/
public Student(String n, int i, String g){
name = n;
id = i;
grade = g;
stuName = n.split(" ");
first = stuName[0];
last = stuName[1];
}
/**
* Compares Students. First by last name, then by first if the last names
* are the same. If the first names are also the same, the students are
* compared by their ID Numbers.
* #return the value upon comparing the proper property of the Student
*/
#Override
public int compareTo(Student other){
if (last.equals(other.getLast())){
if (first.equals(other.getFirst())){
return id - other.getID();
}else
return first.compareTo(other.getFirst());
}
return last.compareTo(other.getLast());
}
/**
* Changes the student's current grade.
* #param g new grade
*/
public void changeGrade(String g){
grade = g;
}
/**
* Returns student's name.
* #return name
*/
public String getName(){
return name;
}
/**
* Returns student's first name.
* #return first name
*/
public String getFirst(){
return first;
}
/**
* Returns student's last name.
* #return last name
*/
public String getLast(){
return last;
}
/**
* Returns the student's grade.
* #return grade
*/
public String getGrade(){
return grade;
}
/**
* Returns the student's ID Number
* #return id number
*/
public int getID(){
return id;
}
Tester:
public class Main {
public static void main(String[] args) throws InterruptedException{
Map<Student, String> students = new TreeMap();
Scanner in = new Scanner(System.in);
System.out.println("How many students do you want to add?");
int numStudents = in.nextInt();
String name, grade;
int id;
for (int i = 1; i < numStudents; i++){
System.out.println("Name of student " + i + "?");
name = in.nextLine();
in.nextLine();
System.out.println("Grade of " + i + "?");
grade = in.nextLine();
System.out.println("ID Number of " + i + "?");
id = in.nextInt();
Student s = new Student(name, id, grade);
students.put(s, s.getGrade());
}
System.out.println("How many students do want to remove");
int remStudents = in.nextInt();
for (int i = 0; i < remStudents; i++){
System.out.println("ID?");
int remID = in.nextInt();
for (Student s : students.keySet()){
if (s.getID() == remID){
students.remove(s);
}
}
}
System.out.println("How many grades do you want to change?");
int changeGrades = in.nextInt();
for (int i = 0; i < changeGrades; i++){
System.out.println("ID?");
int foo = in.nextInt();
System.out.println("New grade?");
String newGrade = in.nextLine();
for (Student s : students.keySet()){
if (s.getID() == foo){
s.changeGrade(newGrade);
}
}
}
String printout = "";
for (Student s : students.keySet()){
printout += s.getLast() + ", " + s.getFirst() + " (" + s.getID() + "): " + s.getGrade() + "\n";
}
System.out.println(printout);
}
}
Probably because you have two different loops, with different indices:
in your one loop, you start from 1, and thus you are 1 student short:
for (int i = 1; i < numStudents; i++){
in the delete loop you have a 0-based index:
for (int i = 0; i < remStudents; i++){
I suspect that, you think you add 2 studends, but really you have just one (at index 0), and thus your indexout-of-bounds exception.
EDIT, OP has added a 'full' stack for the exception, and the above answer is not related to the OP's problem.....
Answer 2: Based on your revised stack/exception edit, the only possible answer is that there are no spaces in the student's name..... your assertion that there is always a space is simply not true ....
you may want to add a count qualifiewr to the split so that you will get an empty string on any invalid input:
stuName = n.split(" ", 2);
Related
I'm trying to get the person's name from an input prompt. Get the name length and if the length is less than 1 throw a custom error throws LineLimitException, and prompt the user again to enter their name. I know I threw a lot of code in here but I'm hoping it makes what I'm trying to do more clearly.
LineLimitException Class
public LineLimitException(String message){
super(message);
}
}
Here I prompt and store the name field
name = input.nextLine();
int strSizeName = name.length();
if(strSizeName < 1) {
I'm getting these results in the console
How many employees are there?
2
Enter employee 1's name
Name must be greater than one character. Please try again.
Enter employee 1's name *<--- this is before I can even enter a name*
Enter employee's hourly wage *<-- prompts for hourly wage before I got the name.*
public class Driver {
/**
* defualt constructor
*/
public Driver() {
}
/**
* Main method - prompts the user for name, hours worked, and hourly salary. Stores it in a person object
* #author
* #param args
*
*/
public static void main(String[] args) throws LineLimitException{
ArrayList<Employee> person = new ArrayList<Employee>();
// prompt user for the total number of employees
Scanner input = new Scanner(System.in);
System.out.println("How many employees are there?");
String name;
int numEmployees = input.nextInt();
for (int count = 1; count <= numEmployees; count++) {
System.out.println("Enter employee " + count + "'s name");
**name = input.nextLine();
int strSizeName = name.length();
if(strSizeName < 1) {
//Why is this showing up afterI give emploee count?
System.out.println("Name must be greater than one character. Please try again.");
//reprompt the user for a name
System.out.println("Enter employee " + count + "'s name");
}else {
continue;
}**
System.out.println("Enter employee's hourly wage");
double wage = input.nextDouble();
System.out.println("Enter how many hours worked");
double hrsWkd = input.nextDouble();
person.add(new Employee(name, wage, hrsWkd)); // add an employee object to the ArrayList
printSalaryReport(person, wage, hrsWkd);
}
input.close();
System.out.println("CSV File Created.");
}
/**
* Method printSalaryReport - prints the employee person objects name, hours worked
* hourly salary and gross salary to a csv file.
* #param person in ArrayList
* #param getHours_Worked
* #param getHourly_Salary
* #throws IncorrectFileNameException
*/
private static void printSalaryReport(ArrayList<Employee> person, double getHours_Worked, double getHourly_Salary) {
String CSV_SEPARATOR = ",";
String fileName = "employee.csv";
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"));
String Header = "Name, Hourly Salary, Hours Worked, Pay";
bw.write(Header.toString());
bw.newLine();
for (Employee man : person)
{
StringBuffer manStr = new StringBuffer();
manStr.append(man.getName());
manStr.append(CSV_SEPARATOR);
manStr.append(man.getHourly_Salary());
manStr.append(CSV_SEPARATOR);
manStr.append(man.getHours_Worked());
manStr.append(CSV_SEPARATOR);
manStr.append(calculateSalary(man.getHours_Worked(), man.getHourly_Salary()));
bw.write(manStr.toString());
bw.newLine();
}
bw.flush();
bw.close();
}
catch (IOException err){}
}
/**
* Method calculateSalary takes the hours worked and hourly salary and returns
* the result of each multiplied.
*
* #param getHours_Worked
* #param getHourly_Salary
* #return
*/
private static Object calculateSalary(double getHours_Worked, double getHourly_Salary) {
double salary = getHourly_Salary;
double hoursWorked = getHours_Worked;
double wkAmount = salary*hoursWorked;
return wkAmount;
}
}
boolean skip = false;
for (int count = 1; count <= numEmployees; count++) {
if (!skip)
input.nextLine();
else
skip = false;
try {
System.out.println("Enter employee " + count + "'s name");
name = input.nextLine();
int strSizeName = name.length();
if (strSizeName < 1)
throw new LineLimitException("Name must be non-empty. Please try again.");
System.out.println("Enter employee's hourly wage");
double wage = input.nextDouble();
System.out.println("Enter how many hours worked");
double hrsWkd = input.nextDouble();
person.add(new Employee(name, wage, hrsWkd)); // add an employee object to the ArrayList
printSalaryReport(person, wage, hrsWkd);
} catch (final LineLimitException e) {
System.out.println(e.getMessage());
count--;
skip = true;
}
}
Does this solve your problem?
So the while loop is not working, even though it compiles. How do I position it correctly??
I tried a few things but they kinda worked. if someone on here can help me out that would be great
import java.util.Scanner;
//This is a Driver program to test the external Class named Student
public class StudentDriver //BEGIN Class Definition
{
//**************** Main Method*************************
public static void main (String[] args)
{Scanner scan = new Scanner(System.in);
//Data Definitions:
//Instance Data
String courseName;
int courseCredits;
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
//Executable Statements:
//Initialize first Student
name = "Fred Fergel";
id = "0123";
street = "123 Main Street";
city = "Smalltown";
state = "NY";
zip = "12345";
major = "Computer Science";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
//Test toString
System.out.println("Student 1\n\n" + student1.toString());
//Print a blank line
System.out.println();
//Add a course
student1.addCourse("CSC111", 4);//NOTE: DO NOT PUT A SPACE BETWEEN CSC AND 111
//Print schedule
System.out.println("Student 1's Schedule:\n\n");
student1.displaySchedule();//call method
final String FLAG = "Y";
String prompt = "Y";
while (prompt.equals("y"))
{
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
System.out.println("How many credits is the course? ");
courseCredits = scan.nextInt();
student1.addCourse(courseName, courseCredits);
System.out.println("Do you wish to enter another course? y/n");
prompt = scan.next();
}
//end while
}//end main
}//end StudentDriver
Here is the student class:
import java.util.Scanner;
public class Student
{Scanner scan = new Scanner(System.in);
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
int totalCredits;
final int SIZE = 6;
final int MAX_CREDITS = 18;
String [ ] schedule = new String [SIZE];
int courseNumber = 0; //start out with no courses
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student (String name, String id, String address, String cityName, String stateName, String zip, String area )
{
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
}//end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString()
{
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress
+ "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode
+ "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
}// end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits)
{
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
}
else
{
return false; //return a false if 18 credit limit is exceeded
}//end numCredits
}//checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits)
{
if (courseNumber < SIZE ) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule [courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
}
else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
}//end checkCredits
}
else //oops – can’t do more than 10 courses
{
System.out.println("You have exceeded 10 courses.");
}//end courseNumber
}//addCourse
//Method to display the schedule
//-------------------------------------------------------
// Will only print out the courses added to the array.
//-------------------------------------------------------
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
}
String prompt = "Y";
while (prompt.equals("y"))
Y and y are not the same thing. You need to use .equalsIgnoreCase() instead of .equals() if you want it to ignore case.
My dad and I narrowed it down to the object can't store the data. also, I'm new to java. The code is supposed to print in the console the first name, last name, grade, and grade average. I think the problem is in public double getCalcGraeAverage() but correct me if wrong, please.
import java.util.Scanner;
/**
* Write a description of class Student here.
*
* #author XXXX
* #version XXXX
*/
public class Student
{
String firstName;
String lastName;
int gradeLevel;
double gradeAverage;
int totalAssignments;
double totalPoints;
/**
* Create a new student with student's name, grade, and average
*/
public Student(String newFirstName, String newLastName, int newGradeLevel, double newGradeAverage)
{
firstName = newFirstName;
lastName = newLastName;
gradeLevel = newGradeLevel;
gradeAverage = newGradeAverage = 0.0;
}
/**
* Return the student's first name.
*/
public String getFirstName()
{
return firstName;
}
/**
* Return the student's last name.
*/
public String getLastName()
{
return lastName;
}
/**
* Return the grade level of the student.
*/
public int getGradeLevel()
{
return gradeLevel;
}
/**
* Calculates grade average.
*/
public double getCalcGradeAverage()
{
double gradeAverage = totalAssignments / totalPoints;
return gradeAverage;
}
public static void main (String[] args)
{
Student student1 = new Student ("XXXX", "XXXX", 11, 0.0);
System.out.println("The student's first name is: " + student1.getFirstName());
System.out.println("The student's last name is: " + student1.getLastName());
System.out.println("The student's grade level is: " + student1.getGradeLevel());
System.out.println("Please enter the total assignment points the student has earned: ");
Scanner input = new Scanner(System.in);
Double totalAssignments = input.nextDouble();
System.out.println("Please enter the number of assignments given: ");
double totalpoints = input.nextDouble();
System.out.println(student1.getFirstName() + " " + student1.getLastName() + " average grade is" + student1.getCalcGradeAverage());
}
}
In your code you are :
creating a Student student1 object
reading totalAssignments, totalpoints from System.in
calling student1.getCalcGradeAverage()
between steps 2 and 3 you have to set the fields totalAssignments, totalpoints of student to the values you read or they will retain their default values of zero. E.g.
student1.totalAssignments = totalAssignments;
student1.totalpoints = totalpoints;
Also, since totalAssignments is of type int, you probably want to read it as:
int totalAssignments = input.nextInt();
When writing your code, you declare variables for the student class with class scope.
int totalAssignments;
double totalPoints;
those class scope variable are used in the method :getCalcGradeAverage()
totalAssignments of Student and totalPoints of student are used in this method
When you create a new Student those variable are equals to zero because not affected by a value in your constructor.
in the main method when you writes :
Double totalAssignments =
you declare a new variable named "totalAssignments" with a method scope.When the method ends, the variable reference goes away and there is no way to access that variable any longer.
you can consider that the variable decalred is not the same that the student variable: student.totalAssignments is always equals to zero because no value affected to him.
Then assuming that you can do that :
student1.totalAssignments = input.nextInt();
student1.totalPoints = input.nextDouble();
So I have this program that builds a School using dynamic arrays instead of using Array List. I have the methods created and tested, everything works except I'm trying to get the UI to work.
The UI is supposed to take user input to build the array of Students. Normal students versus CS students. The problem is, when I enter in how many students I want to enter into the school either regular or CS students, it stops after I enter in the amount of students I request to enroll.
I want the ability to say enroll 5 students, then go back and be asked if I want to enroll more, drop a student, or do any of the other options listed on the main menu. That's my problem. Every time I try to add in a for loop or switch the if/else if statements around compilation errors abound. This is the entire code that I have created:
import java.util.Arrays;
import java.util.Scanner;
public class School {
private Student[] theStudents;
public School() {
this.theStudents = new Student[0];// needs to start out as empty
}
/*
* next two methods would allow a user to add or drop a student into the
* student array for the school ??Also with Enroll student, should be able
* to assign a class to the student, i.e. Calculas, history, etc??
*/
public void enrollStudent(Student newStudent) {
Student totalStudents[] = new Student[theStudents.length + 1];
for (int i = 0; i < theStudents.length; i++) {
totalStudents[i] = theStudents[i];
}
totalStudents[theStudents.length] = newStudent;
theStudents = totalStudents;
}
public void dropStudent(String dropStudent) {
boolean checkForName = false;
for (int i = 0; i < theStudents.length; i++) {
if (theStudents[i].getName().equals(dropStudent)) {
theStudents[i] = null;
checkForName = true;
}
}
if (checkForName == true) {
Student totalStudents[] = new Student[theStudents.length - 1];
for (int i = 0; i < totalStudents.length; i++) {
if (theStudents[i] == null) {
totalStudents[i] = theStudents[theStudents.length - 1];
} else {
totalStudents[i] = theStudents[i];
}
}
theStudents = totalStudents;
}
if (checkForName == false) {
System.out.println("The Student does not exist in the school");
}
}
// add Test Score for a student
public void addTestScore(String newStudent, double testScore) {
for (int i = 0; i < theStudents.length; i++) {
if (newStudent.equals(theStudents[i])) {
theStudents[i].addTestScore(testScore);
}
}
}
/*
* count the number of students in a given class, not the school
*/
public int countClassSize(String course) {
// Need to access how the course names are stored for the school to
// count this size.
int count = 0;
for (int i = 0; i < theStudents.length; i++) {
if (theStudents[i].getClassName().equals(course)) {
count = count + 1;
}
}
return count;
}
/*
* get average average score of the student array The student array is made
* up of Regular students and CompSciStudents. The average should take the
* average of both the average score for Students and average score of
* CompSciStudents and return the average average.
*/
public double averageAverageScore(String course) {
double avgAvgTest = 0;
for (int i = 0; i < theStudents.length; i++) {
if (theStudents[i].getClassName().equals(course)) {
avgAvgTest += theStudents[i].getTestAvg();
}
}
return avgAvgTest / this.countClassSize(course);
}
/*
* add a programming language to only CS students at the school Will need to
* use the instanceof for proper type casting
*/
public void addProgrammingLanguage(String studentName, String programLanguage) {
for (int i = 0; i < theStudents.length; i++) {
if (this.theStudents[i] instanceof CompSciStudent) {
CompSciStudent tempStudent = (CompSciStudent) this.theStudents[i];
tempStudent.learnedLanguage(programLanguage);
}
}
}
/*
* Count the number of students in the school that know a certain
* programming language, again will need to typecast properly
*/
public int numberThatKnowLanguage(String programLanguage) {
int count = 0;
for (int i = 0; i < theStudents.length; i++) {
if (this.theStudents[i] instanceof CompSciStudent) {
CompSciStudent tempStudent = (CompSciStudent) this.theStudents[i];
String knowThisLanguage = programLanguage;
tempStudent.learnedLanguage(knowThisLanguage);
count += 1;
}
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String dropStudent, course;
System.out.println("Welcome to the School. Please select\n" + " Option 1 to enroll a regular student,"
+ "Option 2 to enroll a CompSci student, \n" + "Option 3 to drop a student, \n"
+ "Option 4 to add test score or programming language, or \n" + "Option 5 to perform class analytics.");
int Operation = input.nextInt();
/*
* Simple UI to add and drop students, will need to set the operation to
* call the add and drop students to fit them to the Student body array
* will need to make these two options loop until the user is satisfied
* with the size of the student body
*/
if (Operation == 1) {
System.out.println("Enter the # of regular students that you want to add to the school.");
int addStudents = input.nextInt();
// Possibly create some type of input array to
// make it easier to enter the students' names. for(<type> <var
// name> : <array name>)
System.out.println("Please enter the name and course of the student you are enrolling:");
for (int i = 0; i < addStudents; i++) {
String newRegularStudent = (String) input.next();
course = input.next();
System.out.println("Enter next student's name and then the course's name that he is enrolling in.");
}
} else if (Operation == 2) {
System.out.println("Enter the # of CompSci students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
String newCompSciStudent = (String) input.next();
course = input.next();
}
else if (Operation == 3) {
System.out.println("Enter the # of students that you want to drop from the school.");
int dropStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name of the student you wish to drop from the school:");
dropStudent = (String) input.next();
/*
* After the first two operations, will need to build to the UI to
* call the other five methods, will need to make it into a
* while/for loop so user can continue to add information as needed.
*/
}
else if (Operation == 4) {
System.out.println("Enter the # for what you want to add to a student's records."
+ "Enter 1 to enter a test score\n " + "Enter 2 to enter a programming language, enter 2.");
int optionNum1 = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
if (optionNum1 == 1) {
} else if (optionNum1 == 2) {
}
}
else if (Operation == 5) {
System.out.println("This is the analytics section of this program.\n");
System.out.println("Enter the # for which of the following analytics options that you want performed: "
+ "Enter 1 to count the # of students for a particular class,\n "
+ "Enter 2 to calculate the average average score for all students take a particular course, or\n "
+ "Enter 3 to count the # of CompSciStudents.");
int optionNum2 = input.nextInt();
if (optionNum2 == 1) {
System.out.println("Enter the course name that you\n" + " want to know the # of students for.");
course = input.next();
Student classSize;
}
else if (optionNum2 == 2) {
System.out.println(
"Enter the course name that you want to \n" + "calculate the average average test value for.");
course = input.next();
Student testAvg;
}
else if (optionNum2 == 3) {
System.out.println("Count the # of CompSciStudents who know a particular programming\n"
+ " language by entering that language name now.");
String programLanguage = input.next();
CompSciStudent csStudent = null;
csStudent.knowsLanguage(programLanguage);
}
}
input.close();
}
}
You cannot change the size of an array in Java at runtime. The size of your array therefore will always be zero since you wrote:
this.theStudents = new Student[0];
I would suggest you to use:
ArrayLists<type> list = new ArrayLists<type>();
If you do now know how to use ArrayLists you can follow this tutorial.
I want to read data from a text file and print the output to both the terminal and a text file. I have a loop that reads for numbers and one that reads for non-numerical characters, but nothing is printing out to the terminal. i am new to programming.
I am transforming an old project to a new one by the way.
package studenttester;
public class Student
{
private String name;
double quizScore;
double quizAverage;
private int numQuizzes;
String grade;
/**
* Returns the name of a student
*
* #return the name of the student
*/
public Student (String inName)
{
name = inName;
quizAverage = 0;
quizScore = 0;
numQuizzes = 0;
}
public String getName()
{
return name;
}
/**
* Adds a quiz score to the total quiz score of the student
*
* #param score the score of a quiz
*/
void addQuiz(int score)
{
numQuizzes += 1;
quizScore += score;
}
/**
* Returns the total score of all the quizzes combined that student took
*
* #return the value of score
*/
double getTotalScore()
{
return quizScore;
}
/**
* Returns the average score of all the quizzes a student took
*
* #return
*/
double getAverageScore()
{
return quizScore / numQuizzes;
}
}
package studenttester;
import java.io.*;
import java.util.Scanner;
public class StudentTester {
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Student Name Number of Quizzes Average");
Scanner reader = new Scanner(new File("quizScores.txt"));
String studentName = "", first="", last="";
while (!reader.hasNext("-10"))
{
}
while (reader.hasNextDouble())
{
first = first+reader.next();
studentName = last + first;
}
Student newStudent = new Student(studentName);
while (reader.hasNextDouble() && !reader.hasNext("-10"))
{
System.out.printf("");
}
{
// writer.close;
}
}
}
The "red underline" means an compiler error, I guess.
Have a look to your while loop, it seems to be wrong.
Try ...
while (reader.hasNextDouble() && (!reader.hasNext("-10")))
System.out.printf("");
}
reader.close();
instead.