My code is as follows:
import java.io.*;
import java.util.*;
public class readStudents extends Object
{
private String SName = "";
private String DoB = "";
private String Gender = "";
private String Address = "";
Student [] students = new Student[20];
public void fillStudentArray()
{
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try
{
Scanner in = new Scanner(file);
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String getName()
{
return this.SName;
}
public void printname()
{
System.out.println("hello");
}
public Student search(String name)
{
System.out.print("Enter the name you wish to search: ");
for (int i = 0; i < this.students.length; i++)
{
Student s = this.students[i];
if (s.getName().equalsIgnoreCase(name))
{
return s;
}
}
return null;
}
} //end class students
However I am trying to create a well refined program that I can call on these methods from another main file with as minimal code as possible in that file.
The search method at the bottom is tripping me up as I am assuming I need to put something to do with the array in my getName() method but I can't figure it out.
Since I am doing this as a class for another main method, with the placement of my array initialization and declaration it allows the other methods to access it but it leaves me with no way to create this array from the main method unless I am missing something?
This is the error jCreator is throwing:
F:\University\Ass2\readStudents.java:62: error: cannot find symbol
if (s.getName().equalsIgnoreCase(name))
^
symbol: method getName()
location: variable s of type Student
You never populated the Student students[] array... You retrieved the values you would populate them with here:
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
But you never actually set those values into a Student object in the students[] array
Do something like this:
int i = 0;
while(in.hasNextLine())
{
String name = in.next();
String dateOfBirth = in.next();
String gender = in.next();
String address = in.next();
students[i] = new Student(name, dateOfBirth, gender, address);
i++
}
Also, you might consider ditching the array and using some sort of List or Hash object... If your file contains more than 20 lines, the array will be out of index when you try to define the 21st value.. With an arraylist or a List you wouldn't have that problem
I took a liberty to tweak your code as previous answer mentioned, it's better to use array list in your case. You could make a small student container class within your reader. The get name method is also kinda redundant ;s
package test;
import java.io.*;
import java.util.*;
public class readStudents{
ArrayList<Student> students = new ArrayList<Student>();
class Student {
private String name;
private String dob;
private String gender;
private String address;
public Student(String name, String dob, String gender, String address) {
this.name = name;
this.dob = dob;
this.gender = gender;
this.address = address;
}
public void fillStudentArray() {
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try {
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
students.add(new Student(SName, DoB, Gender, Address));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String getName(Student student) {
return student.name;
}
public void printname() {
System.out.println("hello");
}
public Student search(String name) {
System.out.print("Enter the name you wish to search: ");
for (Student student : students) {
if (student.name.equalsIgnoreCase(name))
;
return student;
}
return null;
}
}
}
If you're not forced by your teacher to use for or for-each cycle in the search function - this is how to do a full scan the Java 8 way
public Optional<Student> findFirstByName(final String name) {
return Arrays.stream(students)
.filter(s -> s.getName().equalsIgnoreCase(name))
.findFirst();
}
Related
I am trying to create an array list that contains all employees and is able to handle any type of employee. I also have to load the data onto to the list The class I'm using is called payroll. This is what I have so far:
The employee class looks like this:
import java.util.*;
public abstract class Employee
{
private String name, employeeNum, department;
private char type;
public Employee()
{
name ="";
employeeNum = "";
department = "";
}
public Employee(String Name, String EmpNum, String Depart)
{
name = Name;
employeeNum = EmpNum;
department = Depart;
}
//public EMpoy
public String getName()
{
return name;
}
public String getEmployeeNum()
{
return employeeNum;
}
public String getDepartment()
{
return department;
}
public char getType()
{
return type;
}
public void setName(String Name)
{
name = Name;
}
public void setEmployeeNum(String EmpNum)
{
employeeNum = EmpNum;
}
public void setDepartment(String Depart)
{
department = Depart;
}
public String toString()
{
String str;
str = "Employee Name: " + name + "\n"
+ "Employee Number: " + employeeNum + "\n"
+ "Employee Department: " + department + "\n";
return str;
}
}
The payroll class looks like this so far:
import java.util.*;
import java.io.*;
public class Payroll
{
private ArrayList<Employee> list = new ArrayList<Employee>();
private String fileName;
public Payroll()
{
}
public void fileName(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("InsertFileName");
String fileName1 = kb.next();
fileName = fileName1 + ".txt";
}
public void loadData() throws FileNotFoundException
{
Scanner s = new Scanner(new File(fileName));
while (s.hasNext())
{
String name = s.next();
String employeeNum = s.next();
String department = s.next();
//String typeString = s.next();
//char type = typeString.toUpperCase().charAt(0);
char type = s.next().toUpperCase().charAt(0);
if (type == 'S')
{
double yearlySalary = s.nextDouble();
list.add(new Salary (name, employeeNum, department, yearlySalary));
}
else if (type == 'H')
{
double hourlyPayRate = s.nextDouble();
String hours = s.next();
int hoursWorked = Integer.parseInt(hours);
list.add(new Hourly (name, employeeNum, department, hourlyPayRate, hoursWorked));
}
else if (type == 'C')
{
int numOfWeeks = s.nextInt();
double baseWeeklySalary = s.nextDouble();
int salesThisWeek = s.nextInt();
int salesThisYear = s.nextInt();
double commissionRate = s.nextDouble();
list.add(new Commission (name, employeeNum, department, numOfWeeks, baseWeeklySalary, salesThisWeek, salesThisYear, commissionRate));
}
}
s.close();
}
Now I know I'm supposed to make the arraylist in the constructor, that's what I'm having trouble with. How can I make the list using polymorphism to get every employee? Thanks.
Hi Srk93 You are getting error as your list contains the references of Employee class and Employee class does't have getCommissionRate method. You can call on Employee reference which are declared in Employee class. Create abstact method of calculateSalary() and implement in all your child classes.
Its duplicate of "cannot find symbol: method" but the method is declared
I have a text file which contains a student number (9 digits), pin (4 digits), first name, last name. Which looks like this:
456864324,4965,Eves,Dalton
457642455,2164,Jagger,Michael
132435465, 3578,McIvar, Alan
543247531,2854,Jones, Alan
The student enters its student number and then pin. The program matches his input to the text file and checks if it matches or not.
So far I've separated the text line by line and stored it into an ArrayList and then thought about splitting it with ",". I've also thought about using Maps but cannot figure out how I will store the names with it as well.
String studentdb = sn_field.getText(); //get student number from input
String pindb = pin_field.getText(); //get pin from input
try {
File f = new File("file name");
Scanner sc = new Scanner(f);
ArrayList<String> number= new ArrayList<String>();
ArrayList<String> pswd = new ArrayList<String>();
while(sc.hasNextLine()){
String line = sc.nextLine();
// = line.split("\n");
String sn = line;
people.add(sn);
}
//if(people.contains(studentdb)){
//System.out.println("pass");}
} catch (FileNotFoundException f) {
System.out.print("file not found");
}
All in all if the student number and pin both are wrong, it should give an error, if both are correct and match, it passes. Any help would be appreciated as I'm just a beginner at Java.
I was able to process your file with the following example. Thanks for the problem as it provided a fun playground for some of the new features in Java 8 that I'm still getting familiar with . . .
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Scanner;
public class StudentInformationMatcher
{
private static final Path FILE_PATH = Paths.get("C:\\projects\\playground\\src\\main\\resources\\studentinfo.txt");
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your student number: ");
String studentNumber = scanner.next();
System.out.print("Please enter your pin: ");
String pin = scanner.next();
Optional<Person> matchingPersonRecord =
Files.lines(FILE_PATH)
.map(line -> line.split(","))
.map(csvValues -> new Person(csvValues))
.filter(person -> person.getStudentNumber().equals(studentNumber) && person.getPin().equals(pin))
.findFirst();
if (matchingPersonRecord.isPresent())
{
Person matchingPerson = matchingPersonRecord.get();
System.out.println("Hello " + matchingPerson.getFirstName() + " " + matchingPerson.getLastName());
}
else
{
System.out.println("No matching record found");
}
}
private static class Person
{
private final String studentNumber;
private final String pin;
private final String lastName;
private final String firstName;
private Person(String[] csvValues)
{
this.studentNumber = csvValues[0].trim();
this.pin = csvValues[1].trim();
this.lastName = csvValues[2].trim();
this.firstName = csvValues[3].trim();
}
private String getStudentNumber()
{
return studentNumber;
}
private String getPin()
{
return pin;
}
private String getLastName()
{
return lastName;
}
private String getFirstName()
{
return firstName;
}
}
}
Here an idea how you could achieve this:
Create a "student" class:
class student {
private String lastname;
private String firstname;
private String studentId;
private String pin;
// Getter and Setter methods
public static createNewStudent(String line) {
// split here the line and save the fields in the member variables
}
public boolean checkPinCode(String pin) {
return this.pin.equals(pin);
}
}
In your loop you can create student objects and add them to a Hashtable.
The key is the studentId and the value is the student object.
You can retrieve a student object from the hashtable with the entered key and check if the pin passes.
I am trying to solve an assignment in my Java class. I am stuck and need a little help.
I am trying to create a method in my Group class that will display the group name and the 4 students in the group. My code currently displays the group name and the memory location of my student inside my array.
public class Group {
/**-------Declaring attributes----*/
String groupName;
int newStudentCount;
/**----------------------------*/
/**--------Constructor------------*/
public Group(String givenGroupName) {
groupName = givenGroupName;
}
Student[] students = new Student[4];
/**----------------------------*/
/**--------Method------------*/
void addStudent(Student st) {
students[newStudentCount] = st;
++newStudentCount;
System.out.println("New student: " +st.getName());
}
public String getGroup() {
return "Group = " + groupName;
}
public Student getStudent(){
return students[0];
}
}
In my App class I have this:
public class App {
public static void main(String[] args) {
Group g1 = new Group("Pink Pony Princesses");
Student st1 = new Student("Joshua Mathews");
st1.getName();
g1.addStudent(st1);
Student st2 = new Student("Jame Brooks");
g1.addStudent(st2);
Student st3 = new Student("Mike Myers");
g1.addStudent(st3);
Student st4 = new Student("Christie Richie");
g1.addStudent(st4);
System.out.println(g1.getGroup()+ " " + g1.getStudent());
}
This is my Student class:
public class Student {
/**-------Declaring attributes----*/
String name;
String degree;
int age;
/**----------------------------*/
/**--------Constructor------------*/
Student(String givenName){
name = givenName;
}
Student(String givenName, String givenDegree, int givenAge) {
name = givenName;
degree = givenDegree;
age = givenAge;
}
/**--------- METHODS --------*/
//Array
public final String [] activities = {
"Working on Homework", "Playing a Game", "Taking a Nap"
};
String getInfo(){
return name + age + degree;
}
String getName() {
return name;
}
int getAge(){
return age;
}
String getDegree() {
return degree;
}
String whatsUp(){
Random rand = new Random();
int randomIndex = rand.nextInt(activities.length);
String returnActivity = activities[randomIndex];
return returnActivity;
}
I'm not sure how to call my array to display the 4 names, and not the memory location of them. Any help would be greatly appreciated.
I can deduce a couple of things from your question.
First, you are returning only the student at index 0 of the Student array held within your Group object. If you want to return all students your method signature should have a Student[] as the return type rather than a Student object.
If you follow the above prompt then you will have to iterate through the returned array printing each Student object.
Regardless of which implementation you choose the reason you print out a memory reference rather than a String object is that you have not overridden toString within your Student class.
Something like this will print out Student data when passed to a System.out call:
#Override
public String toString() {
return someStudentData;
}
You can go with what andrewdleach said by implementing toString(). OR
To print all student names your method should be something like:
public String getStudent(){
String studentNames = "";
for(Student stu: students){
studentNames+= stu.getName() + ",";
}
return studentNames;
}
I am new to java and doing some arraylist work, and when compiling my lists just return null values instead of names I have typed in.
I don't understand why this is so, so if anyone could advise/help me that would be great.
Here is my main code
import java.util.*;
public class StudentData
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
String yesNo = "true";
do
{
System.out.println("Enter student's name: ");
String name = in.next();
Student s = new Student();
studentList.add(s);
String input;
do
{
System.out.println("Would you like to enter data for another student? Yes/No ");
yesNo = in.next();
}
while (!yesNo.equalsIgnoreCase("YES") && !yesNo.equalsIgnoreCase("NO"));
}
while (yesNo.equalsIgnoreCase("YES"));
for(int i = 0; i < studentList.size(); i++)
{
System.out.println(studentList.get(i).getName());
}
}
}
And
class Student
{
private String studentName;
public StudentData(String name)
{
setName(name);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
}
You're creating a student but didn't set the name :
String name = in.next();
Student s = new Student();
studentList.add(s);
Try with :
String name = in.next();
Student s = new Student();
s.setName(name);
studentList.add(s);
Also replace your constructor. I.e :
public StudentData(String name){
setName(name);
}
should be
public Student(String name) {
setName(name);
}
Then you will be able to do Student s = new Student(name);
Basically I have a class that has methods which use String arrays and i'm writing a method in the application class to read a file and update an array of object of class Customer. I get errors like:
Line 83: set_address(java.lang.String[]) in Customer cannot be applied to (java.lang.String)
at the line review[i].set_address(st[1]). I understand that it is looking for a string[] and it is receiving a string but is there any way to fix this? Here's the code I'm working with.
import java.io.*;
import java.util.*;
class Customer {
int account_id;
char[] ch1 = new char[20];
String name = new String (ch1);
char[] ch2 = new char[80];
String address = new String (ch2);
char[] ch3 = new char[10];
String phone_number = new String (ch3);
char[] ch4 = new char[8];
String date_of_birth = new String (ch4);
double account_balance;
public int get_accountid(){
return account_id;
}
public String get_address(){
return address;
}
public String get_phone_number(){
return phone_number;
}
public String get_date_of_birth(){
return date_of_birth;
}
public double get_balance(){
return account_balance;
}
public void set_account_id(int num){
account_id = num;
}
public void set_address(String add){
address = add;
}
public void set_phone_number(String phone){
phone_number = phone;
}
public void set_date_of_birth(String dob){
date_of_birth = dob;
}
public void set_balance(double bal){
account_balance = bal;
}
Customer(){ // default constructor
}
// parametrized constructor
Customer(int id, String name, String add, String dob, String num, double bal){
this.account_id = id;
this.name = name;
this.address = add;
this.date_of_birth = dob;
this.phone_number = num;
this.account_balance = bal;
}
}
public class lab2{
public static void main(String args[]){
System.out.println("testing this shit");
}
public static void readFile(String filename){
Customer[] review = new Customer[30];
int i=0;
Scanner scan = new Scanner (new File (filename));
while (scan.hasNext()){
while(i<30){
review[i].set_account_id(scan.nextInt());
String[] st = scan.nextLine().split("=");
review[i].set_address(st[1]);
st = scan.nextLine().spilt("=");
review[i].set_phone_number(st[1]);
st = scan.nextLine().split("=");
review[i].set_date_of_birth(st[1]);
//st = scan.nextLine().split("=");
review[i].set_balance(scan.nextDouble());
scan.nextLine();
i=i+1;
}
}
}
}
Your class Customer looks like a Java bean. I find these declaration suspicious:
String[] name = new String [20];
String[] address = new String [80];
String[] phone_number = new String [10];
String[] date_of_birth = new String [8];
Why do you want a Customer to have 20 names, 80 addresses, 10 phone numbers, and 8 date of birth? I suspect that your intention is saying that a Customer name is at most 20 characters long, his/her address is at most 80 characters long, etc. If this is the case, than you don't want a String[], you may want a char[]!
However, think about making those fields simply String: it seems more natural. I don't see reason why you may want to limit their size.
Just change your method signature:
public void set_address(String add){
address = add;
}
Or other choice: You create a new String[] object based on your String object an pass this: