Im having trouble with 'keyboard' in my program - java

our assignment objective is to implement 3 students grades in two different classes (Student, grades) and find the average
here is what i have so far,
public class Program01
{
public static void main(String[] args)
{
Student bob, john, matt;
Grades grades;
grades = new Grades();
double bobgrade, johngrade, mattgrade;
bob = new Student();
john = new Student();
matt = new Student();
bob.setup();
john.setup();
matt.setup();
bob.display();
john.display();
matt.display();
bobgrade = bob.overallGrade();
johngrade = john.overallGrade();
mattgrade = matt.overallGrade();
grades.average(bobgrade, johngrade, mattgrade);
System.out.println("The overall grade for the class is: " + grades.theSectionAverage);
}
public class Student
{
Grades grades;
String fullName, firstName, lastName, name;
int studentProgramGrade, studentExamGrade;
public void setup(){
setName();
setGrades();
}
public void setName()
{
System.out.print("Please, enter the student's name in the form of Doe, John or Smith, Jane:");
fullName = Keyboard.readString();
firstName = fullName.substring(fullName.indexOf(" ") + 1, fullName.length());
lastName = fullName.substring(0, fullName.indexOf(","));
name = firstName + " " + lastName;
}
public void setGrades()
{
studentExamGrade = grades.setupExam(name);
studentProgramGrade = grades.setupProgram(name);
}
public void display()
{
System.out.println(name + " " + grades.display());
}
public double overallGrade()
{
final double PROGRAM_WEIGHT = 0.40;
final double EXAM_WEIGHT = 1 - PROGRAM_WEIGHT;
double theOverallGrade;
theOverallGrade = studentProgramGrade * PROGRAM_WEIGHT + studentExamGrade * EXAM_WEIGHT;
return theOverallGrade;
}
}
public class Grades {
int programGrade, examGrade;
double theSectionAverage;
public int setupExam(String studentname)
{
System.out.print("Please, enter the exam grade for " + studentname + ":");
examGrade = Keyboard.readInt();
return examGrade;
}
public int setupProgram(String studentname)
{
System.out.print("Please, enter the program grade for " + studentname + ":");
programGrade = Keyboard.readInt();
return programGrade;
}
public String display()
{
return programGrade + " " + examGrade;
}
public double average(double bobgrade, double johngrade, double mattgrade)
{
theSectionAverage = bobgrade + johngrade + mattgrade / 3;
return theSectionAverage;
}
}
whenever i try to run this, i keep getting this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Keyboard cannot be resolved
at Student.setName(Student.java:18)
at Student.setup(Student.java:10)
at Program01.main(Program01.java:19)
any help would be greatly appreciated.

I think by Keyboard you want to use Scanner in your program.
include the following line in your file
import java.util.Scanner;
and create an instance of it.
Scanner keyboard = new Scanner(System.in);
Or you have some other API that has a class called Keyboard then import that file into your program.
Note: And by the way Scanner doesn't have a readInt() method, it has only nextInt()
This error may happen when you use Eclipse as IDE and try to run code that doesn't even compile. Check your Problems view in Eclipse, and fix the compilation errors before executing the application.

You seem to be missing the import for the Keyboard utils. Java: Input strings with keyboard class
Try importing it, should do the trick.
P.S: This has already been discussed in another topic.

Use
Scanner sc = new Scanner(System.in);
instead of Keyboards

Related

How can i find the name of student who has the highest average? Java

I have a simple project in java.
the project is a program for a teacher who wants to enter the grades for his students (three grades for each student) with five private attributes name,grade1, grade2, grade3and average and three methods: readGrades(), GetAverage() and getName(). I but them all but my problem is no matter what I did the output always gave me the average of the latest student I entered not the highest.I should also print his name not the average.
someone told me to use ArrayList but honestly I don't know how??
so if anyone can help me I'll appreciate it.
This is what i have so far
import java.util.Scanner;
class Student {
private String name;
private int grade1, grade2, grade3;
private double average;
void Setgrade1(int g1) {
grade1 = g1;
}
void Setgrade2(int g2) {
grade2 = g2;
}
void Setgrade3(int g3) {
grade3 = g3;
}
int Getgrade1() {
return grade1;
}
int Getgrade2() {
return grade2;
}
int Getgrade3() {
return grade3;
}
int readGrades() { //method that reads grades.
Scanner input = new Scanner(System.in);
int g1, g2, g3;
String name;
char choice;
do {
System.out.println(" --Please enter the student name: ");
name = input.next();
SetName(name);
System.out.println(" --Please enter the first grade: ");
g1 = input.nextInt();
Setgrade1(g1);
System.out.println(" --Please enter the the second grade: ");
g2 = input.nextInt();
Setgrade2(g2);
System.out.println(" --Please enter the the third grade: ");
g3 = input.nextInt();
Setgrade3(g3);
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = input.next().charAt(0);
}
while (choice != '2');
return choice;
}
void SetAverage(double avr) {
average = avr;
}
double GetAverage() {
average = (grade1 + grade2 + grade3) / 3;
return average;
}
void SetName(String name1) {
name = name1;
}
String getName() {
return name;
}
}
public class TestStudent1 {
public static void main(String args[]) {
Student student = new Student();
student.readGrades();
student.GetAverage();
double i = 0;
double average = student.GetAverage();
if (i < average) {
i = average;
System.out.println("THE HIGHEST AVG :" + i);
}
}
}
A couple of problems in your code here are as follows:
1) It is giving you the output for the latest student is because you are modifying a single object all the time as your logic for entering more grades and name is inside the student itself which should be out.
2) To get the name and not the average you should call getName while printing.
3) To handle multiple students you can take out the logic of asking do you wish to continue in your main method and make an ArrayList of students in the main method to handle multiple student objects or you can do it with other collections as well like
List<Student> students = new ArrayList<>();
From here loop and add the student objects in the list using students.add(studentObj).
Then to get the highest compare the average of the students objects by using getAverage and find the student with the highest average from the list and print it.
That will do it. Try some of it and if you are stuck let us know.
I think your problem is you need to create multiple instances of student object in order to store the data of multiple students. What you did in your code is you will always replace your data with the last input. Here is an example of what you can do.
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
You will also need a data structure to store all the instances of student object, you can either use Array or ArrayList. You will then add every instance of the student object into your data structure. After that, you can compare the average among all the students in your array.
First of all, remove user interaction method readGrades() from data holder Student class. It should be outside. I think that you should not hold average as separate field. This is not big dial to calculate it every time whey you invoke getAverage() method:
public final class Student {
private final String name;
private int grade1;
private int grade2;
private int grade3;
public Student(String name) {
this.name = name;
}
public void setGrade1(int grade1) {
this.grade1 = grade1;
}
public void setGrade2(int grade2) {
this.grade2 = grade2;
}
public void setGrade3(int grade3) {
this.grade3 = grade3;
}
public double getAverage() {
return (grade1 + grade2 + grade3) / 3.0;
}
public String getName() {
return name;
}
public int getGrade1() {
return grade1;
}
public int getGrade2() {
return grade2;
}
public int getGrade3() {
return grade3;
}
}
Second, do create separate method, that interacts with user (or probably other sources) to retrieved required number of students.
private static List<Student> getStudents() {
try (Scanner scan = new Scanner(System.in)) {
List<Student> students = new ArrayList<>();
char choice;
Student student;
do {
System.out.print(" --Please enter the student name: ");
students.add(student = new Student(scan.next()));
System.out.print(" --Please enter the first grade: ");
student.setGrade1(scan.nextInt());
System.out.print(" --Please enter the the second grade: ");
student.setGrade2(scan.nextInt());
System.out.print(" --Please enter the the third grade: ");
student.setGrade3(scan.nextInt());
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = scan.next().charAt(0);
} while (choice != '2');
return students;
}
}
And finally very simple client's code:
List<Student> students = getStudents();
students.sort((s1, s2) -> Double.compare(s2.getAverage(), s1.getAverage()));
System.out.println("THE HIGHEST AVG :" + students.iterator().next().getName());
I'm providing an alternate approach that doesn't use List/ArrayList. Since this is homework, I won't provide code.
Since the requirement is to find the student with the highest average, and you're collecting each student and three grades at a time, you only need to keep track of two instances of Student at any one time. The one with the highest grade bestStudent, and the one being entered currentStudent.
After each student is entered, check to see whether currentStudent's average is higher than bestStudent's. If it is she's your new teacher's pet. Otherwise, discard. Keep in mind, you'll need to handle the first student a little bit differently.
You have only one instance object for that class, so, when you read data for more students, the next student will replace the data from the previous student.
In this case, to save all students and get information about all of them, is better use ArrayList, and push all new data to that list.
e.g:
List<Student> students = new ArrayList<>();
And in the end, you can get the average that you need.
Edit:
Code using ArrayList:
Student class
public class Student {
private String name;
private int grade1, grade2, grade3;
private double average;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade1() {
return grade1;
}
public void setGrade1(int grade1) {
this.grade1 = grade1;
}
public int getGrade2() {
return grade2;
}
public void setGrade2(int grade2) {
this.grade2 = grade2;
}
public int getGrade3() {
return grade3;
}
public void setGrade3(int grade3) {
this.grade3 = grade3;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public double calculateAverage() {
return (grade1 + grade2 + grade3) / 3;
}
}
Main Class
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class MainStudent {
public static void main(String[] args) {
//Create a list of student
List<Student> studentList = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int g1, g2, g3;
String name;
int choice;
do {
//Instantite a new object student
Student student = new Student();
System.out.println(" --Please enter the student name: ");
name = input.next();
student.setName(name);
System.out.println(" --Please enter the first grade: ");
g1 = input.nextInt();
student.setGrade1(g1);
System.out.println(" --Please enter the the second grade: ");
g2 = input.nextInt();
student.setGrade2(g2);
System.out.println(" --Please enter the the third grade: ");
g3 = input.nextInt();
student.setGrade3(g3);
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = input.nextInt();
student.setAverage(student.calculateAverage());
//Push a new object to student list
studentList.add(student);
}
while (choice != 2);
//Get student object with the higher average
Student higherStudent = Collections.max(studentList, Comparator.comparing(c -> c.getAverage()));
System.out.println("THE HIGHEST AVG :" + higherStudent.getAverage() + "\n BELONG'S TO: " + higherStudent.getName());
}
}
I have transfer the while code to main method, and create a new method to calculate the average, because the getAverage is how we will retrieve the value calculate.
Edit: Get higher average with simple loop
Replacing:
Student higherStudent = Collections.max(studentList, Comparator.comparing(c -> c.getAverage()));
By:
Student higherStudent = new Student();
for(int i = 0; i < studentList.size(); i++) {
if(i == 0) {
higherStudent = studentList.get(i);
} else if(higherStudent.getAverage() < studentList.get(i).getAverage()) {
higherStudent = studentList.get(i);
}
}

Creating an array of students based on user input

I'm trying to create an array of math students, science students, and computer students based on the user input.
So basically the user should choose what student they want to add and then enter the student details.
Below I have added the code I have so far:
Main Java class:
public class Lab4 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(4,5);
s[1] = new MathStudent(5,7);
s[2] = new MathStudent(2,8);
s[3] = new MathStudent(3,6);
s[4] = new ScienceStudent(8,9);
s[5] = new ScienceStudent(3,6);
s[6] = new ScienceStudent(4,9);
s[7] = new ComputerStudent(6,12);
s[8] = new ComputerStudent(11,14);
s[9] = new ComputerStudent(13,17);
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (Lab4.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(int age, String name){
this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender;
}
public String getSubjects(){
return this.getSubjects();
}
}
MathStudent class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
public MathStudent(float algebraGrade, float calculusGrade) {
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Algebra Grade: " + algebraGrade + " Calculus Grade: "
+ calculusGrade);
}
}
scienceStudent class:
public class ScienceStudent extends Student {
private float physicsGrade;
private float astronomyGrade;
/**
* Default constructor
*/
public ScienceStudent() {
super();
physicsGrade = 6;
astronomyGrade = 7;
}
public ScienceStudent(float physicsGrade, float astronomyGrade) {
this.physicsGrade = physicsGrade;
this.astronomyGrade = astronomyGrade;
}
// Getters
public void setPhysicsGrade(float physicsGrade){
this.physicsGrade = physicsGrade;
}
public void setAstronomyGrade(float astronomyGrade){
this.astronomyGrade = astronomyGrade;
}
// Setters
public float getPhysicsGrade() {
return this.physicsGrade;
}
public float getAstronomyGrade() {
return this.astronomyGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Physics Grade: " + physicsGrade + " Astronomy Grade: "
+ astronomyGrade);
}
}
computerStudent class:
public class ComputerStudent extends Student {
private float fortanGrade;
private float adaGrade;
/**
* Default constructor
*/
public ComputerStudent() {
super();
fortanGrade = 4;
adaGrade = 9;
}
public ComputerStudent(float fortanGrade, float adaGrade) {
this.fortanGrade = fortanGrade;
this.adaGrade = adaGrade;
}
// Getters
public void setFortanGrade(float fortanGrade){
this.fortanGrade = fortanGrade;
}
public void setAdaGrade(float adaGrade){
this.adaGrade = adaGrade;
}
// Setters
public float getFortanGrade() {
return this.fortanGrade;
}
public float getAdaGrade() {
return this.adaGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Fortan Grade: " + fortanGrade + " Ada Grade: " + adaGrade);
}
}
How Would I go about this?
You can ask for the number of students with type on each input and dynamically create the object.
Here is an example
System.out.println("Enter total number of students");
int n = scannerObject.nextInt();
Student students[] = new Students[n];
for(int i=0;i<n;i++){
int type = scannerObject.nextInt();
if(type == 1)
students[i] = new MathStudent();
}
Similarly, you can write for others.
For allowing user to enter his choice as input
You can do this(interpreted by your comments)
Pseudo code -
Print:
Enter 1 for math student
Enter 2 for Science student
Enter 3 for Comp student
Input choice
Now in your code use either multiple if else or better switch statement
switch(choice){
case 1: create object of math student
break;
case 2: create object of science student
break;
case 3:create object of comp student
break;
default: if not above by default do this
}
You could use an ArrayList and switch case to make your life easier. Your code should be like this:
import java.util.ArrayList;
import java.util.Scanner;
public class Students {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
switch (lesson) {
case "Math":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Algebra grade: ");
int alg = input.nextInt();
System.out.print("Give student's Calculus grade: ");
int calc = input.nextInt();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new MathStudent(alg, calc);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((MathStudent) st).getSubjects());
break;
case "Science":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Physics grade: ");
int physics = input.nextInt();
System.out.print("Give student's Astronomy grade: ");
int astronomy = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ScienceStudent(physics, astronomy);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ScienceStudent) st).getSubjects());
break;
case "Computers":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Fortran grade: ");
int fortran = input.nextInt();
System.out.print("Give student's Ada grade: ");
int ada = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ComputerStudent(fortran, ada);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ComputerStudent) st).getSubjects());
break;
default:
System.out.println("Wrong lesson");
addMore = false;
break;
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
The code above asks for the lesson name (Computers, Math, Science) and if it is one of them it reads all the info about the student and the grades for the corresponding lesson. It creates the objects and adds them in the list students. When all info is added, it asks the user if he/she wants to add another student and if he writes the letter y, then all these are made again, until the user answers something different than the letter y (the letter n in most cases). After these it prints all the students' info by itterating the list.
Note: I think in your code for the ComputerStudent class, you meant to name the variable fortranGrade and not fortanGrade (change it also in the getSubjects function).
Links:
Java ArrayList
Switch Case in Java
Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
I hope this helped you. If you have any questions or wanted something more you can do it.
UPDATE
The code below does the same things, but it uses for loop instead of switch case, as you asked in your comment.
package students;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Lab4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
ArrayList<Class<?>> studentClasses = new ArrayList<>();
studentClasses.add(MathStudent.class);
studentClasses.add(ComputerStudent.class);
studentClasses.add(ScienceStudent.class);
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
addMore = false;
for (Class studentClass : studentClasses) {
try {
st = (Student) studentClass.newInstance();
if (st.getLessonName().equals(lesson)) {
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's " + st.getSubjectsNames()[0] + " grade: ");
float firstSubj = input.nextFloat();
System.out.print("Give student's " + st.getSubjectsNames()[1] + " grade: ");
float secondSubj = input.nextFloat();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = (Student) studentClass.getConstructor(float.class, float.class).newInstance(firstSubj, secondSubj);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(st.getSubjects());
addMore = true;
break;
}
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Lab4.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
System.out.println("Wrong lesson. Try again.");
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
You also need to add the functions in the classes as mentioned bellow:
Student class:
public String getLessonName(){
return "";
}
public String[] getSubjectsNames(){
return new String[] {"", ""};
}
MathStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Algebra", "Calculus"};
}
#Override
public String getLessonName(){
return "Math";
}
ComputerStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Fortran", "Ada"};
}
#Override
public String getLessonName(){
return "Computers";
}
ScienceStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Physics", "Astronomy"};
}
#Override
public String getLessonName(){
return "Science";
}
Changes: The code firstly creates an arraylist with the student classes (studdentClasses) and adds all the classes for the students that are currently in the project (MathStudent, ComputerStudent, ScienceStudent). Then the user adds the lesson's name. Then (instead of the switch case) there is a for loop which itterates through the studdentClasses list and checks if the lesson's name that the user has written is the same with a student's class by using the getLessonName function. After that all the info for the student are asked and the grades for the subjects, and for the question (Give student's Physics grades) it uses the function getSubjectsNames. All the other things are like before.
You have a main class, that's what you need essentially, but you need to read from command line. Great, run from command line. Once you run, pay attention to what you did, you can pass parameters there as well. once you pass parameters, they go in line. This line is logically splitable, so split it within you code. for instance by pair of numbers after some key word like science and until next keyword and put again from java and ask a new question once you there.

