My program is only reading the name of the file and none of the contents inside. I get an ElementDoesNotExist error every time. The file is in the same folder, and I have no idea why it won't read the contents. I understand that this program is inefficient, and it's my first time using File IO in Java.
import java.util.*;
import java.io.*;
public class Project4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the year: ");
int fileYear = input.nextInt();
String userFile = "";
if (fileYear == 2001)
{
userFile = "BabyNames2001.txt";
}
else if (fileYear == 2002)
{
userFile = "BabyNames2002.txt";
}
else if (fileYear == 2003)
{
userFile = "BabyNames2003.txt";
}
else if (fileYear == 2004)
{
userFile = "BabyNames2004.txt";
}
else if (fileYear == 2005)
{
userFile = "BabyNames2005.txt";
}
else if (fileYear == 2006)
{
userFile = "BabyNames2006.txt";
}
else if (fileYear == 2007)
{
userFile = "BabyNames2007.txt";
}
else if (fileYear == 2008)
{
userFile = "BabyNames2008.txt";
}
else if (fileYear == 2009)
{
userFile = "BabyNames2009.txt";
}
else if (fileYear == 2010)
{
userFile = "BabyNames2010.txt";
}
File theFile = new File(userFile);
ArrayList<BabyName> theBabies = loadNames("BabyNames2001.txt", fileYear);
System.out.print("Enter the gender: ");
String babyGender = input.next();
System.out.print("Enter the name: ");
String babyName = input.next();
findName(babyName, fileYear, theBabies);
}
private static ArrayList<BabyName> loadNames(String fileName, int checkYear)
{
ArrayList<BabyName> babies = new ArrayList<BabyName>();
int currentYear = checkYear;
String chooseFile = fileName;
Scanner reader = new Scanner(chooseFile);
while (reader.hasNext())
{
BabyName boy = new BabyName();
BabyName girl = new BabyName();
boy.setYear(currentYear);
girl.setYear(currentYear);
boy.setGender("M");
girl.setGender("F");
String currentRank = reader.next();
boy.setRank(currentRank);
String boyName = reader.next();
int boyTotal = reader.nextInt();
String girlName = reader.next();
int girlTotal = reader.nextInt();
girl.setRank(currentRank);
boy.setName(boyName);
girl.setName(girlName);
boy.setTotal(boyTotal);
girl.setTotal(girlTotal);
babies.add(boy);
babies.add(girl);
}
return babies;
}
private static BabyName findName(String name, int year, ArrayList<BabyName> babies)
{
ArrayList<BabyName> theBabies = babies;
BabyName tempBaby = new BabyName();
String findName = name;
int findYear = year;
for (int baby = 0; baby < 2000; baby++)
{
if (findName == theBabies.get(baby).getName())
{
tempBaby = theBabies.get(baby);
}
}
return tempBaby;
}
}
class BabyName
{
private String rank;
private int year;
private String name;
private String gender;
private int total;
BabyName()
{
}
public String getRank()
{
return rank;
}
public int getYear()
{
return year;
}
public String getName()
{
return name;
}
public String getGender()
{
return gender;
}
public int getTotal()
{
return total;
}
public void setRank(String newRank)
{
this.rank = newRank;
}
public void setYear(int newYear)
{
this.year = newYear;
}
public void setName(String newName)
{
this.name = newName;
}
public void setGender(String newGender)
{
this.gender = newGender;
}
public void setTotal(int newTotal)
{
this.total = newTotal;
}
}
Your problem is here:
Scanner reader = new Scanner(chooseFile);
The Scanner class has multiple overloaded constructors. chooseFile is a String, so you are calling Scanner(String) when what you probably want is Scanner(File). Because of this your code does not read any files, it is reading the literal string "BabyNames2001.txt".
The solution is to simply pass a File instead of a String, or something along the lines of:
Scanner reader = new Scanner(new File(chooseFile));
Related
So I have a text file named "phone.txt" and I loaded it into an arraylist, the problem is now I don't know how to use that arraylist on my methods in the same class. Let's say on my method "optionP" that I want the customer to be able to search for a name in that arraylist and that person's info will be displayed, how would I do it? So far my code is like this:
import java.util.*;
import java.io.*;
public class Directory {
Scanner kbd = new Scanner(System.in);
ArrayList<Person> persons = new ArrayList<Person>();
public void run() throws FileNotFoundException {
String firstName;
String lastName;
String initial;
String department;
int telNum;
File inFile = new File("phone.txt");
Scanner in = new Scanner(inFile);
while (in.hasNext()) {
Person list;
lastName = in.next();
firstName = in.next();
initial = in.next();
department = in.next();
telNum = in.nextInt();
list = new Person(lastName, firstName, initial, department, telNum);
persons.add(list);
}
in.close();
int i;
i = 0;
while (i < persons.size()) {
System.out.println(persons.get(i).toString());
i++;
}
char userInput = kbd.next().charAt(0);
if (userInput == 'p' || userInput == 'P') {
optionP();
} else if (userInput == 'l' || userInput == 'L') {
optionL();
} else if (userInput == 'r' || userInput == 'R') {
optionR();
} else if (userInput == 'c' || userInput == 'C') {
optionC();
} else if (userInput == 'a' || userInput == 'A') {
optionA();
} else {
optionD();
}
}
public void optionP() {
}
public void optionL() {
}
public void optionR() {
}
public void optionC() {
}
public void optionA() {
}
public void optionD() {
}
public class Person {
String firstName;
String lastName;
String initial;
String department;
int telNum;
public Person(String firstName, String lastName, String initial, String department, int telNum) {
this.firstName = firstName;
this.lastName = lastName;
this.initial = initial;
this.department = department;
this.telNum = telNum;
}
}
}
I'm guessing the file has data and that you are able to see the data when you print it on the console, if not you have to fix that first
Secondly if you wish to read from an arrayList
for(Person p:persons){
//do what you want
}
OptionP needs to go through the ArrayList and finds the corresponding result
Additionally, because you need to iterate the ArrayList, it's better to use LinkedList instead.
You may also need to add a toString method to describe the result.
import java.util.*;
import java.io.*;
public class Directory {
Scanner kbd = new Scanner(System.in);
List<Person> persons = new LinkedList<Person>();
public void run() throws FileNotFoundException {
String firstName;
String lastName;
String initial;
String department;
int telNum;
File inFile = new File("/Users/zhaojing/Desktop/phone.txt");
Scanner in = new Scanner(inFile);
while (in.hasNext()) {
Person list;
lastName = in.next();
firstName = in.next();
initial = in.next();
department = in.next();
telNum = in.nextInt();
list = new Person(lastName, firstName, initial, department, telNum);
persons.add(list);
}
in.close();
int i;
i = 0;
while (i < persons.size()) {
i++;
}
char userInput = kbd.next().charAt(0);
if (userInput == 'p' || userInput == 'P') {
optionP();
} else if (userInput == 'l' || userInput == 'L') {
optionL();
} else if (userInput == 'r' || userInput == 'R') {
optionR();
} else if (userInput == 'c' || userInput == 'C') {
optionC();
} else if (userInput == 'a' || userInput == 'A') {
optionA();
} else {
optionD();
}
}
public Person optionP() {
String userInputFirstName = kbd.next();
for (Person p : persons) {
if (Objects.equals(userInputFirstName, p.firstName)) {
System.out.println(p.toString());
return p;
}
}
return null;
}
public void optionL() {
}
public void optionR() {
}
public void optionC() {
}
public void optionA() {
}
public void optionD() {
}
public class Person {
String firstName;
String lastName;
String initial;
String department;
int telNum;
public Person(String firstName, String lastName, String initial, String department, int telNum) {
this.firstName = firstName;
this.lastName = lastName;
this.initial = initial;
this.department = department;
this.telNum = telNum;
}
#Override
public String toString() {
return "result: Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", initial='" + initial + '\'' +
", department='" + department + '\'' +
", telNum=" + telNum +
'}';
}
}
}
I'm learning java language and I saw this code. I was wondering if I can add an if else condition that if the grade is below 80, it will print failed and else passed. Like.
System.out.print("Your Grade is ");
if(avg>80)
{
System.out.print("A");
I searched for other links but I can't find anything. I hope someone can help me. Thanks in advance.
import java.util.*;
public class UserInteraction {
public static void main(String[] args) {
UserChoiceManager userChoiceManager = new UserChoiceManager();
UserChoice choice = UserChoice.UNKNOWN;
do {
choice = userChoiceManager.manage();
} while (choice != UserChoice.EXIT);
System.out.println("Thank you for using the system!");
}
}
enum UserChoice {
UNKNOWN(0),
ENTER_SUBJECT(1),
DISPLAY_DATA(2),
CALCULATE_AVERAGE_GRADE(3),
EXIT(4);
private int id;
public int getId() {
return id;
}
UserChoice(int id) {
this.id = id;
}
public static UserChoice getById(int input) {
for (UserChoice value : UserChoice.values()) {
if (value.getId() == input) {
return value;
}
}
return UserChoice.UNKNOWN;
}
}
class Subject {
private String name;
private int grade;
public Subject(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
class UserChoiceManager {
private final static int SUBJECT_COUNT = 3;
private Subject[] subjects = new Subject[SUBJECT_COUNT];
private Scanner scan = new Scanner(System.in);
public UserChoiceManager() {
}
public UserChoice manage() {
System.out.println(printHelp());
UserChoice choice = getUserChoiceById(scan);
if (choice == UserChoice.ENTER_SUBJECT) {
choice = enterSubjects(choice);
}
if (choice == UserChoice.DISPLAY_DATA) {
printSubjectsAndGrades();
}
if (choice == UserChoice.CALCULATE_AVERAGE_GRADE) {
printAverageGrade();
}
return choice;
}
private static String printHelp() {
StringBuilder usage = new StringBuilder("\nUsage:\n");
usage.append(UserChoice.ENTER_SUBJECT.getId()).append(". Enter a subject name and a corresponding grade").append("\n");
usage.append(UserChoice.DISPLAY_DATA.getId()).append(". Display all grades").append("\n");
usage.append(UserChoice.CALCULATE_AVERAGE_GRADE.getId()).append(". Calculate the average grade").append("\n");
usage.append(UserChoice.EXIT.getId()).append(". Exit system");
return usage.toString();
}
private UserChoice getUserChoiceById(Scanner scan) {
return UserChoice.getById(scan.nextInt());
}
private UserChoice enterSubjects(UserChoice choice) {
System.out.println("Enter " + subjects.length + " subjects and their corresponding grades:");
System.out.println();
for (int i = 0; i < subjects.length; i++) {
String subjectName = scanSubjectName();
int grade = scanGrade();
subjects[i] = new Subject(subjectName.toLowerCase(), grade);
}
System.out.println("Thank you!");
System.out.println();
return choice;
}
private String scanSubjectName() {
Scanner temp = new Scanner(System.in);
String subjectName = "";
do {
System.out.println("Subject:");
subjectName = temp.nextLine();
if (subjectName.equals("")) {
System.out.println("Empty subject name! Try again.");
}
} while (subjectName.equals(""));
return subjectName;
}
private int scanGrade() {
int grade = 0;
do {
Scanner temp = new Scanner(System.in);
System.out.println("Grade:");
try {
grade = temp.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid grade. Enter numeric value! Try again.");
}
} while (grade == 0);
return grade;
}
private void printAverageGrade() {
System.out.println("Total of grades: " + getSum(subjects));
System.out.println("Count of grades: " + subjects.length);
System.out.println("Your average grade is: " + getAverage(subjects));
System.out.println();
}
private void printSubjectsAndGrades() {
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for (int p = 0; p < subjects.length; p++) {
System.out.println(subjects[p].getName() + "\t" + "\t" + subjects[p].getGrade());
}
}
public static double getAverage(Subject[] subjects) {
int sum = 0;
for (Subject s : subjects)
sum += s.getGrade();
return ((double) sum) / subjects.length;
}
public static double getSum(Subject[] subjects) {
int sum = 0;
for (Subject s : subjects) {
sum += s.getGrade();
}
return sum;
}
}
I tried adding some if functions in print out tag but it's not working.
Change your implementation of printAverageGrade to this, and the program will print out what you want:
private void printAverageGrade() {
System.out.println("Total of grades: " + getSum(subjects));
System.out.println("Count of grades: " + subjects.length);
double average = getAverage(subjects);
System.out.println("Your average grade is: " + average);
System.out.print("Your Grade is ");
if (average > 80) {
System.out.println("A");
} else {
System.out.println("Failed");
}
System.out.println();
}
I'm writing a program to take and organize class info, including the students in a class, recorded by ID and Grade. I'm able to add the students as desired, and they print as desired (so I know the entries are correct), but when I go to search for a student, the search method is only able to find the last entered student ID. Why is my search function breaking down?
The search function:
public static int studentFinder(ClassSection classOne) {
int studentIndex = 0;
boolean searchAgain = false;
boolean correctStudent = false;
do {
studentIndex = idFinder(classOne);
if (studentIndex == -1) {
System.out.println("That student was not found in the class");
System.out.println("Would you like to search again?");
searchAgain = yesNoBool();
} else {
System.out.println("You have selected student ID# " +classOne.getStudentIDByIndex(studentIndex));
System.out.println("Is this correct?");
correctStudent = yesNoBool();
if (!correctStudent) {
System.out.println("Would you like to search again?");
searchAgain = yesNoBool();
}
}
} while(searchAgain);
return studentIndex;
}
ID Finder module:
public static int idFinder(ClassSection classOne) {
int studentID = 0;
String intString = "a Student ID to search for:";
int studentIndex = 0;
System.out.println("Please enter a Student ID to search for:");
studentID = intChecker(intString);
for (int i = 0; i < classOne.students.size(); i++) {
int studentIdTest = classOne.students.get(i).getStudentID();
if (studentIdTest == studentID) {
studentIndex = i;
} else if (studentIdTest != studentID){
studentIndex = -1;
}
}
return studentIndex;
}
The ClassSection class:
import java.util.*;
public class ClassSection {
//instance variables
protected int crnNum = 0;
protected String deptCode = "null";
protected int courseNum = 0;
protected String instructMode = "null";
protected String meetingDays = "null";
protected String meetingTimesStart = "null";
protected String meetingTimesEnd = "null";
protected int classCapacity = 0;
protected int classEnrollment = 0;
protected int instructorID = 0;
protected ArrayList<StudentEnrollee> students = new ArrayList<StudentEnrollee>();
//constructors
public ClassSection(int crnNum, String deptCode, int courseNum, String instructMode, String meetingDays,
String meetingTimesStart, String meetingTimesEnd, int classCapacity, int classEnrollment,
int instructorID) {
super();
this.crnNum = crnNum;
this.deptCode = deptCode;
this.courseNum = courseNum;
this.instructMode = instructMode;
this.meetingDays = meetingDays;
this.meetingTimesStart = meetingTimesStart;
this.meetingTimesEnd = meetingTimesEnd;
this.classCapacity = classCapacity;
this.classEnrollment = classEnrollment;
this.instructorID = instructorID;
}
public ClassSection() {
super();
this.crnNum = 0;
this.deptCode = "";
this.courseNum = 0;
this.instructMode = "";
this.meetingDays = "";
this.meetingTimesStart = "";
this.meetingTimesEnd = "";
this.classCapacity = 0;
this.classEnrollment = 0;
this.instructorID = 0;
}
//getters and setters
public void getStudents() {
this.students.forEach(System.out::println);
}
public int getStudentIDByIndex(int index) {
return this.students.get(index).getStudentID();
}
public void addStudent(StudentEnrollee student) {
this.students.add(student);
}
public void removeStudent(int removalIndex) {
this.students.remove(removalIndex);
}
public void changeAddStudentGrade(int studentIndex, int studentGrade) {
this.students.get(studentIndex).setStudentGrade(studentGrade);
}
public int getCrnNum() {
return crnNum;
}
public void setCrnNum(int crnNum) {
this.crnNum = crnNum;
}
public String getDeptCode() {
return deptCode;
}
public void setDeptCode(String deptCode) {
this.deptCode = deptCode;
}
public int getCourseNum() {
return courseNum;
}
public void setCourseNum(int courseNum) {
this.courseNum = courseNum;
}
public String getInstructMode() {
return instructMode;
}
public void setInstructMode(String instructMode) {
this.instructMode = instructMode;
}
public String getMeetingDays() {
return meetingDays;
}
public void setMeetingDays(String meetingDays) {
this.meetingDays = meetingDays;
}
public String getMeetingTimesStart() {
return meetingTimesStart;
}
public void setMeetingTimesStart(String meetingTimesStart) {
this.meetingTimesStart = meetingTimesStart;
}
public String getMeetingTimesEnd() {
return meetingTimesEnd;
}
public void setMeetingTimesEnd(String meetingTimesEnd) {
this.meetingTimesEnd = meetingTimesEnd;
}
public int getClassCapacity() {
return classCapacity;
}
public void setClassCapacity(int classCapacity) {
this.classCapacity = classCapacity;
}
public int getClassEnrollment() {
return classEnrollment;
}
public void setClassEnrollment(int classEnrollment) {
this.classEnrollment = classEnrollment;
}
public int getInstructorID() {
return instructorID;
}
public void setInstructorID(int instructorID) {
this.instructorID = instructorID;
}
//mutators
#Override
public String toString() {
return String.format("Crn Number: %20s \nDept Code: %20s \nInstruction Mode: %20s"
+ " \nCourse Number: %20s \nClass Capacity: %20s \nClass Enrollment: %20s"
+ " \nMeeting Days: %20s \nMeeting Times: %8$20s - %9$2s \nInstructor ID: %10$20s \n" + Arrays.toString(students.toArray()).replace("[", "").replace(", S","S").replace("]", "").trim(),
crnNum, deptCode, instructMode, courseNum, classCapacity, classEnrollment, meetingDays,
meetingTimesStart, meetingTimesEnd, instructorID);
}
}
The student enrollee class (where the objects in the arraylist are from):
public class StudentEnrollee {
protected int studentID = 0;
protected int studentGrade = 0;
public StudentEnrollee() {
super();
studentID = 0;
studentGrade = 0;
}
public StudentEnrollee(int studentID, int studentGrade) {
super();
this.studentID = studentID;
this.studentGrade = studentGrade;
}
//setters & getters
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public int getStudentGrade() {
return studentGrade;
}
public void setStudentGrade(int studentGrade) {
this.studentGrade = studentGrade;
}
#Override
public String toString() {
return String.format("Student ID: %20s \nStudent Grade: %20s \n", studentID, studentGrade);
}
}
The intchecker and yesNoBool methods are just error checking and confirmation functions, but here they are just in case:
public static int intChecker(String object) {
boolean correctInput = false;
int userInput = 0;
while (!correctInput) {
try {
userInput = scanner.nextInt();
correctInput = true;
} catch(InputMismatchException e) {
System.out.println("I'm sorry, that doesn't seem to be a number");
System.out.println("Please enter " +object);
scanner.next();
}
}
return userInput;
}
public static boolean yesNoBool() {
String yesNo = "";
boolean yesNoBool = false;
System.out.println("Please enter Y/N");
yesNo = scanner.next();
while ((!yesNo.equalsIgnoreCase("n") && !yesNo.equalsIgnoreCase("y"))){
System.out.println("I'm sorry, please enter Y/N");
yesNo = scanner.next();
}
if (yesNo.equalsIgnoreCase("y")) {
yesNoBool = true;
} else if (yesNo.equalsIgnoreCase("n")) {
yesNoBool = false;
}
return yesNoBool;
}
Once you found the match you have to break the loop, otherwise studentIndex gets overwritten for rest of the records for which loop iterating. Also you don't need if(studentIdTest != studentID) just else is also work same.
Add Break in loop in idFinder method as follows:
for (int i = 0; i < classOne.students.size(); i++) {
int studentIdTest = classOne.students.get(i).getStudentID();
if (studentIdTest == studentID) {
studentIndex = i;
break;
} else{
studentIndex = -1;
}
}
Suggestion: you can intialize studentIndex with -1 instead of setting it in each iteration where match not found.
I hope this will solve your problem.
In your idFinder method, you continue to search for the id even when you find it. In the for loop, you need to stop when you find the id.
Modify your for loop to:
public static int idFinder(ClassSection classOne) {
String intString = "a Student ID to search for:";
int studentIndex = -1; // Initialize the studentIndex to a negative value since 0 is a valid index
System.out.println("Please enter a Student ID to search for:");
int studentID = intChecker(intString);
for (int i = 0; i < classOne.students.size(); i++) {
int studentIdTest = classOne.students.get(i).getStudentID();
if (studentIdTest == studentID) {
studentIndex = i;
break;
}
}
return studentIndex;
}
I keep getting an error called "java.util.Mismatchexpection: null". I'm not sure how to fix this. It points to the grade = fileInput.nextInt(); line.
Here are the classes I'm using:
import java.util.Scanner;
import java.io.*;
public class Students
{
public static void printAllStudents(Student[] students){
for(int i=0;i<students.length;i++)
{
System.out.println(students[i]);
}
}
public static void printAllStudentsByFirstName(Student[] students,String firstName){
String name=firstName.split(" ")[1];
int len=name.length();
for (int i=0;i<students.length;i++){
try{
if(students[i].getFname().substring(0, len).equalsIgnoreCase(name)){
System.out.println(students[i]);
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}
public static void printAllStudentsByLastName(Student[] students,String lastName){
String name=lastName.split(" ")[1];
int len = name.length();
for(int i=0;i<students.length;i++){
try{
if(students[i].getLname().substring(0, len).equalsIgnoreCase(name)){
System.out.println(students[i]);
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}
public static void printAllStudentsByGrades(Student[] students,String interval){
int start=Integer.parseInt(interval.split(" ")[1]);
int end=Integer.parseInt(interval.split(" ")[2]);
for(int i=0;i<students.length;i++){
if(students[i].getGrade()>=start && students[i].getGrade()<=end){
System.out.println(students[i]);
}
}
}
public static void sort(Student[] students)
{
int n = students.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (students[i].getGrade() > students[k].getGrade())
{
Student temp=new Student();
temp = students[k];
students[k]=students[i];
students[i]=temp;
}
}
}
printAllStudents(students);
}
public static void main (String[] args) throws IOException
{
String first_name, last_name, line = "";
int grade, lines = 0, i;
char ch;
Scanner sc = new Scanner(System.in);
Scanner fileInput = new Scanner(new File("students.txt"));
//Counting the number of lines in the file.
while (fileInput.hasNext())
{
line = fileInput.next();
lines++;}
fileInput = new Scanner(new File("students.txt"));
//Declaring Student array of size lines.
Student[] students=new Student[lines];
i = 0;
while (fileInput.hasNext())
{
first_name = fileInput.nextLine();
last_name = fileInput.nextLine();
grade = fileInput.nextInt();
Student st = new Student(first_name, last_name, grade);
students[i++] = st;
}
System.out.println("Please choose from below operations: ");
System.out.println("1. printall");
System.out.println("2. firstname <name>");
System.out.println("3. lastname <name>");
System.out.println("4. interval m n");
System.out.println("5. sort");
System.out.println("6. end");
while (true)
{
System.out.println("Enter choice:");
String choice = sc.nextLine();
if(choice.equals("printall"))
printAllStudents(students);
else if(choice.indexOf("firstname")==0)
printAllStudentsByFirstName(students, choice);
else if(choice.indexOf("lastname") == 0)
printAllStudentsByLastName(students, choice);
else if(choice.indexOf("interval") == 0)
printAllStudentsByGrades(students, choice);
else if(choice.equals("sort"))
sort(students);
else if(choice.equals("end"))
break;
}
}
}
public class Student
{
private String fname, lname;
private int grade;
public Student()
{
super(); //gives us the ability to override
}
public Student (String fname, String lname, int grade)
{
this.fname = fname;
this.lname = lname;
this.grade = grade;
}
public String getFname() {
return fname;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String toString()
{
return fname + " " + lname + "\t" + grade;
}
}
Any help will be much appreciated.
A MismatchException is triggered when the Scanner runs into unexpected input. In your case, the Scanner is picking up null when it is expecting int input for fileInput.nextInt().
This has to do with the formatting of student.txt and how you're parsing it; try running the code in debug, step-by-step, in your IDE (if you're using one) to pinpoint how to fix your text-file parsing.
I am writing a Java program that I need:
A method to read the customer names and id and store them in an array. (Read a sequence of zero or more lines each containing the name and id of one customer. Instantiate one Customer object per line and store each object in an array of objects. The array need not be more than 10 elements long. The sequence of name and id will end with an empty line).
Main
import java.util.Scanner;
public class CustomerTest {
public static void main(String[] args) {
Customer[] customers = new Customer[10];
Scanner myScanner = new Scanner(System.in);
int numItem;
readCustomer(myScanner, customers); //not sure about this calling
readNameAmount(myScanner, customers); ////not sure about this calling
}
public static void readCustomer(Scanner myScanner, Customer[] input) {
boolean streamEnded = false;
int numItem = 0;
while (!streamEnded && myScanner.hasNext()) {
String name = myScanner.nextLine();
String id = myScanner.nextLine();
if (name.length() == 0 && id.length() == 0) {
streamEnded = true;
} else {
input[numItem] = name; //error
input[numItem] = id; //error
}
numItem++;
Customer customerTest = new Customer(name, id);
}
}
public static void readNameAmount(Scanner myScanner, Customer[] input) {
while (myScanner.hasNext()) {
String id = myScanner.nextLine();
double amount = myScanner.nextDouble();
int i = 0;
boolean found = false;
while (i <numItem && !found) { //error
if (customers[i].equals(id)) { //error
changeBalance(double value);//error
}
found = true;
i++;
}
}
}
public static void print(Customer[] input, int numItem) {
for (int i = 0; i < numItem; i++) {
System.out.println(customers[i].toString()); //error
}
}
}
Can you please check if this works.
I dont know whether I understood your question.And I just cleared the error.
public class CustomerTest {
static int numItem = 0;
public static void main(String[] args) {
Customer[] customers = new Customer[10];
Scanner myScanner = new Scanner(System.in);
readCustomer(myScanner, customers); //not sure about this calling
readNameAmount(myScanner, customers); ////not sure about this calling
}
public static void readCustomer(Scanner myScanner, Customer[] input) {
boolean streamEnded = false;
while (!streamEnded && myScanner.hasNext()) {
String name = myScanner.nextLine();
String id = myScanner.nextLine();
if (name.length() == 0 && id.length() == 0) {
streamEnded = true;
}
else {
input[numItem].getName();
input[numItem].getId(); //error
}
numItem++;
Customer customerTest = new Customer(name, id);
}
}
public static void readNameAmount(Scanner myScanner, Customer[] input) {
while (myScanner.hasNext()) {
String id = myScanner.nextLine();
Customer cust = new Customer();
double amount = myScanner.nextDouble();
int i = 0;
boolean found = false;
while (i < numItem && !found) { //error
if (input[i].equals(id)) { //error
cust.changeBalance(amount);//error
}
found = true;
i++;
}
}
}
public static void print(Customer[] input, int numItem) {
for (int i = 0; i < numItem; i++) {
System.out.println(input[i].toString()); //error
}
}
}
Let me know your thoughts.
Customer.java
public class Customer {
private String name;
private String id;
private double balance;
public Customer(){
}
public Customer(String name, String id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public void changeBalance(double value) {
balance = balance + value;
}
public String toString() {
return "name " + name + " id " + id + " balance " + balance;
}
}