Implementing classes and objects in java, calling a method - java

I'm having trouble with calling a method. The basis of the program is to read in data from data.txt, grab the name token given, then all of the grades that follow, then implement some operations on the grades to give details of the person's grades. I do all of the methods in a separate file named Grades.java, which has the Grades class. I'm just having trouble because I MUST have the testGrades method in my code (which I don't find necessary). I have done everything I need to do for the results to be perfect in a different program without having two different .java files. But it's necessary to do it this way. I think I have mostly everything pinned down, I'm just confused on how to implement and call the testGrades method. I commented it out and have the question on where it is in the program. Quite new to classes and objects, and java in general. Sorry for the lame question.
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
//testGrades(sgrades); How would I implement this method call?
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
}
}
This is a little snippet of the beginning of the Grades.java file
public class Grades {
private String studentName; // name of student Grades represents
private int[] grades; // array of student grades
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
}
public String getName() {
return studentName;
} // end method getName
public int length() {
return grades.length;
}

well your test grades take a Grades object so you need to construct a Grades object using your data and pass it to your test grades method
i.e.
Grades myGrade = new Grades(studentName,sgrades);
testGrades(myGrade);

It looks like what you need to do is have some type of local variable in your main method, that would hold your custom Grade type. So you need add a line like..
Grades myGrades = new Grades(studentName, sgrades);
Then you can call your testGrades method with a line like...
testGrades(myGrades);
Looks like you may also need a toString method in your Grades class.
Seems like homework, so I tried to leave a bit to for you to figure out :)

Related

