Number format exception in java, taking wrong input - java

When using the code
else if(command.equalsIgnoreCase("add")) {
System.out.println("Enter the Student's Name: ");
String name = input.nextLine();
System.out.println("Enter the Student's Number: ");
String studNum = input.nextLine();
System.out.println("Enter the Student's Address: ");
String address = input.nextLine();
langara.addStudent(name, address, studNum);
System.out.println("A Student added to the College Directory");
}
If the user enters add, it's suppose to go through the above procedure, In the collage class (langara) there is a "addStudent" method :
public void addStudent(String name, String address, String iD) {
Student firstYear = new Student(name, address, iD);
collegeStudents.add(firstYear);
}
And this creates a student object of the student class using the constructor:
public Student(String name, String address, String iD) {
long actualId = Long.parseLong(iD);
studentName = name;
studentID = actualId;
studentAddress = new Address(address);
numberOfQuizzes = 0;
scoreTotal = 0;
}
I'm getting the error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Abernathy, C."
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
at Student.<init>(Student.java:48)
at College.addStudent(College.java:33)
at CollegeTester.main(CollegeTester.java:53)
It's as if it's trying to convert the Students name to long, but it's supposed to convert the student ID to long..
This is where scanner is created, college is created, and command is initialized:
Scanner input = new Scanner(System.in);
College langara = new College();
String command = "";
System.out.print("College Directory Commands:\n" +
"add - Add a new Student\n" +
"find - Find a Student\n" +
"addQuiz - Add a quiz score for a student\n" +
"findHighest - Find a student with the highest quiz score\n" +
"delete - Delete a Student\n" +
"quit - Quit\n");
command = input.nextLine();
The input is being read from a input.txt file, with each input on it's own line.
The input at the beginning of the file for this command is:
add
Abernathy, C.
10010123
100, West 49 Ave, Vancouver, BC, V7X2K6
What is going wrong here?

It looks right now, but I would swear that when I first looked at this (and copy/pasted your code) that the call to langara.addStudent had the parameters as name, studNum, address. I put this class together with your input file and it appears to work fine:
import java.io.FileInputStream;
import java.util.Scanner;
public class StackOverflow_32895589 {
public static class Student
{
String studentName;
long studentID;
String studentAddress;
long numberOfQuizzes;
long scoreTotal;
public Student(String name, String address, String iD)
{
studentName = name;
studentID = Long.parseLong(iD);
studentAddress = address;
numberOfQuizzes = 0;
scoreTotal = 0;
}
}
public static void main(String[] args)
{
try{
System.setIn(new FileInputStream("c:\\temp\\input.txt"));
}
catch (Exception e)
{
throw new RuntimeException(e);
}
Scanner input = new Scanner(System.in);
String command = input.nextLine();
if (command.equals("add"))
{
System.out.println("Enter the Student's Name:");
String name = input.nextLine();
System.out.println("Enter the Student's Number:");
String studNum = input.nextLine();
System.out.println("Enter the Student's Address:");
String address = input.nextLine();
System.out.println("[" + name + "][" + studNum + "][" + address + "]");
input.close();
addStudent(name, address, studNum);
}
}
public static void addStudent(String name, String address, String iD)
{
Student firstYear = new Student(name, address, iD);
}
}

Related

Runtime error with scanners

Why does my code have a runtime error?(java)
import java.util.Scanner;
public class StudentID
{
static int gradeLevel;
static int id;
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("---Student ID---");
System.out.print("Enter your first name: ");
String firstName = keyboard.next();
System.out.print("\nEnter your last name: ");
String lastName = keyboard.next();
System.out.print("\nEnter your grade level: ");
gradeLevel = keyboard.nextInt();
System.out.print("\nEnter your id: ");
id = keyboard.nextInt();
System.out.print("\nThe text for your student id is:");
String result = getIDText(firstName, lastName, gradeLevel, id);
System.out.print(result);
}
public static String getIDText(
String firstName,
String lastName,
int gradeLevel,
int id)
{
String result =
"\n\nName: " + lastName + ", " + firstName +
"\nGrade: " + gradeLevel +
"\nID: " + id;
return result;
}
}
I can enter my my data just fine, but after type in my ID and press enter, my program crashes saying i have an error at id = keyboard.nextInt();
My error is this:
java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:864) at
java.util.Scanner.next(Scanner.java:1485) at
java.util.Scanner.nextInt(Scanner.java:2117) at
java.util.Scanner.nextInt(Scanner.java:2076) at
StudentID.main(StudentID.java:18)
Code works fine in case you print integer value for ID. If you print String value, like e.g. aaa, you get this java.util.InputMismatchException. If you would like to check incorrect data, you have to read always String an then in the code manually convert it.
P.S. You should close Scanner isntance somehwere: keyboard.close()
There are 2 ways to resolve this:
1. use keyboard.nextLine() instead of keyboard.next if your string input has spaces in between as the input is considered only till it encounters first space.
2. if you want to use keyboard.next() only, the check whether the input is int when you want for e.g:
if(keyboard.hasNextInt())
{
id = keyboard.nextInt();
}

