I'm having a number of issues with this:
1) Under which class would I want to put my Scanner, so that it assigns the proper variables? The task I am given says to "read data file into Students" in the Tester class
2) How can I make a readFile() method in the Students class?
3) How can I properly write toString() in both Student and Students classes?
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[]) throws IOException
{
//new Students object
Students theStudents = new Students();
//reads file from Students
theStudents.readFile();
// create new 'Output.txt' file to save program output
PrintWriter ot = new PrintWriter(new FileWriter("Output.txt"));
System.out.println(theStudents.toString());
ot.println(theStudents.toString());
ot.close();
}
}
import java.util.ArrayList;
import java.io.*;
import java.util.*;
import java.io.FileReader;
public class Students
{
// instance variables
private ArrayList<Student> students;
public Students()
{
//create arraylist for students
students = new ArrayList<>();
}
public void readFile() throws IOException
{
String name;
int age;
double gpa;
String line;
//Scanner to read file
try {
Scanner sc = new Scanner(new File("Students.txt"));
while (sc.hasNextLine()) {
name = sc.nextLine();
line = sc.nextLine();
age = Integer.parseInt(line);
line = sc.nextLine();
gpa = Double.parseDouble(line);
}
}
catch (FileNotFoundException e) {
System.out.println("Error");
}
}
public void add(Student s)
{
students.add(s);
}
public Students aboveAverage(double avgGPA)
{
Students aboveAverage = new Students();
for (int i = 0; i < students.size(); ++i) {
if (students.get(i).getGPA() > avgGPA)
aboveAverage.add(students.get(i));
}
return aboveAverage;
}
public String toString()
{
String out = "";
int count = 0;
for (Student student : students){
out += students.toString() + " ";
++count;
}
return out;
}
}
public class Student
{
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGPA)
{
name = studentName;
age = studentAge;
gpa = studentGPA;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getGPA()
{
return gpa;
}
public String toString()
{
return String.format("%10s", name) +
String.format("%5d", age) + String.format("%10.2f \n", gpa);
}
}
I'm not gonna give you the complete solution but here is a way to approach this problem.
You need readLine() instead of nextLine()
Once you read the values, you need to call the add() function with the Student Object to add it to your ArrayList.
Code Snippet:
try (Scanner sc = new Scanner(new File("Students.txt"))) {
while (sc.hasNextLine()) {
String name = sc.readLine();
int age = Integer.parseInt(sc.readLine());
double gpa = Double.parseDouble(sc.readLine());
/* Create A New Student Object & Add To List */
add(new Student(name, age, gpa));
}
} catch (FileNotFoundException e) {
System.out.println("Error");
}
Also, you need to #Override the toString() function.
Related
I am new in java and I trying to get information
for five students and save them into an array of classes. how can I do this?
I want to use class person for five students whit different informations
import java.io.IOException;
import java.util.*;
public class exam
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// I want to get and save information in this array
person[] f = new student[5];
}
}
class person defined for get name and family name.
import java.util.*;
public abstract class person {
Scanner scr = new Scanner(System.in);
private String name , fname;
public void SetName() {
System.out.println("enter name and familyNAme :");
name = scr.next();
}
public String getname() {
return name;
}
public void setfname () {
System.out.println("enter familyname:");
fname = scr.next();
}
public String getfname() {
return fname;
}
}
class student that inherits from the class person for get studentID and student Scores .
import java.util.*;
class student extends person {
float[] p = new float[5];
int id , sum ;
float min;
public void inputs() {
System.out.println("enter the id :");
id = scr.nextInt();
}
public void sumation() {
System.out.println("enter points of student:");
sum= 0;
for(int i = 0 ; i<5 ; i++){
p[i]=scr.nextFloat();
sum+=p[i];
}
}
public void miangin() {
min = (float)sum/4;
}
}
So first things first, when creating Java objects, refrain from getting input inside the object so that if you decide to change the way you get input (e.g. transition from command line to GUI) you don't need to modify the Java object.
Second, getters and setters should only get or set. This would save some confusion when debugging since we don't have to check these methods/functions.
So here's the person object:
public abstract class Person {
protected String name, fname;
public Person (String name, String fname) {
this.name = name;
this.fname = fname;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return name;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getFname () {
return fname;
}
}
And here's the student object (tip: you can make as much constructors as you want to make object creation easier for you):
public class Student extends Person {
private float[] p;
private int id;
public Student (String name, String fname) {
this (name, fname, -1, null);
}
public Student (String name, String fname, int id, float[] p) {
super (name, fname);
this.id = id;
this.p = p;
}
public void setP (float[] p) {
this.p = p;
}
public float[] getP () {
return p;
}
public void setId (int id) {
this.id = id;
}
public int getId () {
return id;
}
public float summation () {
float sum = 0;
for (int i = 0; i < p.length; i++)
sum += p[i];
return sum;
}
public float miangin () {
return summation () / 4.0f;
}
#Override
public String toString () {
return new StringBuilder ()
.append ("Name: ").append (name)
.append (" Family name: ").append (fname)
.append (" Id: ").append (id)
.append (" min: ").append (miangin ())
.toString ();
}
}
And lastly, wherever your main method is, that is where you should get input from. Take note that when you make an array, each index is initialized to null so you still need to instantiate each array index before using. I made a sample below but you can modify it depending on what you need.
import java.util.*;
public class Exam {
Scanner sc;
Person[] people;
Exam () {
sc = new Scanner (System.in);
people = new Person[5];
}
public void getInput () {
for (int i = 0; i < people.length; i++) {
System.out.print ("Enter name: ");
String name = sc.nextLine ();
System.out.print ("Enter family name: ");
String fname = sc.nextLine ();
System.out.print ("Enter id: ");
int id = sc.nextInt (); sc.nextLine ();
System.out.println ("Enter points: ");
float[] points = new float[5];
for (int j = 0; j < points.length; j++) {
System.out.printf ("[%d] ", j + 1);
points[j] = sc.nextFloat (); sc.nextLine ();
}
people[i] = new Student (name, fname, id, points);
}
}
public void printInput () {
for (Person p: people)
System.out.println (p);
}
public void run () {
getInput ();
printInput ();
}
public static void main (String[] args) {
new Exam ().run ();
}
}
Just one last tip, if you ever need dynamic arrays in Java, check out ArrayList.
You can add a class attribute, and then add class information for each student, or you can add a class class, define an array of students in the class class, and add an add student attribute, and you can add students to that class.
First of all, please write class names with capital letter (Student, Exam <...>).
Exam class:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[]{
new Student(),
new Student(),
new Student(),
new Student(),
new Student()
};
for (int i = 0; i < 5; i++) {
students[i].setFirstName();
students[i].setLastName();
students[i].setId();
}
}
}
Person class:
import java.util.Scanner;
public class Person {
String firstName, lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName() {
System.out.println("Type firstName: ");
this.firstName = new Scanner(System.in).next();
}
public String getLastName() {
return lastName;
}
public void setLastName() {
System.out.println("Type lastName: ");
this.lastName = new Scanner(System.in).next();
}
}
Student class:
import java.util.Scanner;
public class Student extends Person{
int id;
public int getId() {
return id;
}
public void setId() {
//Converting String line into Integer by Integer.parseInt(String s)
System.out.println("Type id: ");
this.id = Integer.parseInt(new Scanner(System.in).next());
}
}
This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I am trying to add these data I have read from a file into my map. My map is a treemap TreeMap<String, Student>, where Student in another class. I am trying to use the code map.put(formatSNumber, student.setCourses(courses)); to add the read file elements to my map, but I keep encountering that void type not allowed here error.
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
hours = Integer.parseInt(Breader.readLine());
grade = Double.parseDouble(Breader.readLine());
Student student = map.get(formatSNumber);
Course course = new Course(hours, grade);
List<Course> courses = student.getCourses();
courses.add(course);
map.put(formatSNumber, student.setCourses(courses));
end = Breader.ready();
Here is my full code:
import java.io.*;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.List;
public class FinalProgram {
public static void main(String[] args) throws IOException {
String nameFile = " ";
String classFile = " ";
TreeMap<String, Student> map = new TreeMap<>();
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter the Name file(c:filename.txt): ");
nameFile = input.nextLine();
} catch(IllegalArgumentException e) {
System.out.printf("Invalid input. Please enter"
+ " filename in the form of "
+ "c:filename.txt\n", e.getMessage());
}
nameReader(nameFile, map);
try {
System.out.print("Enter the Class file(c:filename.txt): ");
classFile = input.nextLine();
} catch(IllegalArgumentException e) {
System.out.printf("Invalid input. Please enter"
+ " filename in the form of "
+ "c:filename.txt\n", e.getMessage());
}
classReader(classFile, map);
}
private static void nameReader(String file, TreeMap<String, Student> map)
throws IOException {
String nameFile = file;
int sNumber = 0;
String formatSNumber = " ";
String sName = " ";
//Instantiate FileReader and BufferedReader
FileReader freader = new FileReader(nameFile);
BufferedReader Breader = new BufferedReader(freader);
boolean end = Breader.ready();
do {
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
sName = Breader.readLine();
Student student = new Student(sName);
map.put(formatSNumber, student);
end = Breader.ready();
} while(end);
Iterator<String> keySetIterator = map.keySet().iterator();
while(keySetIterator.hasNext()) {
String key = keySetIterator.next();
System.out.println("key: " + key + " value: " + map.get(key).getName());
}
}
private static void classReader(String file, TreeMap<String, Student> map)
throws IOException {
String classFile = file;
int sNumber = 0;
String formatSNumber = " ";
int hours = 0;
double grade = 0.0;
double points = grade * hours;
double GPA = points / hours;
//Instantiate FileReader and BufferedReader
FileReader freader = new FileReader(classFile);
BufferedReader Breader = new BufferedReader(freader);
boolean end = Breader.ready();
do {
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
hours = Integer.parseInt(Breader.readLine());
grade = Double.parseDouble(Breader.readLine());
Student student = map.get(formatSNumber);
Course course = new Course(hours, grade);
List<Course> courses = student.getCourses();
courses.add(course);
map.put(formatSNumber, student.setCourses(courses));
end = Breader.ready();
} while(end);
points = grade * hours;
GPA = points / hours;
}
}
Student class:
import java.util.ArrayList;
import java.util.List;
public class Student {
private String name = " ";
private List<Course> courses = new ArrayList<>();
public Student(String name) {
this.name = name;
}
public Student(String name, List courses) {
this.name = name;
this.courses = courses;
}
public List getCourses() {
return courses;
}
public void setCourses(List courses) {
this.courses = courses;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Course class:
public class Course {
private int hours = 0;
private double grade = 0.0;
public Course(int hours, double grade) {
this.hours = hours;
this.grade = grade;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getHours() {
return hours;
}
public void setGrade(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
}
The second argument in map.put(formatSNumber, student.setCourses(courses)) must be of type Student. student.setCourses(courses) is a setter method with return type void, i.e. no return. This does not match.
You must have something like map.put("someString", new Student("name")) for instance, or map.put("someString", student) where student is of type Student.
The idea of put is about putting something into that Map.
More precisely, you typically provide (non-null) key and a value objects.
You are using student.setCourses(courses) as argument for that "value" parameter that put() expects.
That argument is an expression. And the result of that expression would be the result of the method call.
That method is defined to not return anything (void that is).
Obviously nothing is not the same as something. And that is what the compiler tries to tell you.
Two solutions:
pass a Student object
change that method setCourses()
Like this:
Student setCourses(... {
....
return this;
}
( you better go for option 1; 2 is more of a dirty hack, bad practice in essence )
I am a computer science student and am currently learning about recursion. I am doing my project on recursion and writing to an output text file, due later this week. It is a class of Students (CS152) and it must print all the students, the best student, and the amount of honors students in the class.
Student Class:
public class Student
{
String lastName, firstName, id;
double gpa;
int year;
public Student(String lastName, String firstName, String id, double gpa, int year)
{
this.lastName = lastName;
this.firstName = firstName;
this.id = id;
this.gpa = gpa;
this.year = year;
}
public String toString()
{
String result = "NAME: " + lastName + ", " + firstName + "\n";
result += "ID: " + id + "\n";
result += "GPA: " + gpa + "\n";
result += "YEAR: " + year + "\n";
return result;
}
public boolean isHonors()
{
if (this.gpa > 3.5)
return true;
else
return false;
}
public boolean isBetter(Student s)
{
if(this.gpa > s.getGPA())
return true;
else
return false;
}
public double getGPA()
{
return gpa;
}
}
CS152 Class:
import java.util.*;
import java.io.*;
public class CS152
{
public static final int MAXSIZE = 22;
private static int size = 0;
public CS152() throws IOException
{
Scanner fileScan;
String firstName, lastName, id;
double gpa;
int year;
fileScan = new Scanner(new File("input.txt"));
createList(fileScan);
}
public static Student[] createList(Scanner scan)
{
Student[] list = new Student[MAXSIZE];
return populateList(list, scan);
}
private static Student[] populateList(Student[] list, Scanner scan)
{
Student s;
if (size < MAXSIZE && scan.hasNext())
{
s = new Student(scan.next(), scan.next(), scan.next(), scan.nextDouble(), scan.nextInt());
list[size] = s;
size++;
return populateList(list, scan);
}
else
return list;
}
public static int getSize()
{
return size;
}
public static String toString(Student[] list, int n)
{
String str = "";
if(n == 1)
{
str += list[0].toString();
}
else
{
str += list[n-1].toString();
toString(list,n-1);
}
return str;
}
public static Student findBestStudent(Student[] list, int n)
{
if(n==1)
return list[0];
else
{
Student temp = findBestStudent(list, n-1);
if(temp.isBetter(list[n-1]))
return temp;
else
return list[n-1];
}
}
public static int countHonors(Student[] list, int n)
{
if(n==0)
return 0;
else
{
if(list[n-1].isHonors())
return countHonors(list, n-1) + 1;
else
return countHonors(list, n-1);
}
}
}
TestRecursion Class:
import java.util.*;
import java.io.*;
public class TestRecursion
{
public static void main(String[] args) throws IOException
{
CS152 cs152 = new CS152();
Scanner fileScan = new Scanner(new File("input.txt"));
cs152.createList(fileScan);
String file = "output.txt";
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for(int line=1; line <= cs152.getSize(); line++)
{
for(int num=1; num <= cs152.getSize(); num++)
{
outFile.print(cs152);
}
}
outFile.close();
System.out.println("Output file has been created: " + file);
}
}
Input File:
Zombie Rob 0001 3.5 2013
Smith John 0002 3.2 2012
Jane Mary 0003 3.8 2014
Thekid Billy 0004 2.9 1850
Earp Wyatt 0005 1.5 1862
Holiday Doc 0006 1.4 1863
Cool Annie 0007 4.0 2013
Presley Elvis 0008 3.1 2011
My expected output for each Student is:
NAME: Zombie Rob
ID: 0001
GPA: 3.5
YEAR: 2013
Best Student: (Whoever the best student is)
Amount of Honors Students: (amount of students)
My output file just comes out like:
CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12CS152#5abc3c12
I know I have to add more to print out the best student and the amount of honors students, but but right now I just can't seem to figure out if there's a problem with my toString method in my CS152 class, or how I'm getting the information from the file, or how I'm writing to the file, or if its something else. I am completely lost. Any help will be appreciated!
Your code is confusing.
Here's how I refactored it. My version writes this text to output.txt:
[Student{lastName='Zombie', firstName='Rob', id='0001', gpa=3.5, year=2013}, Student{lastName='Smith', firstName='John', id='0002', gpa=3.2, year=2012}, Student{lastName='Jane', firstName='Mary', id='0003', gpa=3.8, year=2014}, Student{lastName='Thekid', firstName='Billy', id='0004', gpa=2.9, year=1850}, Student{lastName='Earp', firstName='Wyatt', id='0005', gpa=1.5, year=1862}, Student{lastName='Holiday', firstName='Doc', id='0006', gpa=1.4, year=1863}, Student{lastName='Cool', firstName='Annie', id='0007', gpa=4.0, year=2013}, Student{lastName='Presley', firstName='Elvis', id='0008', gpa=3.1, year=2011}]
Best Student: Optional[Student{lastName='Cool', firstName='Annie', id='0007', gpa=4.0, year=2013}]
# of honors students: 2
Your recursive methods are not correct. They don't read the input file, determine best student, or count honors students correctly at all.
I refactored the code using Java 8. It's probably too much if you're a beginner, but it works and provides an example of how to do it differently.
Student:
/**
* Student class
* Created by Michael
* Creation date 4/5/2016.
* #link https://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
*/
public class Student {
private String lastName;
private String firstName;
private String id;
private double gpa;
private int year;
public Student(String lastName, String firstName, String id, double gpa, int year) {
this.lastName = lastName;
this.firstName = firstName;
this.id = id;
this.gpa = gpa;
this.year = year;
}
public boolean isHonors() {
return this.gpa > 3.5;
}
public double getGpa() {
return gpa;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("Student{");
sb.append("lastName='").append(lastName).append('\'');
sb.append(", firstName='").append(firstName).append('\'');
sb.append(", id='").append(id).append('\'');
sb.append(", gpa=").append(gpa);
sb.append(", year=").append(year);
sb.append('}');
return sb.toString();
}
}
StudentFactory:
/**
* StudentFactory
* Created by Michael
* Creation date 4/5/2016.
* #link https://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
*/
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
public class StudentFactory {
public List<Student> getStudentList(Scanner scanner) {
List<Student> studentList = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (StudentFactory.isNotBlank(line)) {
String [] tokens = line.split("\\s+");
studentList.add(new Student(tokens[0], tokens[1], tokens[2], Double.parseDouble(tokens[3]), Integer.parseInt(tokens[4])));
}
}
return studentList;
}
public Optional<Student> getBestStudent(List<Student> studentList) {
return studentList.stream().max(Comparator.comparing(Student::getGpa));
}
public long countHonors(List<Student> studentList) {
return studentList.stream().filter(Student::isHonors).count();
}
public static boolean isNotBlank(String s) {
return (s != null) && !"".equals(s.trim());
}
}
It's never too early to learn about JUnit:
/**
* JUnit test for StudentFactory
* Created by Michael
* Creation date 4/5/2016.
* #link https://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
*/
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;
public class StudentFactoryTest {
private StudentFactory studentFactory = new StudentFactory();
private List<Student> studentList;
#Before
public void setUp() throws FileNotFoundException {
Scanner fileScan = new Scanner(new File("./src/test/resources/input.txt"));
this.studentFactory = new StudentFactory();
this.studentList = studentFactory.getStudentList(fileScan);
}
#Test
public void testGetStudentList() throws FileNotFoundException {
Assert.assertEquals(8, studentList.size());
}
#Test
public void testGetBestStudent() {
String expected = "Optional[Student{lastName='Cool', firstName='Annie', id='0007', gpa=4.0, year=2013}]";
Assert.assertEquals(expected, this.studentFactory.getBestStudent(this.studentList).toString());
}
#Test
public void testCountHonors() {
Assert.assertEquals(2L, this.studentFactory.countHonors(this.studentList));
}
public void printOutput(String outputFileName) {
try (PrintWriter pw = new PrintWriter(new FileWriter(outputFileName))) {
pw.println(this.studentList);
pw.println("best student: " + studentFactory.getBestStudent(studentList));
pw.println("# of honors students: " + studentFactory.countHonors(studentList));
} catch (IOException e) {
e.printStackTrace();
}
}
}
You're assigning the memory address to the file, that's what the #5abc3c12 is. use:
toString()
method when writing non-primitives to file if you want text. If you want the formatting in your output, make use of the
\n
and ensure you aren't crashing on spaces and such. Remember about adding delimiters to be able to fetch data from file. If you want to store full objects, look into serialisation
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);
Im creating a program that is supposed have the user enter a student name and see if it exist in the student array using a linear search method. The student array is in a different class and im having trouble creating a constructor i have tried many things and its not working can someone point me in the right direction.
My linear search class is
import java.util.*;
import java.util.Scanner;
public class LinearSearch {
public int find(Student [] a, String nm) {
for (int i = 0; i < a.length; i++) {
if (a[i].equals(nm)){
return i;
break;
}
else{
return -1;
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student [] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}
My Student class is
import java.util.*;
public class Student {
public Student(){
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
}
You defined a constructor with no argument:
public Student() {
}
But you're invoking a constructor which needs a String as argument:
studentArray[0] = new Student("Mel");
So, your constructor should have a String as argument:
public Student(String name)
And you should probably store this name as a field in the Student class:
private String name;
public Student(String name) {
this.name = name;
}
Note that there is no way that a Student instance could be equal to a String instance. You should provide a getter method for the name, and compare the entered String with the name of the student, instead of comparing it with the student itself.
import java.util.*;
public class Student {
private String name;
public Student(String name){
this.name = name;
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
public String getName(){
return name;
}
}
and of course in the compersion you'll need to do:
f (a[i].getName().equals(nm)){
public class Student {
private String studentName;
private Student[] studentArray;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Student[] getStudentArray() {
return studentArray;
}
public void setStudentArray(Student[] studentArray) {
this.studentArray = studentArray;
}
public Student(){
studentArray = new Student[3];
}
public Student[] getArray() {
Student st1 = new Student();
st1.setStudentName("mel");
Student st2 = new Student();
st2.setStudentName("Jared");
Student st3 = new Student();
st3.setStudentName("Mikey");
studentArray[0]=st1;
studentArray[1]=st2;
studentArray[2]=st3;
return studentArray;
}
}
the above code is your Student class. there is no need to create a constructor though. but because you would like it i put it in the code.
the LinearSearch class is as follow:
public class LinearSearch {
private int i;
public int find(Student[] a, String nm) {
for ( i = 0; i < a.length; i++) {
if (a[i].getStudentName().equals(nm)) {
break;
} else {
i = -1;
}
}
return i;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student[] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}