Java Coding Array List Trouble - java

I am very unexperienced with java and i need help with my school assingment. I am not sure how to get user input. The code was provided to us and we just have to put a ling of code in place of the dotted lines to complete the program but I am stuck.
I have two classes and here they are.
/**
* Write a description of class PhoneBookEntry here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class PhoneBookEntry
{
private String name; // Person's name
private String phoneNumber; // Person's phone number
/**
* The constructor initializes the person's name
* and phone number.
*/
public PhoneBookEntry(String n, String pn)
{
name = n;
phoneNumber = pn;
}
/**
* The setName method sets the person's name.
*/
public void setName(String n)
{
name = n;
}
/**
* setPhoneNumber method sets the person's
* phone number.
*/
public void setPhoneNumber(String pn)
{
phoneNumber = pn;
}
/**
* The getName method returns the person's
* name.
*/
public String getName()
{
return name;
}
/**
* The getPhoneNumber method returns the
* person's phone number.
*/
public String getPhoneNumber()
{
return phoneNumber;
}
}
/**
* Chapter 7
* Lab Assignment: Phone Book ArrayList
* This program demonstrates the PhoneBookEntry class.
*/
public class PhoneBookDemo
{
public static void main(String args[])
{
// Constant for the numer of entries.
final int NUM_ENTRIES = 5;
// Create an ArrayList to hold PhoneBookEntry objects.
ArrayList<PhoneBookEntry> list =
new ArrayList<PhoneBookEntry>();
// Tell the user what's about to happen.
System.out.println("I'm going to ask you to enter " +
NUM_ENTRIES + " names and phone numbers.");
System.out.println();
// Store PhoneBookEntry objects in the ArrayList.
for (int i = 0; i < NUM_ENTRIES; i++)
{
-----------------
System.out.println();
}
System.out.println("Here's the data you entered:");
// Display the data stored in the ArrayList.
for (int i = 0; i < list.size(); i++)
{
System.out.println(list);
}
}
/**
* The getEntry method creates a PhoneBookEntry object
* populated with data entered by the user and returns
* a reference to the object.
*/
public static PhoneBookEntry getEntry()
{
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Variables to hold a person's name and
// phone number.
String name;
String phoneNumber;
// Get the data.
System.out.print("Enter a person's name: ");
name = keyboard.nextLine();
System.out.print("Enter that person's phone number: ");
phoneNumber = keyboard.nextLine();
// Create a PhoneBookEntry object.
PhoneBookEntry entry = new PhoneBookEntry(name, phoneNumber);
// Return a reference to the object.
return entry;
}
/**
* The displayEntry method displays the data stored
* in a PhoneBookEntry object.
*/
public static void displayEntry(PhoneBookEntry entry)
{
System.out.println("------------------------------");
System.out.println("Name: " + entry.getName());
System.out.println("Phone number: " + entry.getPhoneNumber());
}
}

In the loop (the dotted lines) you just need to add:
list.add(getEntry());
The handling of the stream is already implemented in getEntry() method.

Add this stuff to your code:
outside the Main class:
import java.util.Scanner;
inside the main class
Scanner input = new Scanner(System.in);
System.out.println("Asking for input");
String userResponse = input.nextLine();
For an Int rather than a string:
Int userResponse = input.nextInt();
The program will pause and wait for an input. Then, your userResponse will now contain what the user typed in.

Related

storing arraylist, phonebookdemo program(Need two more lines)?