stack overflow error when using constructor with 2D dynamic graphic [duplicate]

Please excuse what is probably a very basic question, but I am writing a program to store employee info and it works fine until it tries to set the info inside my employee class. It gives a stackoverflow error and I cannot figure out why. Thanks for any help.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}
Employee class:
public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;
public Employee()
{
}
public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}
Name class:
public class Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? ...
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
Bingo: recursion!
This constructor will create a new Name object whose constructor will create a new Name object whose constructor will... and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don't do this. Assign name to a String:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)

Inputting into an array using scanner class (error: incompatible types: Scanner cannot be converted to String)

I'm trying to input student details using a scanner but I keep getting this error:
error: incompatible types: Scanner cannot be converted to String
I have 4 scanners which are
static Scanner name = new Scanner(System.in);
static Scanner Date = new Scanner(System.in);
static Scanner address = new Scanner(System.in);
static Scanner gender = new Scanner(System.in);
My code is as follows
System.out.println("You have chosen to add a student. Please enter the following details");
System.out.println("Name: ");
String Name = name.nextLine();
System.out.println("DOB: ");
String DOB = Date.nextLine();
System.out.println("Address: ");
String Address = address.nextLine();
System.out.println("Gender: ");
String Gender = gender.nextLine();
app.addStudent(name, DOB, address, gender);
System.out.println(Name + " has been added!" + "\n" + "Returning to menu....");
app.delay();
The addStudent method is as follows
public void addStudent (String name,String DOB,String address,String gender)
{
for(int i = 0; i < enrolment.length; i++)
{
if (enrolment[i] == null)
{
this.enrolment[size] = new Student(name, DOB, address, gender);
this.size++;
if (gender == "Male")
{
this.maleStudents++;
}
else {
this.femaleStudents++;
}
break;
}
}
}
The problem is that you're passing your Scanner objects to your addStudent method instead of the strings that you obtained from the scanners:
app.addStudent(name, DOB, address, gender);
Should be
app.addStudent(Name, DOB, Address, Gender);
Also:
one Scanner object should be sufficient. No need for four of them.
Java code conventions dictate that variable names are in lower camel-case, i.e. gender instead of Gender.
Putting everything together, your code should look something like this:
Scanner scanner = new Scanner(System.in);
System.out.println("You have chosen to add a student. Please enter the following details");
System.out.println("Name: ");
String name = scanner.nextLine();
System.out.println("DOB: ");
String dob = scanner.nextLine();
System.out.println("Address: ");
String address = scanner.nextLine();
System.out.println("Gender: ");
String gender = scanner.nextLine();
app.addStudent(name, dob, address, gender);
System.out.println(name + " has been added!" + "\n" + "Returning to menu....");
You only need one scanner, not one for each input.
In you code you are confusing Name (the string) with name (the scanner).
This is why there are naming rules.
Try changing to
Scanner input = new Scanner (System.in);
String name = input.nextLine ();
String gender = input.nextLine ();
...
then
app.addStudent (name, dob, address, gender);
try also reading about naming conventions
name, adress, and gender are scanners, your method takes Strings
app.addStudent(Name, DOB, Address, Gender);
is the method with the String variables that you defined

How can I combine an extra variable to an array/method?