Outputting information without explicitly calling toString() in java

For step 6 in the println i know how to call the toString explicitly but how do i output student information from the current student in the array WITHOUT calling toString() explicitly or using any accessor methods?
import java.util.Scanner;
public class Students
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Student[] students;
students = getStudents();
printStudents(students);
}
private static Student[] getStudents()
{
Student[] temp;
int how_many;
System.out.print("How many students? ");
how_many = input.nextInt();
purgeInputBuffer();
temp = new Student[input.nextInt()]; // Step 1 ???
for (int i = 0; i < temp.length; i++)
{
getStudent();
temp[i] = getStudent(); // Step 2
}
return temp; // Step 3
}
private static Student getStudent()
{
String name,
address,
major;
double gpa;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter address: ");
address = input.nextLine();
System.out.print("Enter major: ");
major = input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
purgeInputBuffer();
return new Student(name, address, major, gpa); // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(______); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
Declare your variables name, address, major, gpa as member variables.
Override the toString() method for this class.
public String toString() {
return "Name: " + name + "\n" + "Address: " + .... //whatever you want to print.
}
Whenever you need to print details of a student, pass it to the println method:
System.out.println(obj); //where obj is a Student object.
In your Stundent class override the toString() method as, for example,:
#Override
public String toString() {
return "Stundent [ Name: " + name + ", Address: " + address + ", Major: " + major + ", GPA: " + gpa + " ]";
}
And modify your printStudents() method as follows (your Step 6):
private static void printStudents(final Student[] s) {
System.out.println();
for (final Student student : s) {
System.out.println(student);
}
}
Then your output should look like:
Stundent [ Name: Name1, Address: Addr1, Major: Major1, GPA: 3.0 ]
Stundent [ Name: Name2, Address: Addr2, Major: Major2, GPA: 3.5 ]
Now you see the toString() method will be invoked implicitly.

How do I terminate the program in Java?

This is my code. The program won't give me the last print line "Thank you for using the Basic user Interface program."
public class nameClass {
public static void main(String[] args) {
String input;
String name;
int age;
double mileage;
displayApplicationInformation();
displayDivider("Start Program");
TerminateApplication();
// process name
displayDivider("Get Name");
name = getInput("name");
System.out.println("Your name is: " + name);
// Process age
displayDivider("Get Age");
input = getInput("Your age");
age = Integer.parseInt(input);
System.out.println("Your age is: " + age);
// Process Mileage
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
}// end of main
public static void displayApplicationInformation()
{
System.out.println("Welcome to the Basic User Interface Program");
}// end of displayApplicaionInformation
public static void displayDivider(String outputTitle) {
System.out.println("*********" + outputTitle + "********");
}// end of displayDvider
public static String getInput(String inputType)
{
String input = "";
input = JOptionPane.showInputDialog("Enter the " + inputType);
return input;
}
public static void TerminateApplication()
{
System.out.println("Thank you for using the Basic User Interface program");
return;
}
}// end of MainClass
You have to actually call the method TerminateApplication;
System.out.println("Your car MPG is: " + mileage);
TerminateApplication();
Simple, call TerminateApplication.
You are doing it on the 9th line of main().
Here, check this out:
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
//add this...
TerminateApplication();
Hope this helps!

Having trouble with array

I am currently trying to program a array based program. We have to make a employee class then a tester main class that holds a array of five user input employee names, salaries, and performance rating. The performance rating is used to determine a supplied raise amount. I have it basically done, but when i run the program, nothing happens even though java virtual machine is running. I have looked up and down for the error, anyone can point out what i am doing wrong?
Employee Class
public class Employee
{
private String employeeName;
private int salary;
private int performanceRating;
public Employee()
{
employeeName = "";
salary = 0;
performanceRating = 0;
}
public String getEmployeeName()
{
return employeeName;
}
public int getSalary()
{
return salary;
}
public int getPerformanceRating()
{
return performanceRating;
}
}
And this is the tester main class where the error comes in somewhere
import java.util.Scanner;
public class Tester
{
public static void main(String[] args)
{
Employee[] work = new Employee[5];
Scanner scanString = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
String employeeName = "";
double salary = 0;
double performanceRating = 0;
String choice = scanString.nextLine();
while(choice.equals("yes"))
{
for(int i = 0; i < 5 ;i++)
{
System.out.println("What is the employee's name?");
employeeName = scanString.nextLine();
System.out.println("Enter Employee's salary");
salary = scanInt.nextInt();
System.out.println("Performance? 1 = excellent, 2 = good, 3 = poor");
performanceRating = scanInt.nextInt();
work[i] = new Employee();
}
for(int j = 0; j < 5; j ++)
if(work[j].getPerformanceRating() == 1)
{
salary = salary * 0.06;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 2)
{
salary = salary * 0.04;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 3)
{
salary = salary * 0.015;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating < 5)
{
salary = salary;
System.out.println("Rating is off scale. No raise for emplyee " + employeeName);
}
System.out.println("Enter more employees? type 'yes' if you want to go again");
choice = scanString.nextLine();
}
System.out.println("Done");
}
}
The program reads from System.in. If you don't enter anything, nothing will happen.
Not sure why you have 2 Scanners instead of just one.
You have while(choice.equals("yes")) except you never prompt the user to make a choice. The program does do stuff (some of which may not all work properly), but you have to give the program input. What you can do is ask the user a question before the line String choice = scanString.nextLine();.
As a side note, you could use a switch in place of the if and else if's and it might be a little easier to read and understand.

Categories

Resources