I am making a function that gets the students' Id, score, last name, and first name and compares them according to their Score, then the last name, and then the first name and prints the result in the descending format.
I have used a Comparator to compare the elements of the array. The problem is that when the user enters -1 as score or ID, the program needs to break and show the result but when I use break, it will add a null value to my array which prevents comparing.
This is my code:
import java.util.Arrays;
import java.util.Scanner;
import java.util.*;
public class Main {
private static class Student {
String fName;
String lName;
int id;
int score;
public Student(String fName, String lName, int id, int score) {
this.fName = fName;
this.lName = lName;
this.id = id;
this.score = score;
}
public int getScore() {
return score;
}
public String getFirstName() {
return fName;
}
public String getLastName() {
return lName;
}
public int getId() {
return id;
}
#Override
public String toString() {
return "id: " + this.id + " " + "fName: " + this.fName + " " + "lName: " + this.lName + " " + "score: " + this.score;
}
}
public static boolean alphabetic(String str) {
char[] charArray = str.toCharArray();
for (char c : charArray) {
if (!Character.isLetter(c)) {
if (c != ' ') {
return false;
}
}
}
return true;
}
static class Comparators implements Comparator<Student> {
#Override
public int compare(Student s1, Student s2) {
int n = Integer.compare(s2.getScore(), s1.getScore());
if (n == 0) {
int last = s1.getLastName().compareTo(s2.getLastName());
return last == 0 ? s1.getFirstName().compareTo(s2.getFirstName()) : last;
} else {
return n;
}
}
}
public static void main(String[] args) {
System.out.println("Enter the number of students");
Scanner input = new Scanner(System.in);
HashSet<Integer> used = new HashSet<>();
List<List<Object>> listData = new ArrayList<List<Object>>();
int k = input.nextInt();
Student[] students = new Student[k];
for (int i = 0; i < k; ) {
System.out.println("Enter id");
int id = input.nextInt();
if (id == -1) {
break;
}
input.nextLine();
System.out.println("Enter first name ");
String fName;
while (alphabetic(fName = input.nextLine()) == false) {
System.out.println("Wrong! please enter again");
}
fName = fName.replace(" ", "");
System.out.println("Enter last name ");
String lName;
while (alphabetic(lName = input.nextLine()) == false) {
System.out.println("Wrong! please enter again");
}
lName = lName.replace(" ", "");
System.out.println("Enter score ");
int score = input.nextInt();
if (score == -1) {
break;
}
if (used.contains(id)) {
listData.add(Arrays.asList(id, lName, fName, score));
continue;
}
used.add(id);
students[i++] = new Student(fName, lName, id, score);
}
Arrays.toString(students);
System.out.println(Arrays.toString(students));
Arrays.sort(students, new Comparators());
Arrays.toString(students);
System.out.println("Data without duplication:");
for (int i = 0; i < k; i++) {
System.out.println(students[i]);
}
if (listData.toArray().length == 0) {
System.out.println("No duplicated Data");
} else {
System.out.println("Data with duplication:");
System.out.println("ID/ LastName/Name/ Score");
System.out.println(Arrays.toString(listData.toArray()));
}
I have tried nullhandlingExpectation methods but I could not get the result I want.
Is there any method to avoid adding the null value to the array while breaking, or remove the null from the array before comparing?
you can put it inside a while loop and put all your code in it and put the condition of breaking it if the value is -1
Note, your array is of predefined size k:
Student[] students = new Student[k];
Therefore, if user needs to break input before entering all k values, you have to truncate the array. E.g.:
if (score == -1) {
students = Arrays.copyOf(students, i);
break;
}
But better consider using ArrayList instead of plain array
Related
guys, am doing java programing and try to make a list, but i cannnot let it work as i expected, please help me find out where is wrong.
i have create the code on BlueJ and try to make main and method in different part, but when i try to add a variable in list, it seems added but wont present correctly, and remove method will call error and shut down the whole program
one is :
import java.util.ArrayList;
public class Plane
{
//Create 3 types of variables.
private String name;
private int safelength;
private short station;
private String passengername;
private static int seat;
private static int age;
private ArrayList<Passenger> Passengers;
public Plane(String psgname, int psgseat, int psgage)
{
psgname = passengername;
psgseat = seat;
psgage = age;
Passengers = new ArrayList<Passenger>();
}
public Plane(String planename, int maxlength, short astation)
{
name = planename;
safelength = maxlength;
station = astation;
}
public void addPassenger(Passenger Passenger)
{
Passengers.add(Passenger);
}
public void addPassenger(String passengernames, int pseat, int page)
{
Passengers.add(new Passenger(passengername, seat, page));
}
public Passenger findPassenger(String find)
{
for(Passenger ps : Passengers)
{
if(ps.getpname().contains(find))
{
return ps;
}
}
return null;
}
public int numberofPassenger()
{
return Passengers.size();
}
public void removePassenger(int number)
{
if (number >= 0 && number <numberofPassenger())
{
Passengers.remove(number);
}
}
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
public void setname(String n)
{
name = n;
}
public String getname()
{
return name;
}
public void setsafelength(int s)
{
safelength = s;
}
public int getsafelength()
{
return safelength;
}
public void setstation(short a)
{
station = a;
}
public short getstation()
{
return station;
}
public String toString()
{
String text = "System checked, " + getname() + ", you can prepare yourself at station " + getstation() + " with the maxlength of " + getsafelength() + " metres.";
return text;
}
}
another one is :
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private static String pname;
private static int seat;
private static int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(pname, seat, age);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public static void setpname(String pn)
{
pname = pn;
}
public static String getpname()
{
return pname;
}
}
Problem 1.
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
Here you are printing the value of instance variable,not the passenger's name.To print it, do
System.out.println(Passengers.get(index).getpname());
but this will return null,because your pname is static and you have never initialized its value.For this,change all yor static varibales to non-static.
Problem 2.
Passenger padd = new Passenger(pname, seat, age);
you are storing passenger's name seat age in x y zvariables respectively,butduring the creation of Passenger ,you are using pname seat age variables, which are null.So here do
Passenger padd = new Passenger(x, y, z);
At last,change every static variable and methods to non-static.
Final Solution will look like this,
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private String pname;
private int seat;
private int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(x, y, z);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public void setpname(String pn)
{
pname = pn;
}
public String getpname()
{
return pname;
}
}
I am trying to create a driver class using array list of objects and it requires me to :
Read the book title from the user
Read the book ISBN from the user
Read the book in stock quantity from the user
program should continue to read the book information from the user until all the entries from the user for all the fields are blank or zero.
program will store valid book objects into an ArrayList (only valid objects)
Your program will then print the list all the "valid" Books entered by the user in the reverse order in which the books were entered.
As the user is entering information, the program should give feedback such as reporting that an item has been added to the ArrayList, or reporting any errors found.
Books with invalid entries were not added to the ArrayList, therefore they will not be printed when the ArrayList is printed
Here is my current code so far for my driver: (I'm a bit newb at this so )
edited: with the answer given
Here is what I got now
import java.io.*;
import java.util.*;
public class Bookstore2{
public static void main(String arg[ ]) throws Exception{
Scanner sc = new Scanner(System.in);
int isbn=0;
int quantity = 0;
String title = "";
Book oneBook;
List<Book> bookList = new ArrayList<Book>(); //here
while(true){
System.out.print("Enter title: ");
title = sc.nextLine( );
sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter isbn: ");
isbn = sc.nextInt( );
sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter quantity: ");
quantity = sc.nextInt( );
sc = new Scanner(System.in);
sc = new Scanner(System.in);
System.out.println();
// WRITE YOUR VALIDATION CODE HERE
// Change condition according to your requirements.
if(isbn !=0 && quantity != 0 && title != null && title != "")
{
oneBook = new Book(title, isbn, quantity);
bookList.add(oneBook); //create a list in main
System.out.println("Book added in the list.");
}
else
{
System.out.println("Book not added");
break;
}
}
for(int i = bookList.size()-1; i >= 0; i--){
System.out.println(bookList.get(i));
}
} //main method
} //class
error now averted but it's not utilizing both my exception and book class it seems like
Here is my class and my exception that will be running with the new driver class
-----Class
public class Book{
//instance variables
private String title = "";
private int isbn;
private int quantity;
public Book (String title, int isbn, int quantity)throws BookException{
//constructors
setTitle(title);
setIsbn(isbn);
setQuantity(quantity);
}
public String toString( ){ //toString Method
String s = "";
s = s + "Title: " + this.title + "\nISBN: " + this.isbn + "\nQuantity: " + this.quantity + "\n";
return s;
}
public String getTitle( ){
return this.title;
}
public int getisbn( ){
return this.isbn;
}
public int getquantity( ){
return this.quantity;
}
//mutator methods
public void setTitle(String newtitle )throws BookException{
if(newtitle.length()<1){
BookException be = new BookException( );
be.setMessage("Title cannot be blank");
throw be;
}
else{
this.title=newtitle;
}
}
public void setIsbn(int newisbn)throws BookException{
if (isbn <= 1000 || isbn >= 10000) {
this.isbn = newisbn;
}
else{
BookException be = new BookException( );
be.setMessage("ISBN should be between 1000 and 10000.");
throw be;
}
}
public void setQuantity(int newquantity)throws BookException{
if(newquantity>=0){
this.quantity = newquantity;
}
else{
BookException be = new BookException( );
be.setMessage("Quantity can't be a negative number.");
throw be;
}
}
}
------Exception Class
public class BookException extends Exception {
//instance variable
private String message = "";
public void setMessage(String newMessage) {
this.message = newMessage;
}
public String getMessage() {
return this.message;
}
}
First of all use: while(true) loop to iterate until user entered 0 for all the field.
while(true)
{
// Scanner Code i.e. read input from the user.
if(//check all the inputs)
{
//create a new book and insert it into array list
}
else
{
// If input is 0, break from the loop
}
}
Secondly, Never perform validation in your bean class. Create a separate class or method to validate the inputs. After, input validation only then create a new object.
Hope this will help you.
The correct code :
sc = new Scanner(System.in);
while(true){
System.out.print("Enter title: ");
title = sc.nextLine( );
System.out.println();
System.out.print("Enter isbn: ");
isbn = sc.nextInt( );
System.out.println();
System.out.print("Enter quantity: ");
quantity = sc.nextInt( );
System.out.println();
// WRITE YOUR VALIDATION CODE HERE
// Change condition according to your requirements.
if(isbn !=0 && quantity != 0 && title != null && title != "")
{
oneBook = new Book(title, isbn, quantity);
bookList.add(oneBook); //create a list in main
System.out.println("Book added in the list.");
}
else
{
System.out.println("Book not added");
break;
}
}
for(int i = bookList.size()-1; i >= 0; i--){
System.out.println(bookList.get(i));
}
You posted :
while(title != null || title.equals("0") || isbn != null || isbn != 0 || quantity
isbn is of int type i.e. primitive type how can we compare it with a null.
quantity is also of int type.
Default value of an int i.e. primitive type is 0. And, primitive type can never be compared with null.
Since there is so much confusion on the code, here is a complete solution to the task:
Bookstore.java:
public class Bookstore {
static final Scanner in = new Scanner(System.in);
static List<Book> books = new ArrayList<>();
public static void main(String arg[]) throws Exception {
while (true) {
// read book information
Book book = new Book();
System.out.print("Enter title: ");
book.title = in.nextLine();
System.out.println();
System.out.print("Enter ISBN: ");
book.isbn = readInt();
System.out.println();
System.out.print("Enter quantity: ");
book.quantity = readInt();
System.out.println();
// exit condition: "blank book" entered
if (book.title.isEmpty() && book.isbn == 0 && book.quantity == 0) {
System.out.println("Goodbye!");
break;
}
//validate and add book
try {
validateBook(book);
books.add(book);
System.out.println("Book successfully added to the list.");
} catch (IllegalStateException ex) {
System.err.println("Book is not valid: " + ex.getMessage());
continue;
}
// print book list
for (int i = books.size() - 1; i >= 0; i--) {
System.out.println(books.get(i));
System.out.println();
}
}
}
static int readInt() {
while (true) {
String input = in.nextLine();
if(input.isEmpty()) {
return 0;
}
try {
return Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.err.println("Expected a valid integer: " + input);
}
}
}
static void validateBook(Book book) {
if (book.title == null || book.title.isEmpty()) {
throw new IllegalStateException("Book title must not be blank.");
}
if (book.isbn < 1000 || book.isbn > 10000) {
throw new IllegalStateException("Book ISBN must be between 1000 and 10000.");
}
if (book.quantity < 0) {
throw new IllegalStateException("Book quantity must be positive.");
}
}
}
Book.java:
public class Book {
public String title;
public int isbn;
public int quantity;
#Override
public String toString() {
return String.join("\n",
"Title: " + title,
"ISBN: " + isbn,
"Quantity: " + quantity
);
}
}
I'm involved in a group assignment where we are supposed to create a bank program. This is our first time programming in java. We are stuck and we are having trouble figuring out how to connect our customer and account classes. They both consist of ArrayLists and we want the customer arraylists to contain the accounts. So that if we delete a customer, the accounts that belong to that customer will also be deleted. Can anyone give us a push in the right direction?
This is our main class which contains the bank menu:
package bank6;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class Bankmenu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Customer client = new Customer();
Account bank = new Account();
Account accs = new Account();
Customer cust1, cust2, cust3;
cust1 = new Customer("8905060000", "Henrik");
cust2 = new Customer("8910210000", "Emelie");
cust3 = new Customer("8611040000", "Fredrik");
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
client.addCustomerAr(cust1);
client.addCustomerAr(cust2);
client.addCustomerAr(cust3);
int ChoiceOne = 0;
int CustChoice;
int currentCustomer;
int currentAccount;
int amountC;
int amountD;
int editCust;
String personNummer = null;
String Pnr = "0";
int AdminChoice;
/*prompts the user to set ChoiceOne equal to 1 or 2. Hasnextint checks
if the input is an int. else asks for new input. */
while (ChoiceOne != 1 && ChoiceOne != 2) {
System.out.println("Press 1 to login as customer or 2 to login as admin ");
if (input.hasNextInt()) {
ChoiceOne = input.nextInt();
System.out.println();
} else {
System.out.println("You must enter number 1 or number 2");
input.next();
}//ends else
}//ends while
/*
If the user chooses 1 in the previous question, the user will be sent to
the interface for the customer. User is then asked to enter his social
security number and this number will be checked using the Luhn algoritm. Since
the scanner input is already used we added a new Scanner calleds nexLine
to deal with custPnr as a string.
(http://stackoverflow.com/questions/5032356/using-scanner-nextline)
*/
if (ChoiceOne == 1) {
//boolean quit=false;
while ("0".equals(Pnr)) {
// System.out.println("Welcome customer. Please login by using your birthdate (yymmddnnnn) ");
// Scanner nextLine = new Scanner(System.in);
// Pnr = nextLine.nextLine();
//Luhn.checkLogin(Pnr);
//Här måste en kontroll med Luhn algoritmen göras.
// getUserBirthdate();
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
/* }
Sets "quit" to false and executes quit=true if customer chooses case 0
*/
}
boolean quit = false;
do {
// boolean quit = false;
//System.out.println();
System.out.println("Logged on as " + personNummer);
System.out.println("1. deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
CustChoice = input.nextInt();
switch (CustChoice) {
case 1: //Deposit money
System.out.println(bank.getAccountNumbersFor(personNummer));
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to deposit:");
amountC = input.nextInt();
System.out.println(bank.creditAccount(currentAccount, amountC));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 2://Withdraw money
// System.out.println(bank.getAccNosFor(custPnr));
bank.getAccountNo();
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to withdraw:");
amountD = input.nextInt();
System.out.println(bank.debitAccount(currentAccount, amountD));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 3://Check ballance and accounts
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends if
else if (ChoiceOne == 2) {
while ("0".equals(Pnr)) {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
}
//AdminpNr = input.nextInt();
//Här måste en kontroll av AdminpNr göras med hjälp av Luhn.
boolean quit = false;
do {
System.out.println("1. Add customer");
System.out.println("2. Add account");
System.out.println("3. List customer");
System.out.println("4. List accounts");
System.out.println("5. Remove customer");
System.out.println("6. Remove account");
System.out.print("Your choice, 0 to quit: ");
AdminChoice = input.nextInt();
switch (AdminChoice) {
case 1://add customer
int i = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<String, Customer> testCustomers = new HashMap<String, Customer>();
String name = scan.nextLine();
//System.out.println("Att arbeta på bank ska vara jobbigt, skriv in det igen:");
//String pnummer = scan.nextLine();
String pnummer = name;
System.out.println("Skriv in namn:");
String kundnamn = scan.nextLine();
Customer obj = new Customer(pnummer, kundnamn);
testCustomers.put(name, obj);
client.addCustomerAr(obj);
i++;
} while (i < 2);
break;
case 2://add account
int i2 = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<Long, Account> testAccs = new HashMap<Long, Account>();
Long name = scan.nextLong();
//System.out.println("Skriv in personnummer igen:");
Long own = name;
long bal = 0;
Account obt = new Account(own, bal);
testAccs.put(name, obt);
accs.addAccAr(obt);
i2++;
} while (i2 < 2);
break;
case 3:// List customer and accounts
for (String info : client.getAllClients()) {
System.out.println(info);
}
break;
case 4:
for (Long infoAcc : accs.getAllAccounts()) {
System.out.println(infoAcc);
}
break;
case 5:
// ta bort kund
break;
case 6:
// ta bort konto
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends else if
}//ends main
/* private static void getUserBirthdate() {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner (System.in);
String personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
}
*/
}//ends class
This is our Account class;
package bank6;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class Account {
private ArrayList accounts;
private Object lastAcc;
public String customerSocial;
private Integer balance;
private Integer accountNumber;
private Customer owner;
private Account Customer6; // Association customer/account.
private ArrayList<Account> myAccounts = new ArrayList<Account>();
public Integer deposit;
public Integer withdraw;
static Integer accountNo = 1010;
private Long persnr;
private long balans = 0;
/*Constructor.. A account cannot exist unless it is owned by a customer*/
public Account(Customer owner, Integer balance) {
this.owner = owner;
this.balance = balance;
accountNumber = accountNo++;
}
public Account() {
accounts = new ArrayList();
}
public Account(Long persnr, long balans) {
this.persnr = persnr;
this.balans = balans;
accountNumber = accountNo++;
}
public Integer getAccountNo() {
return accountNumber;
}
public String getOwner() {
return owner.getName();
}
public Customer getOwn() {
return owner;
}
public Integer getBalance() {
return balance;
}
//credits the account with an amount of money and returns a string
public String credit(Integer anAmount) {
balance += anAmount;
// return "Account number " + accountNumber + " Has been credited with "+anAmount + " kr.";
return " " + anAmount + " kr has been deposited to " + accountNumber + "\n";
}
public boolean canDebit(Integer anAmount) {
return anAmount <= balance;
}
public String debit(Integer anAmount) {
if (this.canDebit(anAmount)) {
balance -= anAmount;
return " " + anAmount + " kr has been withdrawn from " + accountNumber + "\n";
} else {
return "Account number" + accountNo + "has insufficient funds to debit"
+ anAmount;
}
}
public void addNewAccount(Customer customer) {
accounts.add(new Account(customer, 0));
lastAcc = accounts.get(accounts.size() - 1);
System.out.println("*** New account created. ***" //+ lastAcc
+ "\n");
}
public String removeAccount(int accountNumber) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
found = true; //there is a match stop the loop
if (account.getBalance() == 0) {
iter.remove();//remove this account object
results = "Account number " + accountNumber + " has been removed";
} else {
results = "Account number " + accountNumber + " cannot be removed"
+ "as it has a balance of: " + account.getBalance();
}
}//ends if there is a match
}// end while loop
if (!found) {
results = "No such account";
}
return results;
}
public String creditAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.credit(anAmount);
found = true;//stop the loop
}
}
if (!found) {
results = "No such customer";
}
return results;
}
public String debitAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.debit(anAmount);
found = true;
}
}
if (!found) {
results = "No such Customer";
}
return results;
}
public String getAccountNumbersFor(String CustomerName) {
String details = CustomerName + " has the followinng accounts: "
+ "\n\n";
Iterator iter = accounts.iterator();
//visit all of the accounts in the ArrayList
while (iter.hasNext()) {
Account account = (Account) iter.next();
if (account.getOwner().equals(CustomerName)) {
details += " Account number " + account.getAccountNo()
+ " Balance " + account.getBalance() + "kr \n";
}//ends if
}//ends while
return details;
}
public String bankAccounts() {
String details = "ALL BANK ACCOUNTS" + "\n"
+ "-----------------" + '\n';
if (accounts.size() == 0) {
details += "There are no bank accounts";
} else {
Iterator iter = accounts.iterator();
while (iter.hasNext()) {
details += iter.next().toString() + '\n';
}
}
return details;
}
#Override
public String toString() {
return "Account " + accountNumber + ": " + owner
+ "\nBalance: " + balance + " kr.\n";
}
public Boolean authenticateUser(String login, String ssn) {
if (Luhn.checkLogin(ssn)) {
System.out.println("User authenticated");
return true;
} else {
System.out.println("Authentication refused");
return false;
}
}
public void addAccAr(Account myAccount) {
myAccounts.add(myAccount);
}
public Long getBalanceToLong() {
long balTemp = balans;
return balTemp;
}
public Long getPnTorLong() {
return persnr;
}
public Long getAccNoLong() {
long accTemp = accountNumber;
return accTemp;
}
public ArrayList<Long> getAllAccounts() {
ArrayList<Long> allAccounts = new ArrayList<>();
System.out.println("ALL ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
allAccounts.add(myAccount.getAccNoLong());
allAccounts.add(myAccount.getPnTorLong());
allAccounts.add(myAccount.getBalanceToLong());
}
return allAccounts;
}
/*
public ArrayList<String> getMyAccounts() {
ArrayList<String> ownAccounts = new ArrayList<>();
System.out.println("MY ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
ownAccounts.add(myAccount.getAccNoStr());
ownAccounts.add(myAccount.getBalanceToStr());
}
return ownAccounts;
}*/
}
This is our Customer class
package bank6;
import java.util.ArrayList;
public class Customer {
int custCounter;
//attribut
private Long socialNo;
private String name;
private ArrayList customers;
public Integer customerNumber;
static Integer custNo = 1;
private ArrayList<Customer> clients = new ArrayList<Customer>();
//konstruktor
public Customer(String socialStr, String name) {
Long socialTemp = new Long(socialStr);
this.name = name;
this.socialNo = socialTemp;
customerNumber = custNo++;
}//ends konstruktor customer6
public Customer() {
customers = new ArrayList();
}
/* Set methods*/
public void setName(String name) {
this.name = name;
}
public void setsocialNo(Long socialNo) {
this.socialNo = socialNo;
}
/* get methods */
public String getName() {
return name;
}
public String getSocialNoStr() {
String socialTemp = Long.toString(socialNo);
return socialTemp;
}
public Long getSocialNo() {
return socialNo;
}
/*toString() method*/
#Override
public String toString() {
return "\n" + "Owner: " + name + " (" + socialNo + ")";
}
public void addAccCustAr() {
}
public void addCustomerAr(Customer client) {
clients.add(client);
}
public ArrayList<String> getAllClients() {
ArrayList<String> allClients = new ArrayList<>();
System.out.println("ALL CLIENTS\n-----------");
for (Customer client : clients) {
allClients.add(client.getName());
allClients.add(client.getSocialNoStr() + "\n");
}
return allClients;
//add account
//public void addAccount(account6 account){
// accounts.add(account);
//}// ends adds account
//remove account
//public void removeAccount (account6 account) {
// accounts.remove(account);
//}//ends remove account
}
}//ends public class
This is our Luhn class
package bank6;
public class Luhn {
public static boolean checkLogin(String pnr) {
if (pnr.length() != 10) {
System.out.println("");
return false;
} else {
int length = pnr.length();
int sum = 0;
int pos = length - 1;
for (int i = 1; i <= length; i++, pos--) {
char tmp = pnr.charAt(pos);
int num = Integer.parseInt(String.valueOf(tmp));
int produkt;
if (i % 2 != 0) {
produkt = num * 1;
} else {
produkt = num * 2;
}
if (produkt > 9) {
produkt -= 9;
}
sum += produkt;
}
boolean korrekt = (sum % 10) == 0;
if (korrekt) {
System.out.println("Correct");
return true;
} else {
System.out.println("Invalid");
return false;
}
}
}
}
Your Account class already has a Customer field -- good.
You should give Customer an ArrayList<Account> accounts field.
And also give Customer addAccount(Account acct) and removeAccount(Account acct) methods.
Why does Customer have an ArrayList<Customer> field? That makes little sense. Should a Customer hold a list of other Customers? Why? For what purpose?
Why does Account have private ArrayList<Account> myAccounts = new ArrayList<Account>();? That also makes little sense. Should an Account hold a bunch of other Accounts? Again, for what purpose?
The Account class should logically represent one and only one Account.
Same for the Customer class -- it should logically represent only one Customer.
If you think through things logically, they usually come together, and each component of your code should make sense. If it doesn't, question why it is there.
So this code is broken:
Account bank = new Account();
//....
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
Since you're adding a bunch of Customer's to an Account object. It looks like you should have another class, a Bank class, one that can hold an ArrayList<Customer>. Wouldn't this make sense?
Heres the code:
Driver:
package myschool;
import java.util.ArrayList;
import java.util.Scanner;
public class MySchool {
public static void main(String[] args) {
ArrayList<Student> listStudent = new ArrayList<>();
ArrayList<Course> listCourse = new ArrayList<>();
Student s = new Student();
Course c = new Course();
boolean continueLoop = true;
Scanner userInput = new Scanner(System.in);
Scanner courseAddInput = new Scanner(System.in);
int option;
do{
try {
System.out.println(" What would you like to do?");
System.out.println(" 1) Add a student");
System.out.println(" 2) View students");
System.out.println(" 3) Remove a student");
System.out.println(" 4) Exit");
System.out.print("--> ");
option = userInput.nextInt();
switch( option ){
case 1:
Scanner inputs = new Scanner(System.in);
String fName, lName;
int sID;
double sGPA;
System.out.print(" First Name:");
fName = inputs.nextLine();
s.setStudentFirstName( fName );
System.out.print(" Last Name:");
lName = inputs.nextLine();
s.setStudentLastName( lName );
System.out.print(" ID Number:");
sID = inputs.nextInt();
s.setStudentID( sID );
System.out.print(" GPA:");
sGPA = inputs.nextDouble();
s.setStudentGPA( sGPA );
String cName, instructor, cBeginTime, cEndTime, cDay;
int i = 0, cID, cCred;
boolean continueAdd = true;
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
String addCourse;
do{
System.out.println("Would you like to add a course? Y/N");
addCourse = input2.nextLine();
if( "N".equals(addCourse)|| "n".equals(addCourse))
continueAdd = false;
if(continueAdd){
System.out.print(" CourseName:");
cName = input.nextLine();
c.setCourseName( cName );
System.out.print(" Instructor:");
instructor = input.nextLine();
c.setCourseInstructor( instructor );
System.out.print(" CourseID:");
cID = input.nextInt();
c.setCourseID( cID );
System.out.print(" CourseCredit:");
cCred = input.nextInt();
c.setCourseCred( cCred );
/*System.out.print(" StartTime:");
cBeginTime = input.nextLine();
c.setCourseBeginTime(cBeginTime);
System.out.print(" EndTime:");
cEndTime = input2.nextLine();
c.setCourseEndTime(cEndTime);*/
listCourse.add( new Course( c.getCourseName(), c.getCourseInstructor(), c.getCourseCred(), c.getCourseBeginTime(), c.getCourseEndTime(), c.getCourseID() ));
}
}while( continueAdd );
listStudent.add( new Student( s.getStudentFirstName(),s.getStudentLastName(), s.getStudentID(), s.getStudentGPA(), listCourse));
break;
case 2:
if(!listStudent.isEmpty()){
for(Student l:listStudent) {
System.out.println(l);
for(Course n:listCourse) {
System.out.println(n);
}
System.out.println();
}
}else
System.out.println("There are no students to view\n");
break;
case 3:
Scanner removeChoice = new Scanner(System.in);
try {
if(!listStudent.isEmpty()){
int j = 0;
System.out.println("Which student do you want to remove?");
for(Student l:listStudent) {
System.out.print(j+1 + ")");
System.out.println(l);
j++;
}
int remove = removeChoice.nextInt();
listStudent.remove( remove - 1 );
System.out.println("Student has been removed\n");
}else
System.out.println("There are no students to remove\n");
} catch (Exception e) {
System.out.println("There are no students to remove\n");
}
break;
case 4:
continueLoop = false;
break;
}
} catch (Exception e) {
System.out.println("That is not a valid option!!!");
continueLoop = false;
}
}while( continueLoop );
}
}
///////////Student Class///////////
package myschool;
import java.util.ArrayList;
public class Student {
String studentFirstName, studentLastName;
int studentID;
double studentGPA;
ArrayList<Course> listCourse = new ArrayList<>();
Student(){}
public Student(String studentFirstName, String studentLastName, int studentID, double studentGPA, ArrayList courseList) {
this.studentFirstName = studentFirstName;
this.studentLastName = studentLastName;
this.studentID = studentID;
this.studentGPA = studentGPA;
this.listCourse = courseList;
}
public void setListCourse(ArrayList<Course> listCourse) {
this.listCourse = listCourse;
}
public ArrayList<Course> getListCourse() {
return listCourse;
}
public void setStudentFirstName(String studentFirstName) {
this.studentFirstName = studentFirstName;
}
public String getStudentFirstName() {
return studentFirstName;
}
public void setStudentLastName(String studentLastName) {
this.studentLastName = studentLastName;
}
public String getStudentLastName() {
return studentLastName;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public int getStudentID() {
return studentID;
}
public void setStudentGPA(double studentGPA) {
this.studentGPA = studentGPA;
}
public double getStudentGPA() {
return studentGPA;
}
#Override
public String toString() {
return ("FirstName:" + this.getStudentFirstName() +
" LastName:" + this.getStudentLastName() +
" ID:" + this.getStudentID() +
" GPA:" + this.getStudentGPA());
}
}
///////////Course Class//////////////
package myschool;
public class Course {
private String courseName, courseInstructor, courseBeginTime, courseEndTime;
int courseID, courseCred;
Course(){}
public Course(String courseName, String courseInstructor, int courseCred, String courseBeginTime, String courseEndTime, int courseID) {
this.courseName = courseName;
this.courseInstructor = courseInstructor;
this.courseCred = courseCred;
this.courseBeginTime = courseBeginTime;
this.courseEndTime = courseEndTime;
this.courseID = courseID;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseName() {
return courseName;
}
public void setCourseInstructor(String courseInstructor) {
this.courseInstructor = courseInstructor;
}
public String getCourseInstructor() {
return courseInstructor;
}
public void setCourseCred( int courseCred) {
this.courseCred = courseCred;
}
public int getCourseCred() {
return courseCred;
}
public String getCourseBeginTime() {
return courseBeginTime;
}
public void setCourseBeginTime(String courseBeginTime) {
this.courseBeginTime = courseBeginTime;
}
public void setCourseEndTime(String courseEndTime) {
this.courseEndTime = courseEndTime;
}
public String getCourseEndTime() {
return courseEndTime;
}
public void setCourseID(int courseID) {
this.courseID = courseID;
}
public int getCourseID() {
return courseID;
}
#Override
public String toString() {
return( "Course Name:" + this.getCourseName()
+ " Course ID:" + this.getCourseBeginTime()
+ " Instructor:" + this.getCourseInstructor()
+ " Credit:" + this.getCourseCred()
+ " Begin Time:" + this.getCourseBeginTime()
+ " End Time:" + this.getCourseEndTime());
}
}
This is what happens at runtime
What would you like to do?
1) Add a student
2) View students
3) Remove a student
4) Exit
--> 1
First Name:Mike
Last Name:Smith
ID Number:2345
GPA:4
Would you like to add a course? Y/N
y
CourseName:MAth
Instructor:get
CourseID:123
CourseCredit:3
Would you like to add a course? Y/N
n
What would you like to do?
1) Add a student
2) View students
3) Remove a student
4) Exit
--> 1
First Name:Sarah
Last Name:Smoith
ID Number:42342
GPA:3
Would you like to add a course? Y/N
y
CourseName:Science
Instructor:tra;l
CourseID:345
CourseCredit:4
Would you like to add a course? Y/N
n
What would you like to do?
1) Add a student
2) View students
3) Remove a student
4) Exit
--> 2
FirstName:Mike LastName:Smith ID:2345 GPA:4.0
Course Name:MAth Course ID:null Instructor:get Credit:3 Begin Time:null End Time:null
Course Name:Science Course ID:null Instructor:tra;l Credit:4 Begin Time:null End Time:null
FirstName:Sarah LastName:Smoith ID:42342 GPA:3.0
Course Name:MAth Course ID:null Instructor:get Credit:3 Begin Time:null End Time:null
Course Name:Science Course ID:null Instructor:tra;l Credit:4 Begin Time:null End Time:null
Your toString method has a problem, check comments:
public String toString() {
return( "Course Name:" + this.getCourseName()
+ " Course ID:" + this.getCourseBeginTime() // getCourseID should be used here
+ " Instructor:" + this.getCourseInstructor()
+ " Credit:" + this.getCourseCred()
+ " Begin Time:" + this.getCourseBeginTime()
+ " End Time:" + this.getCourseEndTime());
}
so update all the getters call appropriately:
Please look at the toString() method of Course class.
Course ID:" + this.getCourseBeginTime() // should be getCourseId
I am trying to find two's greatest numbers that are entered from the console.
I found the first one, but the solution for the second one is not working. The program is compiling and running. Here is the code.
import java.util.Scanner;
public class FindingSecondHighestScore_4_09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double max = 1;
double score2 = 0;
String firstName = "";
String secondName = null;
System.out.println("Enter number of students: ");
int x = input.nextInt();
while(x > 0)
{
System.out.println("Enter Sudent's name");
String name = input.next();
System.out.println("Enter Student's score");
double score = input.nextDouble();
//find max
if(score > max)
{
max = score;
firstName = name;
}
//find second max
if(max < score2 || score < score2)
{
max = score2;
score = score2;
}
else if(max > score2 && score2 < score)
{
score2 = score;
secondName = name;
}
x--;
}
System.out.println("The student: " + firstName + " has the greatest score: " + max);
System.out.println("Second studemt " + secondName + " with second results: " + score2);
}
}
Here is a bit more elaborate implementation (my waking up excercise of today):
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TopScores {
private static final int TOP_SELECTION_SIZE = 2;
public static class Student {
private final String name;
private double score;
public Student(String name) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("Name cannot be empty");
}
this.name = name;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public void setScore(String score) {
try {
this.score = Double.parseDouble(score);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal score: " + score);
}
}
#Override
public String toString() {
return String.format("%s with score %s", name, score);
}
}
public static void main(String[] args) {
List<Student> students = new ArrayList<TopScores.Student>();
System.out.println("Please enter students. Press <RETURN> to stop.");
Scanner input = new Scanner(System.in);
boolean enteringData = true;
while (enteringData) {
try {
System.out.print("Enter student's name: ");
Student student = new Student(input.nextLine());
System.out.print("Enter student's score: ");
student.setScore(input.nextLine());
for (int i = 0; i < students.size(); i++) {
if (student.getScore() > students.get(i).getScore()) {
students.add(i, student);
break;
}
}
if (students.size() == 0) {
students.add(student);
}
} catch (IllegalArgumentException e) {
enteringData = false;
}
}
int studentsToDisplay = Math.min(TOP_SELECTION_SIZE, students.size());
if (studentsToDisplay > 0) {
System.out.println("Top students:");
for (int i = 0; i < studentsToDisplay; i++) {
System.out.println("* " + students.get(i));
}
} else {
System.out.println("No students to display");
}
}
}
I created a separate class Student which holds name and score, validates the input and creates the display format for one student.
To determine the top scores I keep all the entered students sorted in a list by adding each new student in the correct position.
The user doesn't have to enter the number of students beforehand but can terminate data entry by entering an empty line (or an invalid score).
After data entry is finished the desired number of top scoring students is printed.
This approach is more flexible; printing the top 3 or top 10 students is a matter of changing the value of TOP_SELECTION_SIZE.
Most important takeaway: try to think in classes (in this case Student) where possible and delegate sensible responsibilities to each class.
Since this looks like homework, I will just give you a few hints:
When you find a new max, what should happen to score2?
Should you look for a new score2 even if you found a new max?
If we want to address the if structures, consider rearranging to something like this:
if (/* new score beats second score, but not first */) {
// replace second score
} else if (/* new score beats both first and second */) {
// move first score down to second
// assign a new first score
}
Let your thought process to correspond closely to the code, which will clarify what each block should do, thus localizing any logic errors.
I think when score is greater than max then have to shift max into second score and set max with new score....
And
When the score is between max and score2 then have to update score2 only with new score
//find max
if(score > max)
{
score2 = max;
max = score;
secondName = firstName;
firstName = name;
}
//find second max
if(score < max && score > score2)
{
score2 = score;
secondName = name;
}