I need to fill in the blanks on a phone book entry and phone book demo class. I've filled them all in except for two of them in the demo class, the parts that I need to fill in are represented by question marks.
PhoneBookEntry:
public class PhoneBookEntry
{
private String name; // Person's name
private String phoneNumber; // Person's phone number
/**
* The constructor initializes the person's name
* and phone number.
*/
public PhoneBookEntry(String n, String pn)
{
name = n;
phoneNumber = pn;
}
/**
* The setName method sets the person's name.
*/
public void setName(String n)
{
name = n;
}
/**
* setPhoneNumber method sets the person's
* phone number.
*/
public void setPhoneNumber(String pn)
{
phoneNumber = pn;
}
/**
* The getName method returns the person's
* name.
*/
public String getName()
{
return name;
}
/**
* The getPhoneNumber method returns the
* person's phone number.
*/
public String getPhoneNumber()
{
return phoneNumber;
}
}
I filled in the blanks on that one, in the PhoneBookDemo I don't have a clue on what to put in the spaces with the question marks:
public class PhoneBookDemo
{
public static void main(String args[])
{
// Constant for the numer of entries.
final int NUM_ENTRIES = 5;
// Create an ArrayList to hold PhoneBookEntry objects.
ArrayList<PhoneBookEntry> list =
new ArrayList<PhoneBookEntry>();
// Tell the user what's about to happen.
System.out.println("I'm going to ask you to enter " +
NUM_ENTRIES + " names and phone numbers.");
System.out.println();
// Create and store PhoneBookEntry objects in the ArrayList.
for (int i = 0; i < NUM_ENTRIES; i++)
{
???????
System.out.println();
}
System.out.println("Here's the data you entered:");
// Display the data stored in the ArrayList.
for (int i = 0; i < list.size(); i++)
{
????????????
}
}
/**
* The getEntry method creates a PhoneBookEntry object
* populated with data entered by the user and returns
* a reference to the object.
*/
public static PhoneBookEntry createEntry()
{
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Variables to hold a person's name and
// phone number.
String name;
String phoneNumber;
// Get the data.
System.out.print("Enter a person's name: ");
name = keyboard.nextLine();
System.out.print("Enter that person's phone number: ");
phoneNumber = keyboard.nextLine();
// Create a PhoneBookEntry object.
PhoneBookEntry entry = new PhoneBookEntry(name, phoneNumber);
// Return a reference to the object.
return entry;
}
/**
* The displayEntry method displays the data stored
* in a PhoneBookEntry object.
*/
public static void displayEntry(PhoneBookEntry entry)
{
System.out.println("------------------------------");
System.out.println("Name: " + entry.getName());
System.out.println("Phone number: " + entry.getPhoneNumber());
}
}
You can use the two methods in your code which are not used
// Create and store PhoneBookEntry objects in the ArrayList.
for (int i = 0; i < NUM_ENTRIES; i++)
{
list.add (createEntry());
}
and
for (int i = 0; i < list.size(); i++)
{
displayEntry(list.get(i));
}
Create and store : call the method that create an instance, and add it to the list
for (int i = 0; i < NUM_ENTRIES; i++){
PhoneBookEntry create = createEntry();
list.add(create);
System.out.println();
}
Display : call the displayEntry method on each element, but the best way is to implement the toString() method in the PhoneBookEntry class and use a System.out.println(list.get(i));
for (int i = 0; i < list.size(); i++){
displayEntry(list.get(i));
}
Take a look at following code:
public class PhoneBookDemo {
public static void main(String args[]) {
// Constant for the numer of entries.
final int NUM_ENTRIES = 5;
// Create an ArrayList to hold PhoneBookEntry objects.
ArrayList<PhoneBookEntry> list
= new ArrayList<PhoneBookEntry>();
// Tell the user what's about to happen.
System.out.println("I'm going to ask you to enter "
+ NUM_ENTRIES + " names and phone numbers.");
System.out.println();
// Create and store PhoneBookEntry objects in the ArrayList.
for (int i = 0; i < NUM_ENTRIES; i++) {
list.add(createEntry());
}
System.out.println("Here's the data you entered:");
// Display the data stored in the ArrayList.
for (int i = 0; i < list.size(); i++) {
displayEntry(list.get(i));
}
}
/**
* The getEntry method creates a PhoneBookEntry object populated with data
* entered by the user and returns a reference to the object.
*/
public static PhoneBookEntry createEntry() {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Variables to hold a person's name and
// phone number.
String name;
String phoneNumber;
// Get the data.
System.out.print("Enter a person's name: ");
name = keyboard.nextLine();
System.out.print("Enter that person's phone number: ");
phoneNumber = keyboard.nextLine();
// Create a PhoneBookEntry object.
PhoneBookEntry entry = new PhoneBookEntry(name, phoneNumber);
// Return a reference to the object.
return entry;
}
/**
* The displayEntry method displays the data stored in a PhoneBookEntry
* object.
*/
public static void displayEntry(PhoneBookEntry entry) {
System.out.println("------------------------------");
System.out.println("Name: " + entry.getName());
System.out.println("Phone number: " + entry.getPhoneNumber());
}
}
public class PhoneBookEntry {
private String name;
private String phoneNumber;
public PhoneBookEntry() {
}
public PhoneBookEntry(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the phoneNumber
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* #param phoneNumber the phoneNumber to set
*/
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
I think you should not hold phone book's entires apart from phone bool. Do incapsulate this logic into the phone book:
public final class PhoneBook {
private final Map<String, Entry> entries = new TreeMap<>();
public void add(String name, String phoneNumber) {
entries.put(name, new Entry(name, phoneNumber));
}
public Iterator<Entry> iterator() {
return entries.values().iterator();
}
public static final class Entry {
private final String name;
private final String phoneNumber;
public Entry(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
}
}
Then you can define method, that ask user for phone book entries and retrieves the whole phone book instead of list of phone book's entreis:
public static PhoneBook getPhoneBook(int totalEntries) {
try (Scanner scan = new Scanner(System.in)) {
PhoneBook phoneBook = new PhoneBook();
System.out.println("I'm going to ask you to enter " + totalEntries + " names and phone numbers.");
System.out.println();
for (int i = 1; i <= totalEntries; i++) {
System.out.println("Entry " + i + ':');
System.out.print("Enter a person's name: ");
String name = scan.nextLine();
System.out.print("Enter that person's phone number: ");
String phoneNumber = scan.nextLine();
System.out.println();
phoneBook.add(name, phoneNumber);
}
return phoneBook;
}
}
Finally you can use this method to get a phone book and print all entires:
final int totalEntries = 5;
getPhoneBook(totalEntries).iterator().forEachRemaining(entry -> {
System.out.println("------------------------------");
System.out.println("Name: " + entry.getName());
System.out.println("Phone number: " + entry.getPhoneNumber());
});
//iterate over number of entries
for (int i = 0; i < NUM_ENTRIES; i++)
{
//add to the phonebooklist
list.add (createEntry());
System.out.println();
}
System.out.println("Here's the data you entered:");
// Display the data stored in the ArrayList.
for (int i = 0; i < list.size(); i++)
{
//display entry from list
displayEntry(list.get(i));
//use display entry method for display
}

How to use an object, save the value into an arrayList, and reuse the same object to keep getting user input

I am trying to create a SavingsAccount object and then use a method create account to take user inputs (account name, account number, and starting balance) and then store that information into an arrayList to access later.
I was thinking that I could just have one instance of the object (Savings account) save the data into the arrayList and then reuse the object so that I do not have multiple objects ( was thinking this would be more memory efficient).
I am new to Java, and this is homework, I have posted my code below that I have so far. I also am not exactly sure how I should be using the toString method in order to later print out a list of all the accounts that have been created.
The main problem I am having is how to store the objects data into the arrayList I know to use the .add() however, it seems to be overwriting all the information stored into the array with the last value entered. So I unsure how to do this, I have read many posts here that are on the same topic or something similar and still do not understand the correct way to do this.
I would welcome any guidance or advice, thank you for taking the time to read my post.
package bankingSystem;
/**
*
* #author xxxx
*
*/
public class SavingsAccount {
private String accountNumber;
private String accountName;
private double accountBalance;
/**
* Constructor to create a new savings account object that takes in a new
account number and a new account name
* #param newAccountNumber
* #param newAccountName
*/
public SavingsAccount(String newAccountNumber, String newAccountName){
this.accountNumber = newAccountNumber;
this.accountName = newAccountName;
this.accountBalance = 0;
}
/**
* Creates a new savings account with passed in data of new account name,
number, and starting balance.
* #param newAccountNumber
* #param newAccountName
* #param startingAccountBalance
* #return true always as the information is stored in an arrayList and
will not fill up.
*/
public SavingsAccount(String newAccountNumber, String newAccountName,
double startingAccountBalance){
this.accountNumber = newAccountNumber;
this.accountName = newAccountName;
this.accountBalance = startingAccountBalance;
}
/**
* Gets the banking account number
* #return the bank account number
*/
public String getAccountNumber(){
return accountNumber;
}
/**
* Gets the requested account name
* #return
*/
public String getAccountName(){
return accountName;
}
/**
* Gets the requsted account balance
* #return the account balace;
*/
public double getAccountBalance(){
return accountBalance;
}
/**
* Changes a bank account name.
* #param updateAccountName
* #return the updated value for accountName
*/
public String setAccountName(String updateAccountName){
accountName = updateAccountName;
return accountName;
}
/**
* Deposit funds into account.
* #param depositAmount
* #return true, as this would always be true for a realistic amount.
*/
public boolean deposit(double depositAmount){
accountBalance += depositAmount;
return true;
}
/**
* withdraws the specified amount of funds from the account.
* #param withdrawlAmount
* #return true if successful, else return false if there is an ISF
transaction.
*/
public boolean withdrawl(double withdrawlAmount){
if(accountBalance - withdrawlAmount < 0){
return false;
}else{
accountBalance -= withdrawlAmount;
return true;
}
}
#Override
public String toString(){
StringBuilder results = new StringBuilder();
results.append("The account number is " + accountNumber + " The
account name is " + accountName + " The account balance is " +
accountBalance + "\n");
return results.toString();
}
}
package bankingSystem;
import java.util.Scanner;
import java.util.ArrayList;
/**
*
* #author xxxx
*
*/
public class BankingSystem {
public static void main(String[] args) {
ArrayList<SavingsAccount> arrayOfSavingsAccounts = new \
ArrayList<SavingsAccount>();
int totalNumberOfAccounts = 0;
Scanner input = new Scanner(System.in);
int menuSelection = 0;
do{
System.out.println("\nPlease select from the following options: \n1.
Create a new account\t\t\t2. Deposit funds\n3. Withdrawl funds\t\t\t\t4.
Transfer funds between accounts\n5. Display all accounts\t\t\t6. Exit
Program\n");
if (input.hasNextInt()){
int temp = input.nextInt(); //used a temp variable to compare the
if statement below
if (temp > 0 && temp < 7){
menuSelection = temp;
}else{
System.err.println("INVALID ENTRY, Please try again");
}
}else{
System.err.println("INVALID ENTRY, Please try again");
}
input.nextLine(); //used this to clear the value being held in
scanner
}
while (menuSelection < 1 || menuSelection > 6);
switch (menuSelection){
case 1: System.out.println("\t\t\t\tCREATE NEW ACCOUNT:\nPlease enter
the account holders name: \n");
String AccountName = input.nextLine();
System.out.println("Please enter an account number: ");
String AccountNumber = input.nextLine();
if (totalNumberOfAccounts == 0){
//search for duplicate account number
}
System.out.println("Please enter starting account balance e.g.
2500.50 :");
double startingAccountBalance = input.nextDouble();
SavingsAccount createSavingsAccount = new
SavingsAccount(AccountNumber, AccountName, startingAccountBalance);
arrayOfSavingsAccounts.add(createSavingsAccount);
SavingsAccount createSavingsAccount = new
}
}
}
You don't need the last line:
SavingsAccount createSavingsAccount = new SavingsAccount(AccountNumber, AccountName, startingAccountBalance);
because you initialize a new instance just remove it and then any new operation will overwrite the object old values just it.
Have you thought about just creating an array of SavingAccounts with a fixed number of accounts?
SavingAccounts[] savingArray;
savingsArray = new SavingAccounts[10];
Since the value stored into the ArrayList is a reference(to the memory location of the object), you must create a new object or all the instances of that referenced object in the ArrayList will be of the same value.
I changed my code to create a new object each time a new account was created and then store the value of the newly created object.
Thank you everyone for your assistance.

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.

How do I run a for loop to display different elements of an array?

For my class we have to put stock information into the elements of an array and display the percentage of change for each stock with its symbol. I have it working to where it will print the first object five times verses the five objects once like its suppose to be.
Here's my code (The instructions are in the comments):
import java.util.Scanner;
public class StockTest{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
/*
Make sureto complete the Stock class before you do the following items.
*/
/* Step 1:
* Instantiate two Stock objects with arguments of your choice(stock symbol and name).
* Using two set methods set the previousClosingPrice and curentPrice of two Stocks.
* Display the percentage changed from previousClosingPrice to curentPrice of both stocks.
*/
System.out.println("Input stock symbol");
String symbol = input.next();
System.out.println("Input stock name");
String name = input.next();
Stock stock = new Stock(symbol, name);
System.out.println("Input previous price");
Stock.setPreviousClosingPrice(input.nextDouble());
System.out.println("Input current price");
Stock.setCurrentPrice(input.nextDouble());
System.out.println("the change percentage of the stock is " + Stock.getChangePercent() + "%");
/*
* Step 2: Declare an array of 5 Stock objects. (Next three steps should be done in a loop)
* Ask the user to input stock symbol, name, previousClosingPrice and curentPrice.
* Initialize an array element with new Stock object using symbol and name that user input.
* Using two set methods set the previousClosingPrice and curentPrice of each Stock element
*/
Stock[] stockArray = new Stock[5];
for(int i = 0; i < stockArray.length; i++){
System.out.println("Please input stock symbol, name, previous price, and current price");
String stockSymbol = input.next();
String stockName = input.next();
stockArray[i] = new Stock(symbol, name);
Stock.setPreviousClosingPrice(input.nextDouble());
Stock.setCurrentPrice(input.nextDouble());
}
/*
* Step 4: (this step should be done in a loop)
* Display the percentage changed from previousClosingPrice to curentPrice of all stocks with their symbol.
*/
for (int i = 0; i < stockArray.length; i++){
System.out.println("Percentage changed of " + symbol + " " + Stock.getChangePercent());
}
}
}
You are using the wrong variables for initializing the Stock instances.
Change
String stockSymbol = input.next();
String stockName = input.next();
stockArray[i] = new Stock(symbol,name);
to
String stockSymbol = input.next();
String stockName = input.next();
stockArray[i] = new Stock(stockSymbol,stockName);
It's not clear what's the purpose of the first Stock instance you create (Stock stock = new Stock(symbol, name);), since you don't do anything with it after initializing it.
I could see few problems with your code :
Creating and storing Stock object in array directly as done in below line will have overhead as you also need to update remaining properties for the same object.
stockArray[i] = new Stock(symbol, name);
Using static methods to update object properties doesn't make sense.
Stock.setPreviousClosingPrice(input.nextDouble());
Stock.setCurrentPrice(input.nextDouble());
Again Scanner methods need to be used carefully.
I tried correcting code as per comments:
StockTest class:
import java.util.Scanner;
public class StockTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/*
* Make sureto complete the Stock class before you do the following
* items.
*/
/*
* Step 1: Instantiate two Stock objects with arguments of your
* choice(stock symbol and name). Using two set methods set the
* previousClosingPrice and curentPrice of two Stocks. Display the
* percentage changed from previousClosingPrice to curentPrice of both
* stocks.
*/
System.out.println("Input stock symbol");
String symbol = input.nextLine();
System.out.println("Input stock name");
String name = input.nextLine();
Stock stock1 = new Stock(symbol, name);
System.out.println("Input previous price");
stock1.setPreviousClosingPrice(Double.parseDouble(input.nextLine()));
System.out.println("Input current price");
stock1.setCurrentPrice(Double.parseDouble(input.nextLine()));
System.out.println("Input stock symbol");
symbol = input.nextLine();
System.out.println("Input stock name");
name = input.nextLine();
Stock stock2 = new Stock(symbol, name);
System.out.println("Input previous price");
stock2.setPreviousClosingPrice(Double.parseDouble(input.nextLine()));
System.out.println("Input current price");
stock2.setCurrentPrice(Double.parseDouble(input.nextLine()));
System.out.println("the change percentage of the stock is "
+ stock1.getChangePercent() + "%");
System.out.println("the change percentage of the stock is "
+ stock2.getChangePercent() + "%");
/*
* Step 2: Declare an array of 5 Stock objects. (Next three steps should
* be done in a loop) Ask the user to input stock symbol, name,
* previousClosingPrice and curentPrice. Initialize an array element
* with new Stock object using symbol and name that user input. Using
* two set methods set the previousClosingPrice and curentPrice of each
* Stock element
*/
Stock[] stockArray = new Stock[2];
for (int i = 0; i < stockArray.length; i++) {
System.out
.println("Please input stock symbol, name, previous price, and current price");
symbol = input.nextLine();
name = input.nextLine();
Stock stock = new Stock(symbol, name);
stock.setPreviousClosingPrice(Double.parseDouble(input.nextLine()));
stock.setCurrentPrice(Double.parseDouble(input.nextLine()));
stockArray[i] = stock;
}
/*
* Step 4: (this step should be done in a loop) Display the percentage
* changed from previousClosingPrice to curentPrice of all stocks with
* their symbol.
*/
for (Stock stock : stockArray) {
System.out.println("Percentage changed of " + stock.getSymbol()
+ " " + stock.getChangePercent() + "%");
}
}
}
Stock class
public class Stock {
private String name;
private String symbol;
private double previousClosingPrice;
private double currentPrice;
public Stock(String symbol, String name) {
this.symbol = symbol;
this.name = name;
}
public String getName() {
return this.name;
}
public String getSymbol() {
return this.symbol;
}
public void setCurrentPrice(double currentPrice) {
this.currentPrice = currentPrice;
}
public void setPreviousClosingPrice(double previousClosingPrice) {
this.previousClosingPrice = previousClosingPrice;
}
public double getChangePercent() {
return (this.currentPrice / this.previousClosingPrice - 1) * 100;
}
}

Getting java.lang.NumberFormatException When Outputting

I am using BlueJ, for reference.
The program compiles fine. It runs fine as well except that this:
java.lang.NumberFormatException: For input string: "Washington,George"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at WorkerApp.main(WorkerApp.java:53)
at __SHELL112.run(__SHELL112.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at bluej.runtime.ExecServer$3.run(ExecServer.java:730)
Specifically highlighting:
java.lang.NumberFormatException: For input string: "Washington,George"
at WorkerApp.main(WorkerApp.java:53)
The point of this program is to read a text file and add to said text file.
The program is supposed to read and open "EmployeeData.txt":
S Washington,George 000001 125000
H MacDonald,Ronald 386218 7.80 true 40
H Walton,Samuel 268517 8.21 false
H Thomas,David 131313 9.45 true 38
H Sanders,HarlandDavid 277651 8.72 false
S Baron,James 368535 310236
When I click on the exception it highlights this from my main class
double salary = Double.parseDouble(Employee[3]);
This is the full main class WorkerApp in which I am trying to read and open the text file:
import java.io.*;
import java.util.*;
public class WorkerApp{
/**
* Reads the infile, runs tests, and prints the output.
*/
public static void main (String args[]){
Company company = new Company();
try{
Scanner reader = new Scanner (new File("EmployeeData.txt"));
while(reader.hasNext()){
String line = reader.nextLine();
String Employee[] = line.split(" ");
String sorh = Employee[0];
String name = Employee[1];
String id = Employee[2];
double salary = Double.parseDouble(Employee[3]);
Employee e;
if (Employee[0].equals("S")){
e = new SalariedWorker(sorh, name, id, salary);}
else {
boolean overtime = Boolean.parseBoolean(Employee[4]);
if(overtime){
int maxHours = Integer.parseInt(Employee[5]);
e = new HourlyWorker(sorh, name, id, salary, maxHours);
}
else{
e = new HourlyWorker(sorh, name, id, salary);
}
}
company.add(e);
}
}catch (Exception err){
//System.out.println(err);
err.printStackTrace();
}
company.print();
System.out.println();
//Test Number 1
System.out.println("1) Add a salaried worker");
SalariedWorker SWorker1 = new SalariedWorker("S", "Moran,Blake", "123456", 260000);
company.add(SWorker1);
company.print();
//Test Number 2
System.out.println("2) Add an hourly worker who has no overtime allowed");
HourlyWorker HWorker1 = new HourlyWorker("H", "Bob,Billy", "654321", 15);
company.add(HWorker1);
company.print();
//Test Number 3
System.out.println("3) Add an hourly worker who has overtime allowed");
HourlyWorker HWorker2 = new HourlyWorker("H", "Smith,Will", "345612", 10.5, 30);
company.add(HWorker2);
company.print();
//Test Number 4
System.out.println("4) Add a worker that is already in the database");
try{
company.add(SWorker1);
}catch(Exception err){
System.out.println(err);
System.out.println();
}
//Test Number 5
System.out.println("5) Print the sorted list");
company.print();
//Test Number 6
System.out.println("6) Remove a worker who is NOT in the list");
company.remove("Brooks,Phil");
System.out.println();
//Test Number 7
System.out.println("7) Remove a worker who is the first in the list ");
company.remove("Moran,Blake");
company.print();
System.out.println();
//Test Number 8
System.out.println("8) Find a worker who is the middle of the list");
int index = company.find("Bob,Billy");
System.out.println("Found at "+ index);
System.out.println();
//Test Number 9
System.out.println("9) Find a worker who is NOT in the list");
index = company.find("Harrison,Ford");
System.out.println("Found at "+ index);
System.out.println();
//Test Number 10
System.out.println("10) Find the weekly salary of a worker who is salaried");
System.out.println(SWorker1.FindSalary());
System.out.println();
//Test Number 11
System.out.println("11) Find the weekly salary of an hourly worker who has no overtime allowed [50 hours]");
System.out.println(HWorker1.FindSalary(50));
System.out.println();
//Test Number 12
System.out.println("12) Find the weekly salary of an hourly worker who has overtime allowed [50 hours]");
System.out.println(HWorker2.FindSalary(50));
System.out.println();
//Test Number 13
System.out.println("13) Find the weekly salary of an hourly worker who has overtime allowed [20 hours]");
System.out.println(HWorker2.FindSalary(20));
System.out.println();
//Test Number 14
System.out.println("14) Print the sorted list");
company.print();
//Test Number 15
System.out.println("\n15) End the process");
}
}
It should be noted that on top of the exception it spits out this output:
1) Add a salaried worker
S Moran,Blake 123456 260000.0
2) Add an hourly worker who has no overtime allowed
S Moran,Blake 123456 260000.0
H Bob,Billy 654321 15.0 false
3) Add an hourly worker who has overtime allowed
S Moran,Blake 123456 260000.0
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
4) Add a worker that is already in the database
java.lang.RuntimeException: The Employee Is Not New
5) Print the sorted list
S Moran,Blake 123456 260000.0
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
6) Remove a worker who is NOT in the list
The Employee is not Found
7) Remove a worker who is the first in the list
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
8) Find a worker who is the middle of the list
Found at 0
9) Find a worker who is NOT in the list
Found at -1
10) Find the weekly salary of a worker who is salaried
5000.0
11) Find the weekly salary of an hourly worker who has no overtime allowed [50 hours]
750.0
12) Find the weekly salary of an hourly worker who has overtime allowed [50 hours]
630.0
13) Find the weekly salary of an hourly worker who has overtime allowed [20 hours]
210.0
14) Print the sorted list
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
15) End the process
If it helps, here are my other classes for reference, as they might be the source of the problem.
Company:
import java.io.*;
import java.util.*;
public class Company{
private Employee[] employeeArray;
private final int InitialCapacity = 7;
private int employCount;
/**
* Creates the employee array and sets employCount to 0.
*/
public Company(){
employeeArray = new Employee[InitialCapacity];
employCount = 0;
}
/**
* Finds an employee in the list.
*/
public int find(String name){
for (int i = 0; i < employCount; i++){
if (employeeArray[i].getName().equals(name)){
return i;
}
}
return -1;
}
/**
* Adds an employee to the list.
*/
public int add(Employee employ){
int index;
for (index = 0; index < employCount; index++){
int result = employeeArray[index].getName().compareTo(employ.getName());
if(result == 0){
throw new RuntimeException ("The Employee Is Not New");
}
}
if (employeeArray.length == employCount){
expand();
}
employeeArray[index] = employ;
employCount++;
return index;
}
/**
* Removes an employee to the list.
*/
public void remove(String name){
int index = find(name);
if (index == -1){
System.out.println("The Employee is not Found");
return;
}
for (int i = index; i < employCount - 1; i++){
employeeArray[i] = employeeArray[i + 1];
}
employCount--;
}
/**
* Prints the list.
*/
public void print(){
if(employCount == 0){
System.out.println("The List is Empty");
return;
}
for(int i = 0; i < employCount; i++){
System.out.println(employeeArray[i]);
}
}
/**
* Expands the list.
*/
private void expand(){
Employee[] newArray = new Employee[employeeArray.length + InitialCapacity];
for (int i = 0; i < employeeArray.length; i++){
newArray[i] = employeeArray[i];
}
employeeArray = newArray;
}
}
Employee:
import java.io.*;
import java.util.*;
public class Employee{
private String SorH;
private String name;
private String ID;
/**
* Sets sets SorH, name, and ID to SH, n, and id.
*/
public Employee (String SH, String n, String id){
SorH = SH;
name = n;
ID = id;
}
/**
* Gets the first part (S or H) of the employee list.
*/
public String getSorH(){
return SorH;
}
/**
* Gets the name of the employee list.
*/
public String getName(){
return name;
}
/**
* Gets the ID of the employee list.
*/
public String getID(){
return ID;
}
/**
* Sets SorH to SH.
*/
public void setSorH(String SH){
SorH = SH;
}
/**
* Sets name to n.
*/
public void setName(String n){
name = n;
}
/**
* Sets ID to id.
*/
public void setID(String id){
ID = id;
}
/**
* Returns a string representing the employee list.
*/
public String toString(){
return String.format("%s %s %s", getSorH(), getName(), getID());
}
}
HourlyWorker:
import java.io.*;
import java.util.*;
public class HourlyWorker extends Employee{
private double hourlySalary;
private boolean overtime;
private int maxHours;
/**
* Contains the super and sets the hourly salary and maxHours to hourlySal and maxH and
* overtime to true.
*/
public HourlyWorker(String SH, String n, String id, double hourlySal, int maxH){
super(SH, n, id);
hourlySalary = hourlySal;
overtime = true;
maxHours = maxH;
}
/**
* Contains the super and sets the hourly salary to hourlySal and overtime to false.
*/
public HourlyWorker(String SH, String n, String id, double hourlySal){
super(SH, n, id);
hourlySalary = hourlySal;
overtime = false;
}
/**
* Returns if overtime is true or false.
*/
public boolean overtime(){
return overtime;
}
/**
* Gets the max hours of an hourly worker.
*/
public int getmaxH(){
return maxHours;
}
/**
* Gets the hourly salary of an hourly worker.
*/
public double gethourlySalary(){
return hourlySalary;
}
/**
* Sets hourly salary to hSalary.
*/
public void sethourlySalary (double hSalary){
hourlySalary = hSalary;
}
/**
* Finds the weekly salary of an hourly worker.
*/
public double FindSalary(double hoursWorked){
if (overtime){
if (hoursWorked <= maxHours){
return hoursWorked * hourlySalary;
} else{
return maxHours * hourlySalary +
(hoursWorked - maxHours) * hourlySalary * 1.5;
}
} else{
return hoursWorked * hourlySalary;
}
}
/**
* Contains the super string and adds onto the string.
*/
public String toString(){
String str = super.toString() + String.format(" %s %s", gethourlySalary(),overtime());
if (overtime){
str = str + String.format(" %s", getmaxH());
}
return str;
}
}
SalariedWorker:
import java.io.*;
import java.util.*;
public class SalariedWorker extends Employee{
private double yearlySalary;
/**
* Contains the super and sets yearly salary to ySalary.
*/
public SalariedWorker(String SH, String n, String id, double ySalary){
super(SH, n, id);
yearlySalary = ySalary;
}
/**
* Gets the yearly salary of a salaried worker.
*/
public double getyearlySalary(){
return yearlySalary;
}
/**
* Sets the yearly salary of a salaried worker.
*/
public void setyearlySalary(double ySalary){
yearlySalary = ySalary;
}
/**
* Finds the weekly salary of a salaried worker.
*/
public double FindSalary(){
return yearlySalary / 52;
}
/**
* Contains the super string and adds onto the string.
*/
public String toString(){
return super.toString() + String.format(" %s", getyearlySalary());
}
}
Thank you in advance!
Instead of line.split(" "); you might want to try line.split("\\s+"). I think the splitting is not happening properly.
Don't you have access to a debugger ? There should be one in any IDE you can use, be it Netbeans, Eclipse, IntelliJ or ...
Just put a breakpoint on the line where exception occurs and look at the values in the Employee array. The cause of the error should then be self evident.
In case it is still not evident for you, here is next clue : read again the javadoc for String.split() and compare with what you have in Employee.

Categories

Resources