JAVA: Having trouble printing Array [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
I have an assignment where I have to have a class named Employee with two variables and a class called Salary that inherits those variables and declares new ones. Within the Salary class, I have to create a method that will take user input for the different variables. The first number inputted is the number of employees you are giving information for and tells the loop how many times to go around. After typing in the information for all the employees the information must be presented like this
123 John engineer 40000.0
124 Emma Testing 33000.0
The only other thing that is required in the program is a function that will check the salary variable and if it is under 20000, not display the employee information to the console.
I have the user input working but I can't seem to get the array to display properly. Whatever I try I either get gibberish or null. I have tried putting the array and the array printing function in the display method and the main method and it doesn't make a difference. How can I fix this?
Side note: I know having different scanners for each input is not the best way of doing things it's just temporary. I'm trying to get the program to work before cleaning it up. The reasoning for it is a type mismatch error using one scanner as a result of scanning an int, then two strings, then a double.
This is the code I have right now:
import java.util.Scanner;
class Employee {
int employee_id;
String employee_name;
Employee(int employee_id, String employee_name) {
}
Employee() {
}
}
class Salary extends Employee {
double monthly_salary;
String designation;
int num_of_employees;
int n = 0;
Salary(int employee_id, String employee_name, String designation, double monthly_salary) {
super(employee_id, employee_name);
}
Salary() {
}
void display() {
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
Scanner a = new Scanner(System.in);
Scanner e = new Scanner(System.in);
Scanner t = new Scanner(System.in);
num_of_employees = s.nextInt();
for (;n<num_of_employees;) {
employee_id = c.nextInt();
employee_name = a.nextLine();
designation = e.nextLine();
monthly_salary = t.nextDouble();
n++;
}
s.close();
c.close();
a.close();
e.close();
t.close();
}
}
public class Solution2 {
public static void main(String[] args) {
Salary sal = new Salary();
Salary salary[] = new Salary[10];
sal.display();
salary[sal.n] = new Salary(sal.employee_id, sal.employee_name, sal.designation,
sal.monthly_salary);
if (sal.monthly_salary >= 20000) {
System.out.println(salary[sal.n]);
}
else {
System.out.println("");
}
}
}
The result from the array with this code is
Salary#7b23ec81

Print file contents in decreasing order java

I need to write a Java program where I can read data from a file which has students names and grades. I must find the max grade for each student and then write his name and max grade in a new file. I have been able to do this. The thing is, students should be printed in decreasing order based on their max grade and I can't find out how to do that. Can you help me please? Thank you!
public class NotaMax {
public static void main(String args[]) throws FileNotFoundException{
Scanner input=new Scanner(new File("teksti.txt"));
PrintStream output=new PrintStream(new File("max.txt"));
while(input.hasNextLine()) {
String rreshti=input.nextLine();
max(rreshti,output);
}
}
public static void max(String text,PrintStream output) {
Scanner data=new Scanner(text);
String emri=data.next();
double max=0;
while(data.hasNext()) {
double nota=data.nextDouble();
if(nota>max) {
max=nota;
}
}
output.println(""+emri+":"+max);
}
}
There are two approaches for this, one filling up the other.
You can save them in an ArrayList and then call the method Array#reverse so it will reverse the ArrayList. To add another layer of certainty, it's better to make an Object/Class named Student and apply a Comparator to the #sort method of the ArrayList in order to assure the outcome.
This however takes a lot more steps than the easiest and most efficient way of tackling this problem.
What the best you could do is save the Student Object inside an ArrayList (or HashSet, really any Comparable Collection/Map) and use the #sort method to sort it from the down to the top.
I could (if requested), provide some code for this.
First thing that comes to my mind is creating a separate class for your students and implementing a simple binary heap as a maximum heap with max grade of each student as a sorting criteria. Then just printing it. Shouldn't be to hard.
This should solve your problem. First of all read students and grades in teksti.txt in an Map and then find max grade for each student.
public class NotaMax {
private static Map<String, ArrayList<Integer>> students = new HashMap<>();
private static void readTeksti() throws FileNotFoundException {
Scanner input = new Scanner(new File("teksti.txt"));
// read teksti.txt
String[] line;
while (input.hasNextLine()) {
String rreshti = input.nextLine();
line = rreshti.split(" ");
ArrayList<Integer> grades = students.get(line[0]);
if (grades == null) {
grades = new ArrayList<>();
grades.add(Integer.parseInt(line[1]));
students.put(line[0], grades);
} else {
grades.add(Integer.parseInt(line[1]));
}
}
}
public static void main(String args[]) throws FileNotFoundException {
readTeksti();
max();
}
private static void max() throws FileNotFoundException {
PrintStream output = new PrintStream(new File("max.txt"));
List<Map.Entry<String,Integer>> maximums = new LinkedList<>();
for (String current : students.keySet()) {
ArrayList<Integer> grades = students.get(current);
Integer max = Collections.max(grades);
maximums.add(new AbstractMap.SimpleEntry<>(current, max));
}
Collections.reverse(maximums);
for (Map.Entry<String,Integer> current : maximums) {
output.println("" + current.getKey() + ":" + current.getValue());
}
}
}
I assumed that teksti.txt is like :
saman 100
samad 80
samsam 70
samsam 90
saman 90

Finding specific instance of class? [duplicate]

This question already has answers here:
How to find an object in an ArrayList by property
(8 answers)
Closed 5 years ago.
I've just started learning java and I'm trying to create an application to register students.
Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.
public class RegStudent {
ArrayList<Student> studentList = new ArrayList<>();
Scanner input = new Scanner(System.in);
public void reggaStudent(int start) {
while (start != 0) {
String programNamn, studNamn;
int totalPoint, antalKurser;
System.out.println("Vad heter programmet?");
programNamn = input.nextLine();
System.out.println("Vad heter studenten");
studNamn = input.nextLine();
System.out.println("Hur många poäng har studenten?");
totalPoint = input.nextInt();
System.out.println("Hur många kurser är studenten registrerad på?");
antalKurser = input.nextInt();
// Add student to list of students
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
System.out.println("Vill du registrera in en fler studenter? "
+ "Skriv 1 för ja och 0 för nej");
start = input.nextInt();
input.nextLine();
} // End of whileloop
}
}
The class is:
public class Student {
private int totalPoint;
private int antalKurser;
private String programNamn;
private String studNamn;
private static int counter;
public Student(int totalPoint, int antalKurser, String program, String studNamn) {
this.totalPoint = totalPoint;
this.antalKurser = antalKurser;
this.programNamn = program;
this.studNamn = studNamn;
counter++;
}
public int getTotalPoint() {
return totalPoint;
}
public void setTotalPoint(int totalPoint) {
this.totalPoint = totalPoint;
}
public int getAntalKurser() {
return antalKurser;
}
public void setAntalKurser(int antalKurser) {
this.antalKurser = antalKurser;
}
public String getProgramNamn() {
return programNamn;
}
public void setProgramNamn(String programNamn) {
this.programNamn = programNamn;
}
public String getStudNamn() {
return studNamn;
}
public void setStudNamn(String studNamn) {
this.studNamn = studNamn;
}
public static int getCount(){
return counter;
}
#Override
public String toString() {
return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
+ "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
}
}
How do I go about to get and set the instance variables in specific instance? I.e find the instances.
I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.
I've added a counter just to see I actually created some instances of the class.
You simply query objects for certain properties, like:
for (Student student : studentList) {
if (student.getProgramName().equals("whatever")) {
some match, now you know that this is the student you are looking for
In other words: when you have objects within some collection, and you want to acquire one/more objects with certain properties ... then you iterate the collection and test each entry against your search criteria.
Alternatively, you could "externalize" a property, and start putting objects into maps for example.
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
You now have your Student objects in a list. I assume you have something like
List<Student> studentList = new ArrayList<>();
somewhere in your code. After you populate the list with Student objects, you can use it to find instances. You need to decide what criteria to use for a search. Do you want to find a student with a specific name? Do you want to find all students in a given program? Do you want to find students with more than a certain number of points?
Maybe you want to do each of these. Start by picking one and then get a piece of paper to write out some ideas of how you would do the search. For example, say you want to find a student with the name "Bill". Imagine that you were given a stack of cards with information about students. This stack of cards represents the list in your program. How would you search this stack of cards for the card with Bill's name on it? Describe the steps you need to take in words. Don't worry about how you will code this yet. The first step in writing a computer program is breaking the solution down into small steps. After you have a clear idea how you might do this by hand in the physical world, you can translate your description into Java code.

Printing an array after user input

I'm working on a class that will take user input to assign values to an object created in a source class. Those objects will then be added to an array, which then prints the values on it. However, the "list" under print : list is telling me that I need to initialize the variable. Why is it not recognizing that this is an array even though it seems to work fine in my do loop?
import java.util.Scanner;
import name.Names;
public class NameTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
String entry;
Scanner firstscan = new Scanner(System.in);
Scanner lastscan = new Scanner(System.in);
Scanner codescan = new Scanner(System.in);
Scanner entryscan = new Scanner(System.in);
String first;
String last;
int code;
System.out
.println("This program will prompt you to input first name, +"
+ "last name, and zip code for an individual. Hit \"x\" when finished\n");
do {
System.out.println("Enter first name:");
first = firstscan.nextLine();
System.out.println("Enter last name:");
last = lastscan.nextLine();
System.out.println("Enter zip code:");
code = codescan.nextInt();
Names nm = new Names(first, last, code);
Names[] list = new Names[25];
int count = 0;
list[count] = nm;
count++;
System.out
.println("To quit hit \"X\" or any other key followed by enter to continue:");
entry = entryscan.nextLine();
} while (!(entry.equalsIgnoreCase("x")));
for (Names print : list)
System.out.println(print + "");
}
}
For one, you are instantiating your array inside your loop, that means every time your loop runs through, it creates a new array instead of updating the old one. Then, once you leave your loop, you leave its "scope". That means everything you declare inside the loop is not available outside. The solution is to declare your array outside the loop.
Every block in java has its own scope (defined through brackets). While you can access variables that have been declared outside your block while inside it, it does not work the other way around; as you can see. Just google java scope, and you will understand more. Hope that helps ;)
You will need a method in the class Name that return the first, last name and the zip code because if you just use:
System.out.println(print + "")
You are printing the object Name and no the String that represents the attributes saved in the object.
For example you can have the method in the class Name:
String getFirst()
{
return this.first;
}
And the last line in your class Nametester can be
System.out.println(print.getFirst() + "");