I have created a simple program which outputs student details. Ideally I would like to give the user an option to add both courses. Will this require a lot of messing about changing code? If not can someone help?
class Student
{
public static void main(String[]args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which course do you want to add the student to? .......Literacy or Numeracy ");
courseName = input.next();
TheStu [x] = new Stu (surName, foreName, age, telephone, courseName);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled on the " + TheStu[y].getcourseType() + " Course.");
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String courseType;
Stu (String s, String f, int a, int p, String c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseType = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String getcourseType()
{
return courseType;
}
}
If you want something pretty basic, you could change your courses into a String array so you could store both courses. Also when asking the user to input a course name, you could have an ALL option, so you automatically register the student for all courses. See below for a slightly modified version of your code :
import java.util.Scanner;
class Student
{
public static void main(String[] args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
String[] courses = new String[]{};
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which courses do you want to add the student to? .......Literacy or Numeracy or both ");
courseName = input.nextLine();
// change to either upper case or lower case for easy treatment
courseName = courseName.toUpperCase();
// Also verify that the user entered a valid course name
if(courseName.equals("LITERACY")){
courses = new String[]{"LITERACY"};
} else if(courseName.equals("NUMERACY")){
courses = new String[]{"NUMERACY"};
} else if(courseName.equals("BOTH")){
courses = new String[]{"LITERACY", "NUMERACY"};
} else{
System.out.println("Error : You entered an invalid option.... \n This student won't be registered for any courses");
}
TheStu [x] = new Stu (surName, foreName, age, telephone, courses);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled in the following courses : ");
courses = TheStu[y].getcourseTypes();
for(int i = 0; i < courses.length; i++){
System.out.println(courses[i]);
}
if(courses.length < 1){
System.out.println("No Courses");
}
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String[] courseTypes;
Stu (String s, String f, int a, int p, String[] c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseTypes = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String[] getcourseTypes()
{
return courseTypes;
}
}
I tried as much as possible not to make any serious changes to your code as i assume you're a beginner, but there are a lot of changes you could make to improve your code. Happy Coding :)
When you ask for the course name, keep asking until they have entered in a sentinal value. Inside Stu keep an List<String> courseTypes. Store the entered courses in courseTypes. Also, you may want to add a set value to some of the fields in Stu. What if their phone number changes?

How do I count data objects in Java

I have an assignment that asks me to create students with first name, last name, GPA and major as options the user can input and I am supposed to give these "students" a student ID as well. I can give them an ID in the constructor of one of the classes but I can't seem to iterate through the student count, to give the students the correct type of student id, eg. 123456, 123457, 123458 etc. I am only pasting a few lines because the whole assignment is about 300 lines long and I didn't think anyone cared to read it all over. Can anyone tell me what I'm doing wrong or if this doesn't even make sense to try? I know of another way but I don't like it because it makes me have the student id numbers stored in a separate ArrayList than the other student data and then I would just match up indices. Here's the constructor, with count being initialized as a field with 0...
public Student( String fName, String lName, String maj, double gpa) {
sNumber += count++;
firstName = fName;
lastName = lName;
major = maj;
this.gpa = gpa;
}
Here's the add method from another class....
private static void addStudent(ArrayList<Student> L) {
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("First name: ");
String uFName = input.nextLine();
System.out.print("Last name: ");
String uLName = input.nextLine();
System.out.print("Major: ");
String studyMaj = input.nextLine();
System.out.print("GPA: ");
double grades = input.nextDouble();
Student newStudent = new Student(uFName, uLName, studyMaj, grades);
L.add(newStudent);
input.close();
}
try this
public Student( String fName, String lName, String maj, double gpa,number ) {
firstName = fName;
lastName = lName;
major = maj;
this.gpa = gpa;
sNumber = number;
}
private static void addStudent(ArrayList<Student> L) {
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("First name: ");
String uFName = input.nextLine();
System.out.print("Last name: ");
String uLName = input.nextLine();
System.out.print("Major: ");
String studyMaj = input.nextLine();
System.out.print("GPA: ");
double grades = input.nextDouble();
int number=0;
if(l.size()>0){
number=l.get(l.size()-1).getSNumber()+1;
}
Student newStudent = new Student(uFName, uLName, studyMaj, grades,number);
L.add(newStudent);
input.close();
}

Categories