Here is my code. I did my work a bit off. I was supposed to not just do one applicant, I was supposed to do many and I was supposed to populate the applicants into 2 different arrays, one for graduates, and one for undergraduates. I need help figuring out how to make an empty array and fill up applicants in those. A start would help
import java.util.Scanner;
public class CollegeApplicant
{
String applicantName;
String collegeName;
public String getApplicantName()
{
return applicantName;
}
public void setApplicantName(String applicantName)
{
this.applicantName = applicantName;
}
public String getCollegeName()
{
return collegeName;
}
public void setCollegeName(String collegeName)
{
this.collegeName = collegeName;
}
public void checkCollege()
{
int choice;
Graduate g = new Graduate();
Undergraduate ug = new Undergraduate();
Scanner input = new Scanner(System.in);
System.out.println("1. Undergraduate");
System.out.println("2. Graduate");
System.out.println("enter your choice ");
choice = input.nextInt();
if (choice == 1)
{
System.out.println("Enter SAT marks :");
ug.SAT = input.nextDouble();
System.out.println("Enter GPA marks :");
ug.GPA = input.nextDouble();
}
else
{
System.out.println("Enter the origin of college:");
g.collegeOrigin = input.next();
System.out.println("Status :" + g.checkCollege());
}
}
public class Undergraduate
{
double SAT;
double GPA;
}
public class Graduate
{
String collegeOrigin;
String checkCollege()
{
String information = null;
if (collegeName.equals(collegeName)) information = "Applicant is applying from inside";
else information = "Applicant is applying from outside";
return information;
}
}
}
The Client
import java.util.Scanner;
public class CollegeApplicantClient extends CollegeApplicant
{
public static void main(String[] args)
{
TestCollege tc = new TestCollege();
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of applicant ");
tc.setApplicantName(input.next());
System.out.println("enter the college name of applicant ");
tc.setCollegeName(input.next());
tc.checkCollege();
}
}
Here is an example of the possible output
Name: Joe
College Applied to: Harvard
SAT: 5
GPA: 2
Name: Tom
College Applied to: Yale
College of Origin: NYU – from outside
I need to be able to put the graduates in an array and the undergrads in an array. Then display it when it's all done
Related
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);
}
}
I am working on a project for school. at this point i'm just going over board, I would like to run the class bookstoreCreditPersonal if none of the following conditions are true, but I cant get it to work. any suggestions?
import java.util.Scanner;
public class bookstoreCreditPersonal {
public static void main(Object o) {
String studentNamePers;
String userType;
double studentGPAPers;
double bookstoreCreditPers;
Scanner input = new Scanner(System.in);
System.out.print("Please enter 'S' if you are the student, 'T' if you are the teacher, or 'P' if you are the Parent: ");
userType = input.nextLine();
if (userType.equals("S")) {
System.out.println("Greetings student...");
Scanner Sinput = new Scanner(System.in);
System.out.println("Please enter your(The students) first and last name :");
studentNamePers = input.nextLine();
Scanner SSinput = new Scanner(System.in);
System.out.println("Please enter your(The student's) GPA :");
studentGPAPers = input.nextDouble();
bookstoreCreditPers = studentGPAPers * 10;
System.out.println(studentNamePers + ", your GPA is " + studentGPAPers + ", and you have an available bookstore credit of $" + bookstoreCreditPers);
} else if (userType.equals("T")) {
System.out.println("Teacher");
} else if (userType.equals("P")) {
System.out.println("Parent");
} else {
System.out.println("Lets try that again, one character, in capital form only please.");
//created a class that reruns this class
runClassBSCP.call(null);
}
}
}
Here is the class runClassBSCP:
public class runClassBSCP {
public void call() {
bookstoreCreditPersonal.main(null);
}
}
You need to instantiate/create an object of the class. Then you can call the desired method with the object.
runClassBSCP bscp = new runClassBSCP();
bscp.call();
Also, your class names should always start with an uppercase letter: RunClassBSCP, rather than `runClassBSCP'. For more info, check out Code Conventions for the Java Programming Language.
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.
i am trying to enter a book title "hoopa doopa"into my object array. when i try it throws a java.util.InputMismatchException.If i enter a string that has no spaces like"hoopa" the code will run fine all of the way through. What is causing this and how can I fix it? please help thanks
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int counter = 0;
int numberOfProducts=0; //variable for when the user is asked to enter input the number of products to be entered
do { //this will validate the user input
System.out.println("How many products would you like to enter");
while (!input.hasNextInt()) {
System.out.println("That's not a number!");
input.next(); // this is important!
}
numberOfProducts = input.nextInt();
} while (numberOfProducts <= 0);
//end of the do while loop
Products[] products;
products = new Products[numberOfProducts+4];//create a array the size of the user input that was gathered
for (int i=0;i<numberOfProducts;i++)
{
products[i+4]= new Products(); // create each actual Person
System.out.println("What is the product #: ");
products[i+4].setItemNumber(input.nextInt());
System.out.println("What is the book name: ");
products[i+4].setNameOfProduct(input.next());
System.out.println("How many are in stock: ");
products[i+4].setUnitsInStock(input.nextInt());
System.out.println("What is the cost of the Item: ");
products[i+4].setPrice(input.nextDouble());
counter++;
}
products[0] = new Products(0001,"The Red Rose",1,29.99);
products[1] = new Products(0002,"The Bible",3,11.99);
products[2] = new Products(0003,"End of the Programm",2,29.99);
products[3] = new Products(0004,"WHAT!!! the....",1,129.99);
//____________________________________________________________4 products that are already made
for (int i=0;i<numberOfProducts+4;i++)
{
System.out.println(products[i].toString());
input.nextLine();
}
}
}
this is the other class
import java.text.NumberFormat;
public class Products
{
private int itemNumber;
private String nameOfProduct;
private int unitsInStock;
private double unitPrice;
public Products()
{
itemNumber = 0;
nameOfProduct = null;
unitsInStock = 0;
unitPrice = 0.0;
}
public Products(int num,String name,int inStock,double price)
{
itemNumber = num;
nameOfProduct = name;
unitsInStock = inStock;
unitPrice = price;
}
public int getItemNumber()
{
return itemNumber;
}
public void setItemNumber(int newValue)
{
itemNumber=newValue;
}
//----------------------------------------------
public String getNameOfProduct()
{
return nameOfProduct;
}
public void setNameOfProduct(String newValue)
{
nameOfProduct=newValue;
}
//----------------------------------------------
public int getUnitsInStock()
{
return unitsInStock;
}
public void setUnitsInStock(int newValue)
{
unitsInStock = newValue;
}
//-----------------------------------------------
public double getPrice()
{
return unitPrice;
}
public void setPrice(double newValue)
{
unitPrice = newValue;
}
//_______________________________________________
public double calculateTotalItemValue() //method that uses quantity on hand and price part3 1.A
{
return getUnitsInStock()* getPrice();
}//end of method
#Override
public String toString()
{
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
return"\nItem Number: "+getItemNumber() +
"\nItem Name: "+getNameOfProduct()+
"\nItem Quantity: " +getUnitsInStock()+
"\nItemPrice:" +currencyFormat.format(getPrice())
+"\nValue of Inventory: " +currencyFormat.format(this.calculateTotalItemValue());//part3 1.B
}
}
The Scanner sees the space in the book name as a delimiter since you are using the next() method. So when you go to read the nextInt() for the stock amount, the Scanner index is after the space in the book name String, and pulls in the remaining String data, which doesn't convert to an int. Instead, try something like this:
System.out.println("What is the book name: ");
input.nextLine();
products[i+4].setNameOfProduct(input.nextLine());
If you do not add the input.nextLine();, then it will appear as though the book name prompt gets skipped.
Scanner input = new Scanner(System.in);
Actually you are using scanner to get input and by default scanner delimiter is space. So you have to change the default delimiter of your code.
I think this is your problem:
products[i+4].setNameOfProduct(input.next());
What input.next() does is it reads the input from the user, until it reaches white space (the space between hoopa doopa). The function then passes hoopa to the setNameOfProduct method, and then passes doopa to the nextInt function, which gives a runtime error.
To fix your problem I would code
products[i+4].setNameOfProduct(input.nextLine());
Edit:
nextLine() function passes all characters up to the carriage return
Problem :
products[i+4].setNameOfProduct(input.next());
Solution 1 :
Just create another Scanner object for reading input with spaces
Scanner sc1=new Scanner(System.in);
products[i+4].setNameOfProduct(sc1.nextLine());
Solution 2 :
Or to use same scanner object
input.nextLine(); //Include this line before getting input string
products[i+4].setNameOfProduct(input.nextLine());
Hey guys just need help on how to finish this up.
Code Snippet:
import java.util.Scanner;
public class CreateLoans implements LoanConstants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//set the program here
float prime;
float amountOfLoan = 0;
String customerFirstName;
String customerLastName;
String LoanType;
System.out.println("Please Enter the current prime interest rate");
prime = sc.nextInt() / 100f;
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
LoanType = sc.next();
//enter the Loan amount
System.out.println("Enter the amount of loan");
amountOfLoan = sc.nextInt();
//enter Customer Names
System.out.println("Enter First Name");
customerFirstName = sc.next();
System.out.println("Enter Last Name");
customerLastName = sc.next();
//enter the term
System.out.println("Enter the Type of Loan you want. 1 = short tem , 2 = medium term , 3 = long term");
int t = sc.nextInt();
}
}
I need to display the records I have asked and store the object into an array.
so this where I'm stuck. I need to do this in a loop 5 times and by the end display all records in an array, if that makes sense?
Try this way :
import java.util.Scanner;
public class CreateLoans {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Loan[] loans = new Loan[5];
for(int i=0;i<5;i++) {
loans[i] = new Loan();
System.out.println("Please Enter the current prime interest rate");
float prime = sc.nextInt();
prime = (float)(prime/100f);
loans[i].setPrime(prime);
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
String loanType = sc.next();
loans[i].setLoanType(loanType);
//enter the Loan amount
System.out.println("Enter the amount of loan");
float amountOfLoan = sc.nextFloat();
loans[i].setAmountOfLoan(amountOfLoan);
//enter Customer Names
System.out.println("Enter First Name");
String customerFirstName = sc.next();
loans[i].setCustomerFirstName(customerFirstName);
System.out.println("Enter Last Name");
String customerLastName = sc.next();
loans[i].setCustomerLastName(customerLastName);
}
//Display details
for(int i=0;i<5;i++) {
System.out.println(loans[i]);
}
}
}
class Loan {
private float prime;
private float amountOfLoan = 0;
private String customerFirstName;
private String customerLastName;
private String LoanType;
public float getPrime() {
return prime;
}
public void setPrime(float prime) {
this.prime = prime;
}
public float getAmountOfLoan() {
return amountOfLoan;
}
public void setAmountOfLoan(float amountOfLoan) {
this.amountOfLoan = amountOfLoan;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public String getLoanType() {
return LoanType;
}
public void setLoanType(String loanType) {
LoanType = loanType;
}
#Override
public String toString() {
return "First Name : " + customerFirstName + "\n" +
"Last Name : " + customerLastName + "\n" +
"Amount of Loan : " + amountOfLoan + "\n" +
"Loan type : " + LoanType + "\n" +
"Prime : " + prime + "\n\n";
}
}
Create a Loan class and put all necessary details as private members into it and override toString() method.
Make a ArrayList and add all the variables inside that list
ArrayList arrlist = new ArrayList();
arrlist.add(prime);
arrlist.add(LoanType);
arrlist.add(amountOfLoan);
arrlist.add(customerFirstName );
arrlist.add(customerLastName);
arrlist.add(t);
and display the ArrayList
System.out.println(arrlist);
Example of a loop
int[] nums = new int[5];
String[] names = new String[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++){
System.out.println("Enter a number: ");
int number = input.nextInt();
// insert into array
nums[i] = number;
System.out.println("Enter a name: ");
String name = input.nextLne();
// insert into array
names[i] = name;
}
Everything you want to be looped 5 times, you can put inside the loop. Whatever values you want to store, you can do that in the loop also.