I'm trying to finish this homework:
Create a simple Friendsclass with, as a minimum, the following:
name and age fields
appropriate constructors
get/set methods
toString() method
Create an ArrayList of Friends
Run the program from a menu with the following options:
Add a Friend
Remove a Friend
Display all Friends
Exit
And this is what I got so far:
Friends.class
public class Friends
{
public static String name;
public static int age;
// parameters
public Friends(String name, int age)
{
this.name = name;
this.age = age;
}
// set name
public static void setName(String friendName)
{
name = friendName;
}
// get name
public static String getName()
{
return name;
}
// set age
public static void setAge(int friendAge)
{
age = friendAge;
}
// get age
public static int getAge()
{
return age;
}
// return toString()
public String toString()
{
return this.getName() + " " + this.getAge();
}
} //end clas
And FriendsTest.class:
import java.util.Scanner;
import java.util.ArrayList;
public class FriendsTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// objects
ArrayList<Friends> friendsList = new ArrayList<>();
Friends a1 = new Friends("James", 10);
Friends a2 = new Friends("Christopher", 17);
Friends a3 = new Friends("George", 25);
Friends a4 = new Friends("Linda", 31);
Friends a5 = new Friends("Karen", 62);
friendsList.add(a1);
friendsList.add(a2);
friendsList.add(a3);
friendsList.add(a4);
friendsList.add(a5);
// menu
int menu_choice;
do
{
System.out.println("\n1. Add a Friend");
System.out.println("2. Remove a Friend");
System.out.println("3. Display all Friends");
System.out.println("4. Exit");
System.out.print("\nSelect one option: ");
menu_choice = input.nextInt();
switch (menu_choice)
{
case 1:
System.out.print("Enter Friend's name: ");
Friends.setName(input.next());
System.out.print("Enter Friend's age: ");
Friends.setAge(input.nextInt());
Friends a6 = new Friends(Friends.getName(), Friends.getAge());
friendsList.add(a6);
break;
case 2:
System.out.println("Enter Friend's name to remove: ");
Friends.setName(input.next());
friendsList.remove(Friends.getName());
break;
case 3:
for(int k = 0; k < friendsList.size(); k++)
{
System.out.println(friendsList.get(k).name + " " + friendsList.get(k).age);
}
break;
case 4:
System.exit(0);
}//end switch
} while (menu_choice != 4);
}//end main
}//end class
When I run the program, neither Option 1, 2 and 3 seems to work:
With (1) I get the user input 5 times...
With (2) I get the the input 5 times too
If I select display(3) I get: "Karen 62" 5 times...
I'm not sure if I applying the loop correctly and if I'm using the setters and getters correctly.
I would like to recommend you to use an IDE (for example ECLIPSE[it's free]). An IDE is an integrated development environment, which is basically a text editor(like word or notepad) that would help you minimize errors (mostly syntax errors) in your code.
Things you should fix in your code:
In the Friends class you should erase all of the 'static' keywords. Plus, I would recommend you to use private instead of public all of the attributes of this class (that means in name and in age you should use private instead of public).
In the FriendsTest class:
case 1:
System.out.println("Enter Friend's name: ");
String name = input.next();
System.out.println("Enters Friend's age: ");
int age = input.next();
Friends a6 = new Friends(name,age);
friendsList.add(a6);
break;
case 2:
You need to learn how to use an iterator (look it up at java's API) if you are working with an ArrayList.
The remove(int index) method only lets you delete an object in a specified postion (that means you should know the postion of the friend you want to delete in the friendsList).
case 3:
You should use an iterator to iterate in the friendsList and use the toString method of the Friends class to print each friend.
You should not declare the Friends class's properties as static, neither its getters & setters :
Change
public static String name;
public static int age;
public static void setName(String friendName) ...
public static String getName() ...
public static void setAge(int friendAge) ...
public static int getAge() ...
to
public String name;
public int age;
public void setName(String friendName) ...
public String getName() ...
public void setAge(int friendAge) ...
public int getAge() ...
main() :
switch (menu_choice)
{
case 1:
String name;
int age;
System.out.print("Enter Friend's name: ");
name = input.next();
System.out.print("Enter Friend's age: ");
age = input.nextInt();
Friends a6 = new Friends(name, age);
friendsList.add(a6);
break;
. ...
Retrieve the name & age separatly, create a new Friends object with the corresponding name & age, the add it to the ArrayList. (Adjust this with the other cases accordingly)
Related
I am currently using java and still haven't got the hang of everything so bear with me. I have been trying to get my names to appear on the output menu but I must be missing something in my code.
Here is my code it has a driver class and client class:
import java.util.Scanner;
//This is TestBaby.java class
public class TestBaby {
// This is main() method, program execution start from here
public static void main(String[] args) {
// This is Scanner class object, it will help to take value from end user
Scanner scan = new Scanner(System.in);
//This is array object of Baby type
Baby[] babies = new Baby[4];
//This is for loop, it iterates 4 times for holding 4 Babies data
for(int i=0; i<4; i++) {
//a. Enter details for each baby (name and age) and thus populate the Baby array
System.out.println("Enter details of " + "Baby " +(i+1));
if(i!=0)
scan.nextLine();
System.out.println("Enter name: ");
String name = scan.nextLine();
System.out.println("Enter age: ");
int age = scan.nextInt();
//This is Baby class object*/
Baby baby = new Baby();
//Set name in Baby class object whatever user entered
baby.setName(name);
//Set age in Baby class object whatever user entered
baby.setAge(age);
//Store current Baby class object into babies array
babies[i] = baby;
}//for end
//b. Output the details of each baby from the array (name and age)
int i=0;
for(Baby baby : babies) {
System.out.println("Baby name: " + baby.getName());
System.out.println("Baby age: " + baby.getAge());
i++;
}
//c. Calculate and display the average age of all babies in the array
double averageAge = averageAge(babies);
System.out.println("Average age of all babies: "+averageAge);
//d. Determine whether any two babies in the array are the same
for(i=0; i<babies.length; i++) {
for(int j=i+1; j<babies.length; j++) {
System.out.println(babies[i].getName()+ " and " + babies[j].getName() + " are equal? " + babies[i].equals(babies[j]));
}//inner for loop
}//outer for loop
}//main() end
//This is averageAge() method, it will calculate average age of Babies
public static double averageAge(Baby[] babies) {
//These are local variables of averageAge() method
int size = babies.length;
double averageAge = 0.0;
//This is for loop, it will calculate total age of babies
for(int i=0; i<size; i++) {
averageAge = averageAge + babies[i].getAge();
}//for end
//return average age to caller of this method
return averageAge/size;
}//averageAge() end
}// TestBaby end
//This is Baby.java class
public class Baby {
//These are instance variable of Baby.java class
private String name;
private int age;
//This is default constructor
public Baby() {
name = "Baby";
age = 1;
}
//This is parameterized constructor will take two parameters, a string to set the name and an integer to set the age
public Baby(String name, int age) {
this.name = name;
this.age = age;
}
//Supply methods for setting the name, setting the age, getting the name and getting the age.
public String getName() {
return name;
}
public void setName(String name) {
//The set method for the name instance variable should ensure that the input is not empty or contain whitespaces (otherwise set a default value)
if (name.trim().isEmpty()){
this.name = "Baby";
this.name = name;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
//The set method for the age instance variable should validate the input to be between 1 and 4 inclusive (otherwise set a default value).
if (age >= 1 && age <= 4) {
this.age = age;
} //if end
else {
this.age = 1;
}//else end
}// setAge() end
//Give Java code for an equals method for the Baby class.
#Override
public boolean equals(Object obj) {
//This is type casting
Baby baby = (Baby)obj;
//Compare name and age of Baby, if both are same then return true otherwise return false
if(this.age == baby.age && this.name.equalsIgnoreCase(baby.name))
return true;
return false;
}//equals() end
}// Baby end
Please try the code first so you understand what I mean incase its not clear
Baby.setName(String name) only sets the name if name is empty. Your method:
public void setName(String name) {
if (name.trim().isEmpty()){
this.name = "Baby";
this.name = name;
}
}
Try this:
public void setName(String name)
{
if (name == null)
{
// Use default from constructor
return;
}
String n = name.trim();
if (!n.isEmpty())
{
this.name = n;
}
}
I guess your setName() is badly written. You only set the new name if it is empty. I guess there is a not (!) missing.
so im just starting to study java and planning to learn it in-depth and then i wanna ask this thing because im stuck and to learn more.
im trying to use the get and return method.
i wanted to do this in an input way but i cant use the
"int age = person1.GetAge()
System.out.println("Age:" + age) because it will become 2 variables (age)
i hope you understand my question and i know it sounds stupid but i wanna learn xD.
CODE:
//unfinished
//cant use the getAge, no idea how; the value in yrsleft is always 65 despite of the formula that i give
package practice;
import java.util.Scanner;
class person{
String name;
int age;
void speak() {
System.out.print("Hello my name is:" + name);
}
int retire() {
int yrsleft = 65 - age;
return yrsleft;
}
int GetAge() {
return age;
}
}
public class curiosity1{
public static void main(String[]args) {
person person1 = new person();
Scanner input = new Scanner(System.in);
System.out.print("What is your name:");
String name = input.next();
System.out.print("What is your age:");
int age = input.nextInt();
//person1.name = "John";
//person1.age = 30;
System.out.println("Name: " + name);
int age = person1.GetAge();
System.out.println("Age:" + age);
int years = person1.retire();
System.out.println("Years till retirement:" + years);
}
}```
I hope I understood your question correctly, you want to do this?
person1.age = input.nextInt();
person1.name = input.next();
System.out.println("Age:" + person1.getAge());
Or you can override toString() method in your class (since all java classes are inherited from Object, which has this method) to represent your object with a string. Also, you should create a constructor for your Person class.
class Person { // always start class name with a capital letter
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
// Your methods and etc.
#Override
public String toString() {
return "Name:" + this.name + ". Age:" + this.age;
}
}
And then:
int age = input.nextInt();
String name = input.next();
Person person1 = new Person(age, name);
System.out.println(person1.toString());
how to print Junior, Intermediate,Seniour as string as per age,and must generate roll number and these input must b generated from the user. Ex: junior name:Rahul age:22, roll:1000 intermediate name:prem age:40, roll:1001 senior name: Vamsi age:60, rollno:1002
String name;
static int age;
public static void main(String[] args) {
int size = 3;
DB[] studs = new DB[size];
for (int i = 0; i < size; i++) {
studs[i] = readStudent(i);
}
for (int i = 0; i <studs.length; i++) {
if(age <=30) {
System.out.println( studs[i]);
}else if(age <=40) {
System.out.println("Intermidiate" +" "+studs[i]);
}else {
System.out.println("Seniour" +" "+studs[i]);
}
}
}
static DB readStudent(int i) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name:");
String name = sc.nextLine();
System.out.print("Enter your age:");
int age = sc.nextInt();
DB studs = new DB(name, age);
return studs;
}
}
class juniourStudent extends Student {
String rollno = "juniour";
static int juniourcount = 1000;
juniourStudent(String name, int age) {
rollno = "juniour" + juniourcount++;
}
}
class intermidiateStudent extends Student {
String rollno = "intermidiate";
static int intermidiatecount = 1000;
intermidiateStudent(String name, int age) {
rollno = "intermidiate" + intermidiatecount++;
}
}
class seniourStudent extends Student {
String rollno = " seniour";
static int seniourcount = 1000;
seniourStudent(String name, int age) {
rollno = "seniour" + seniourcount++;
}
}
There are quite a few issues with your code.
Your class structure is counter-intuitive to what you are trying to do. Based on the example output, it seems that you want the rollNo to increase every time a student is made. It also seems to be redundant to create separate classes when the only thing that differs between them is the prefix (like junior, senior, intermediate, etc.). Instead of making multiple classes, why not add an instance variable to your student class. (Also import Scanner so we can use it later for user input, and ArrayList to store the student data) For Example:
import java.util.Scanner;
import java.util.ArrayList;
public class Student {
String name;
String studentType;
int age;
int rollno;
static int schoolRollno = 1000;
Next you should make a proper constructor for your student class consisting of a String name and an int age, and assigning them to the instance variables we declared earlier. We will assign the studentType variable based upon their age, and we will obtain the students rollno from the static variable. We must increment the static variable so the next student will have a different roll number. (You can change the age comparisons to whatever number you need, but these numbers are what I pieced together from your code)
public Student(String name, int age) {
this.name = name;
if(age <= 30) {
this.studentType = "Junior";
}
else if(age <= 40) {
this.studentType = "Intermediate";
}
else {
this.studentType = "Senior";
}
this.age = age;
this.rollno = schoolRollno;
schoolRollno++;
}
The last thing we need to do before we work on our main function is to write a toString() method for our student class. Based upon the output, you might want a method like this:
#Override
public String toString() {
return studentType + " name: " + name + " age: " + age + ", roll: " + rollno;
}
Now we can take a look at the public static void main(String args[]) function. We have a few things we need to do here. Since it appears we do not know the number of students we are going to be adding, we should use an ArrayList. We should also instantiate our scanner here as well:
ArrayList<Student> students = new ArrayList<Student>();
Scanner scan = new Scanner(System.in);
Now we should create a while loop that allows the user to continue inputting students and wish to stop. Personally, I'm a fan of the do/while loop, so I'll do it that way. We'll need to declare our variable outside of the loop so that we can use it as a conditional for the loop.
boolean done = false;
do {
//(inner loop code here)
} while(!done);
//end loop code
Now for the inner loop code. We need to obtain a String (name) from the user and an int (age). Once we obtain the inputs, we want to construct a Student object and add it to our ArrayList. Then, after all that, we want to see if the user wants to input another student (by changing the value of our boolean we used when declaring the first do/while loop according to the user's input). We can do all this using scanner like so:
System.out.println("Enter name:");
String name = scan.nextLine();
System.out.println("Enter age:");
int age = scan.nextInt();
//we use scan.nextLine() here because scan.nextInt() does not read to the end of the line
scan.nextLine();
Student s = new Student(name, age);
students.add(s);
boolean validInput = true;
do {
validInput = true;
System.out.println("Continue? (y/n)");
String input = scan.nextLine();
if(input.equalsIgnoreCase("y")) {
done = false;
}
else if(input.equalsIgnoreCase("n")) {
done = true;
}
else {
validInput = false;
}
} while(!validInput);
Finally, we want to print the students once we are done. We can print all the students in our ArrayList easily using a for-each loop. (This goes at the end of our main(String args[]) method)
for(Student s: students) {
System.out.println(s.toString());
}
TL;DR:
Combine your classes into one student class
Fix the constructor
Add a toString() method
Use an ArrayList to store the students b/c we don't know the number. (DB isn't a class in java, and an array is counter-intuitive when you don't know what size you'll need)
Create a loop that the user can break out of when they wish to
Obtain user input for the name and age, and use this to construct a student object and add it to the ArrayList
Print out all the students in the ArrayList after the loop
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.
The program should take two inputs and display them. However when i run it, it ask only my Age and then it prints it out. I want that the program would ask also my name.
You are 16 years old
Your name is:
import java.util.Scanner;
public class NIMEVALIK{
int Vanus;
String NIMI;
public void setAge(int vanus){
Vanus = vanus;
}
public void setName(String name){
NIMI = name;
}
public int getAge() {
System.out.println("Your are %s years old: ",Vanus);
return Vanus;
}
public String getName(){
System.out.println("Your name is: " + NIMI);
return NIMI;
}
public static void main(String[]args){
int age;
String name;
NIMEVALIK nimiObject = new NIMEVALIK();
Scanner input = new Scanner(System.in);
System.out.println("Siseta vanus");
age = input.nextInt();
nimiObject.setAge(age);
System.out.println("sisega nimi");
name = input.nextLine();
nimiObject.setName(name);
nimiObject.getAge();
nimiObject.getName();
}
}
Your code:
name = input.nextLine();
Try This :
name = input.next()+input.nextLine();
before this line:
name = input.nextLine();
add:
input.nextLine(); //junk