Insert Object into Java Array

I got from my teacher the next assignment -
I need to build a Course class and Student class
and to insert every Student into the Course class
Each Student has an Id,name and grade.
I have tried the next code:
public class Course {
Student[] android = new Student[100];
private void addStudent(Student a) {
for (int i=0;i<android.length;i++) {
if (android[i] == null) {
android[i] = a;
break;
}
}
}
public static void main(String[] args) {
addStudent(Joe);
}
}
I need to insert a Student that i have created in the Students class to the first null position in the array.
When i try addStudent(Joe); it gives me an error : "Joe cannot be resolved to a variable"
The Student class code:
public class Student {
private float grade;
private String name;
private long id;
public Student(long c,String b,float a) {
grade = a;
name = b;
id = c;
}
public static void main(String[] args) {
Student Joe = new Student(1,"Joe",40);
}
**The array holds 100 students (null at start)
When adding a student - i need to check for the first null value in the array and put it
there
When printing the students: i need to print only the non-null Objects in the array**
This code
Array[] Android = new Array[100];
is creating an array of type Array, so you can only store Array objects in it.
If you want to store Students, you need to create an array that, instead:
Student[] android = new Student[100];
Also, you need to realize that arrays in Java are indexed from 0. That is, you cannot reference a position that is the same as the size of the array. In your case, you have made
an array with 100 elements, but your for-loop is trying to put 101 objects in it.
Furthermore, your question text implies you only want to insert the new Student object once, but your loop puts it into every empty location in your array.
Try this instead:
for (int i=0;i<android.length;i++) { // < instead of <=, don't hardcode the length
if (android[i] == null) {
android[i] = a;
break; // once we insert a, stop looping
}
}
Update
The reason that the compiler can't find Joe is an issue of scope. You have declared Joe as a local variable in the main() method in the Student class. If you want the compiler to be able to see it, you need to declare it in the same method you are using it:
public static void main(String[] args) {
Student Joe = new Student(1,"Joe",40);
addStudent(Joe);
}
A quick google search of "Java variable scope tutorial" should give you plenty of reading about how and when you can use local and member variables.
insert method of student S (1111,"ahmed",3.5)in the position "p" in array of students(id,name,GBG)array size 100 and curent size =3.
-remove method that remove the student having GBG =2.5from the array of student .array size 100 and currentsize=3
First, change the
Array[] Android = new Array[100];
to
Student[] listOfStudent = new Student[100];
What this does is creates a array of size 100, and the type of the array is Students, which is what you will be inserting into the array. You are also going to have to change
for (int i=0;i<=100;i++) {
if (Android[i] == null) {
Android[i] = a;
}
}
to
for(int i=0; i < listOfStudents.length; i++){
if(listOfStudents[i] == null){
listOfStudent[i] = a;
}
}
otherwise you will get a "List Out of Bounds" error. It is better to not hard code values into your code - good practice for the future!
Good Luck!

Categories