I was tasked with creating a small application for college, and have created a simple booking system.
I'm having an issue in that when the program runs, for no reason I can fathom it's executing the print part of a method but then jumping to the next method without executing the in.next() part of the original method.
I've included here in order the abstract class, the class where the issue is occurring, the menu, and the 'Creation' class.
I've been informed before here my coding (at least naming conventions) are not the best so I apologize for this in advance.
When I altered the class so that wasn't an extension of raw_Booking it seemed to not have this issue but not sure if that's relevant.
import java.util.Scanner;
abstract class raw_Booking {
private static String fname;
private static String lname;
private static int HouseNo;
private static String Street;
private static String Postcode;
Scanner in = new Scanner(System.in);
raw_Booking(){
}
abstract public String Setfname();
abstract public String Setlname();
abstract public int SetHouseNo();
abstract public String SetStreet();
abstract public String SetPostcode();
abstract public String Verification();
}
The problem class (method is SetPostcode):
import java.util.Scanner;
import java.io.*;
class Hotel_Booking extends raw_Booking{
Scanner in = new Scanner(System.in);
private String TheVerification;
private int guests;
private String Roomtype;
private double numbRooms;
private double costStay;
private double nights;
private static String fname;
private static String lname;
private static int HouseNo;
private static String Street;
private static String Postcode;
Hotel_Booking() {
fname = Setfname();
lname = Setlname();
HouseNo = SetHouseNo();
Street = SetStreet();
Postcode = SetPostcode();
TheVerification = Verification();
Roomtype = setRoomtype();
guests = guests();
numbRooms = numbRooms();
nights = nights();
costStay = costStay();
Write_File();
}
public String Setfname(){
System.out.println();
System.out.print("Bookers first name please: ");
fname = in.next();
return fname;
}
public String Setlname(){
System.out.println();
System.out.print("Bookers surname please: ");
lname = in.next();
return lname;
}
public int SetHouseNo(){
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("Please enter your house number: ");
while (!sc.hasNextInt()) {
System.out.println();
System.out.print("You need to enter a number - please re-enter: ");
sc.next();
}
return sc.nextInt();
}
public String SetStreet(){
System.out.println();
System.out.print("Please enter your street: ");
Street =in.next();
return Street;
}
public String SetPostcode(){
System.out.println();
System.out.print("Please enter your postcode: ");
Postcode = in.next();
return Postcode;
}
public String Verification(){
System.out.println();
System.out.print("Please provide your car reg as verification: ");
TheVerification = in.next();
return TheVerification;
}
public String setRoomtype(){
System.out.println();
System.out.print("Would you like a Premiun or Regular room(s)? ");
Roomtype = in.next();
return Roomtype;
}
public int guests(){
System.out.println();
System.out.print("How many guests will be staying? ");
guests = in.nextInt();
return guests;
}
//For every 3 guests their must be 1 room at £50 per night.
//Premiun rooms = price doubled
public double numbRooms(){
for(int i=0;i < guests;i++){
numbRooms = numbRooms+1;
i = i + 2;
}
System.out.println();
System.out.println("You will require " + numbRooms + " number of rooms");
return numbRooms;
}
public double nights(){
System.out.println();
System.out.print("How many nights are you staying? ");
nights = in.nextDouble();
return nights;
}
public double costStay(){
if(Roomtype.equals("Regular")){
costStay = (nights * numbRooms)*50;
}
else{
costStay = (nights * numbRooms)*100;
}
System.out.println();
System.out.println("The total cost of your stay will be: " + costStay);
return costStay;
}
public void Write_File(){
System.out.println();
System.out.println("Your details will now be written to file.");
System.out.println();
try{
PrintWriter wr = new PrintWriter(new FileOutputStream("Hotel_Booking.txt",true));
wr.println("Name: " + fname+ " " + lname);
wr.println("Address line one: " + HouseNo + " " + Street);
wr.println("Postcode: " + Postcode);
wr.println("Roomtype: " + Roomtype);
wr.println("Number of rooms: " + numbRooms);
wr.println("Nights staying: " + nights);
wr.println("Total cost of stay: " + costStay);
wr.close();
}
catch (IOException e){
System.out.println("Error -- " + e.toString());
}
}
public static String Getfname(){
return fname;
}
}
Contains Interface/Menu.
public class Interface{
public static void Menu(){
System.out.println("Welcome to the booking system select an option");
System.out.println("1 - Create a new hotel booking");
System.out.println("2 - Create a new airline booking");
System.out.println("3 - Create a car hire booking");
System.out.println("4 - Create a amusement park ticket booking");
System.out.println("5 - Create a concert ticket booking");
System.out.println();
}
}
Main point of execution:
import java.util.ArrayList;
import java.util.Scanner;
public class Booking_Creation{
static Scanner in = new Scanner(System.in);
static ArrayList<Hotel_Booking> hotelbookings = new ArrayList<Hotel_Booking>();
static ArrayList<Flight_Booking> flightbookings = new ArrayList<Flight_Booking>();
static ArrayList<Car_Hire> carhirebookings = new ArrayList<Car_Hire>();
static ArrayList<Amusement_Park_Ticket> parkticket = new ArrayList<Amusement_Park_Ticket>();
static ArrayList<Concert_Ticket> concertticket = new ArrayList<Concert_Ticket>();
static int selection;
public static void main(String[] arguments){
Interface.Menu();
selection = in.nextInt();
// COULD ASK THE QUESTIONS HERE????
/// BUT THE INPUT BIT IS INSIDE THE OTHER CLASS
switch(selection){
case 1:
Hotel_Booking hb = new Hotel_Booking();
hotelbookings.add(hb);
break;
case 2:
Flight_Booking fb = new Flight_Booking();
flightbookings.add(fb);
break;
case 3:
Car_Hire ch = new Car_Hire();
carhirebookings.add(ch);
break;
case 4:
Amusement_Park_Ticket pt = new Amusement_Park_Ticket();
parkticket.add(pt);
break;
case 5:
Concert_Ticket ct = new Concert_Ticket();
concertticket.add(ct);
break;
}
}
}
Example output:
Welcome to the booking system select an option
1 - Create a new hotel booking
2 - Create a new airline booking
3 - Create a car hire booking
4 - Create a amusement park ticket booking
5 - Create a concert ticket booking
1
Bookers first name please: Herton
Bookers surname please: Ferford
Please enter your house number: 4
Please enter your street: Park Lane
Please enter your postcode:
Please provide your car reg as verification: KS23
After a quick glance to your sample execution, I think that the street name is parsed as two tokens, so the street name is set as "Tulloch" and when prompted for the postcode (as a string), "Park" is read.
It might be useful to set a pattern on the Scanner.next() method to force a full line as a single token ?
Related
I'm still a beginner so cut me some slack.
I have 5 class but only 2 are needed for my question. This is a question in my assignment so no need to be too particular. I have been tasked to make a java terminal system to store and display lecturer (part time and full time), lecturers address, and classes information.
My code will check if there is a part time lecturer to display (this includes the address object since it is part of the lecturer information) . If not, it will prompt the user to enter the part time lecturer details. When entering the part time details I am not sure on how to enter the address without recreating the object.
here is my codes
This is part time class
public class PartTime extends Lecturer{
private double hourlyRate;
private int hoursWorked;
//classR = class resposible
private ClassInfo classR;
PartTime(){
classR = new ClassInfo();
}
PartTime(String staffNo, String name, int contactNo, int noClasses, Address add, double hourlyRate, int hoursWorked, ClassInfo classR){
super(staffNo, name, contactNo, noClasses, add);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
this.classR = classR;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public int getHoursWorked(){
return this.hoursWorked;
}
public void setHourlyRate(double newHourlyRate){
this.hourlyRate = newHourlyRate;
}
public void setHoursWorked(int newHoursWorked){
this.hoursWorked = newHoursWorked;
}
public void displayClassR(){
System.out.println("Class No : "+ classR.getClassNo());
System.out.println("Subject Name : "+ classR.getSubjectName());
System.out.println("Number Of Students : "+ classR.getNoStudents());
System.out.println("Start Date : "+ classR.getStartDate());
System.out.println("End Date : "+ classR.getEndDate());
}
}
This is lecturer class
public class Lecturer{
private String staffNo, name;
private int contactNo, noClasses;
private final Address add;
Lecturer(){
add = new Address();
}
Lecturer(String staffNo, String name, int contactNo, int noClasses, Address add){
this.staffNo = staffNo;
this.name = name;
this.contactNo = contactNo;
this.noClasses = noClasses;
this.add = add;
}
public String getStaffNo(){
return this.staffNo;
}
public String getName(){
return this.name;
}
public int getContactNo(){
return this.contactNo;
}
public int getNoClasses(){
return this.noClasses;
}
public void displayAdd(){
System.out.println("Unit Number : "+ add.getUnitNo());
System.out.println("Street Name : "+ add.getStreetName());
System.out.println("City : "+ add.getCity());
System.out.println("Postcode : "+ add.getPostcode());
}
public void setStaffNo(String newStaffNo){
this.staffNo = newStaffNo;
}
public void setName(String newName){
this.name = newName;
}
public void setContactNo(int newContactNo){
this.contactNo = newContactNo;
}
public void setNoClasses(int newNoClasses){
this.noClasses = newNoClasses;
}
public void setAdd(String newUnitNo, String newStreetName, String newCity, int newPostcode){
add.setUnitNo(newUnitNo);
add.setStreetName(newStreetName);
add.setCity(newCity);
add.setPostcode(newPostcode);
}
}
You can ignore the menu part
import java.io.*;
class Main{
static Scanner scan = new Scanner(System.in);
static Address add = new Address();
static ClassInfo classI = new ClassInfo();
static FullTime ft = new FullTime();
static PartTime pt = new PartTime();
static String staffNo, name, classNo, subjectName, startDate, endDate, unitNo, streetName, city;
static int contactNo, noClasses, hoursWorked, noStudents, postcode, select;
static double annualSalary, hourlyRate;
public static void main(String[] args){
//menu looping
do{
System.out.println("=======================");
System.out.println("| Main Menu |");
System.out.println("| Select an option |");
System.out.println("| 1. Lecturer |");
System.out.println("| 2. Class Info |");
System.out.println("| 3. File Actions |");
System.out.println("| 0. Exit |");
System.out.println("=======================");
select = scan.nextInt();
switch(select){
case 1:
lecturerMenu();
break;
case 2:
classInfoMenu();
break;
case 3:
fileMenu();
case 0:
System.out.println("Exiting...");
System.exit(0);
break;
default:
System.out.println("Error please select again");
}
}while(select !=0);
}
Eventually it will make its way to the part where the user adds part time lecturer data. the set is incomplete as i didnt know how to do the addresspart
public static void newPartTime(){
System.out.println("Enter Part Time Lecturer Details");
System.out.print("Enter Staff Number: ");
scan.nextLine();
staffNo = scan.nextLine();
System.out.print("Enter Name: ");
name = scan.nextLine();
System.out.print("Enter Contact Number: ");
contactNo = scan.nextInt();
System.out.print("Enter Hourly Rate: ");
hourlyRate = scan.nextDouble();
System.out.print("Enter Hours Worked: ");
hoursWorked = scan.nextInt();
System.out.println("Enter Address");
System.out.print("Enter Unit Number: ");
scan.nextLine();
unitNo = scan.nextLine();
System.out.print("Enter Street Name: ");
streetName = scan.nextLine();
System.out.print("Enter City: ");
city = scan.nextLine();
System.out.print("Enter Postcode: ");
postcode = scan.nextInt();
scan.nextLine();
if(classI == null){
System.out.println("There is no class available. Please add a new class");
newClassInfo();
}else{
pt.setStaffNo(staffNo);
pt.setName(name);
pt.setContactNo(contactNo);
pt.setNoClasses(noClasses);
pt.set
}
}
}
Normally I would do this for my declaration:
static FullTime ft = new FullTime(var1, var1 ,var3, address);
Am I able to recreate the object or should I just add a method for set address in part time?
You could create an Object of the address class and set values to that and then set the object into your part time object.
Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
I have my code in 3 different files using encapsulation (Data hiding) and i have 1 problem at the very end of my code in my if and else statement (very bottom) when trying to call the classes from the other 2 documents. I will put the code in 1st document to 3rd document. Any suggestions on what I did wrong?
// FIRST DOCUMENT
public class CollegeCourse { //class name
//variables
String deptName;
int courseNum;
int credits = 3;
double fee;
//constructor
public CollegeCourse(String department, int course, int Credits) {
deptName = department;
courseNum = course;
credits = Credits;
fee = credits * 120;
}
//getters setters
public String getdepartment() {
return deptName;
}
public String setdepartment(String dept) {
return dept = deptName;
}
public int getcourse() {
return courseNum;
}
public int setcourse(int c) {
return c = courseNum;
}
public int getCredits() {
return credits;
}
public int setCredits(int cred) {
return cred = credits;
}
public void display()
{
System.out.println("Department: " + deptName);
System.out.println("Course Number: " + courseNum);
System.out.println("Credits: " + credits);
System.out.println("Fee: $" + fee);
}
}
//SECOND DOCUMENT
public class LabCourse extends CollegeCourse { //polymorphism extending CollegeCourse class into LabCourse class.
//constructor
public LabCourse(String department, int course, int Credits){
//add 50 dollars to the fee
super(department, course, Credits);
fee = fee + 50;
}
//display the course
public void display(){
System.out.print("This course is a lab course" + fee);
System.out.println("Department: " + deptName);
System.out.println("Course Number: " + courseNum);
System.out.println("Credits: " + credits);
System.out.println("Fee: $" + fee);
}
}
//THIRD DOCUMENT MAIN HEADER
import java.util.Scanner;
public class UseCourse {
public static void main(String[] args){
String s, c, cd;
Scanner input = new Scanner(System.in);
System.out.print("Enter: BIO, CHEM, ENG, MATH: ");
s = input.nextLine();
System.out.print("What is the course number: ");
c = input.nextLine();
System.out.print("How many credits: ");
cd = input.nextLine();
if(s.equals ("BIO") || s.equals ("CHEM")){
LabCourse lc = new LabCourse(department, course, Credits); //here is my problem, it can't find the CollegeCourse class department, course,//and credits...
lc.display();
}
else {
CollegeCourse cc = new CollegeCourse(department, course, Credits); //here is my problem, it can't find the CollegeCourse class department, course,//and credits...
cc.display();
}
}
}
Here is the error that i'm getting.
UseCourse.java:24: error: cannot find symbol
LabCourse lc = new LabCourse(department, course, Credits);
^
And it repeats for each error "department, course, Credits"
UseCourse.java:29: error: cannot find symbol
CollegeCourse cc = new CollegeCourse(department, course, Credits);
^
Your parameters in your constructor call are all wrong. Neither department, course or Credits are defined, so you would need to use s, c and cd instead, as those are the variables you're using for your input.
Furthermore, you need to read c and cd as integers and pass those to your constructor as follows:
System.out.print("What is the course number: ");
int c = input.nextInt();
System.out.print("How many credits: ");
int cd = input.nextInt();
// ...
LabCourse lc = new LabCourse(s, c, cd);
In my program, I want to transfer credits between two person. All of the info I have added in the arrayList. Each person is given an ID.
To make transaction, user have to enter ID.
The withdraw amount enterd by the user must be subtracted from the particular account and eventually that amount must be added with another particular account, depending on the ID chosen by user. How to do that?
Basically, I don't know how to check the amount/credit with the matching ID, and then performing arithmetic task within that specific person's amount.
Actually the part I am concentrating on is switch (option2) in my code.
This is my code I am working on.
AboutPerson:
public static void main(String[] args) {
String name;
int id;
int option1;
int option2;
double credit;
int withdraw_id;
double withdraw_amount;
double dep_id;
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "3. Transfer credits\n"//need help here
+ "*************"
+ "*************");
option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
break;
case 2:
//display them
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pInfo : info) {
System.out.println(pInfo);
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
case 3:
//transfer credit
System.out.println("To transfer credit between two persons enter 1");//working with this one
System.out.println("To transfer credit within the same persons enter 2");//not focusing on that now
option2 = input.nextInt();
input.nextLine();
switch (option2) {
case 1:
System.out.println("Enter the ID of the person you want to withdraw amount from: ");
withdraw_id = input.nextInt();
System.out.println("Enter withdraw amount: ");
withdraw_amount = input.nextDouble();
//subtract that credit from that account
System.out.println("Enter the ID of the person you want to deposit into: ");
dep_id = input.nextDouble();
//the amount has been withdrawn will be deposited
//add that credit
System.out.println("Done!\tTo print them out out choose option 2");
break;
}
}
}
}
PersonInfo:
package aboutperson;
public class PersonInfo {
private String name;
private int id;
private double credit;
public PersonInfo() {
this.name = null;
this.id = 0;
this.credit = 0;
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public void setCredit(double credit) {
this.credit = credit;
}
#Override
public String toString() {
return name + "\t\t" + id + "\t\t" + credit;
}
}
First add getCredit and getID methods to PersonInfo:
public double getCredit() {
return this.credit;
}
public int getID() {
return this.id;
}
And then simply exchange it between the two accounts:
System.out.println("Enter the ID of the person you want to deposit into: ");
dep_id = input.nextDouble();
input.nextLine();
System.out.println("Enter your ID: ");
withdraw_id = input.nextDouble();
input.nextLine();
System.out.println(": ");
withdraw_amount = input.nextDouble();
input.nextLine();
PersonInfo fromPerson = null;
PersonInfo toPerson = null;
//find PersonInfo objects from list:
for (PersonInfo pi : info) {
if (pi.getID() == dep_id) {
toPerson = pi;
break;
}
}
for (PersonInfo pi : info) {
if (pi.getID() == withdraw_id) {
fromPerson = pi;
break;
}
}
if (fromPerson == null || toPerson == null) {
System.out.println("Wrong IDs."); //maybe do something more user friendly here
break;
}
if (withdraw_amount > fromPerson.getCredit()) {
System.out.println("notify of error");
break;
}
fromPerson.setCredit(fromPerson.getCredit() - withdraw_amount);
toPerson.setCredit(toPerson.getCredit() + withdraw_amount);
System.out.println("Done!\tTo print them out out choose option 2");
Instead of storing PersonInfo in List, use Map where you can use key as id and value as PersonInfo itself. so it will be like:
Map<Integer, PersonInfo> info = new HashMap<Integer, PersonInfo>();
...
personInfo.setCredit(input.nextDouble());
perdonIdInfoMap.put(personInfo.getId(), personInfo);
Then when you have two id's get the info from map like:
personInfoFrom = perdonIdInfoMap.get(id1);
personInfoTo = perdonIdInfoMap.get(id2);
//now deduct from one and add to other like personInfoFrom.setCredit(personInfoFrom.getCridit() + personInfoTo.getCredit());
You can iterate over the list and check:
for(PersonInfo person: info){
if(person.getId().equals(searchedId)){
/* here you can do operation on that person*/
/* Printing the balance */
System.out.println("Balance: " + person.getCredit());
/* Adding or subtracting money*/
person.setCredit(person.getCredit() + ammount);
/* Other stuff*/
}
}
Or you could use a Map as SMA suggested
I have searched for this question and I am still at a loss after trying alot. I am completely new to Java so please excuse the ignorance. I am trying to read in a file from the scanner. The file contains SmartPhone attributes and I would like to assign them directly to the smartphone class variables and then create my phone and add it to the list. However, the phones are not getting added and I have made sure that the text file is in the format that the scanner and class attributes are expecting. Can anyone spot my mistake?
package model;
import java.io.*;
import java.util.*;
public class menu {
public static void main(String[] args) {
int inputOption;
SmartPhone newPhone;
LinkedList<SmartPhone> phoneList;
FileToLinkedList smartphoneList;
smartphoneList = new FileToLinkedList();
phoneList = smartphoneList.createDatabase();
System.out.println(phoneList);
Scanner userInput = new Scanner(System.in);
//userInput.useDelimiter(System.getProperty("line.separator"));
int smartphoneLabel = 0;
String model = "";
String manufacturer = "";
int year = 0;
double price = 0.0;
String color = "";
System.out.println("==============================");
System.out.println(" SmartPhone Database Menu ");
System.out.println("==============================");
System.out.println("Options: ");
System.out.println(" 1. Display all smartphones ");
System.out.println(" 2. Add a smartphone ");
System.out.println(" 3. Delete a smartphone ");
System.out.println(" 4. Search for a smartphone ");
System.out.println(" 5. Quit ");
System.out.println("==============================");
inputOption = KeyIn.inInt("Please select an option from the menu: ");
switch(inputOption){
case 1:
System.out.println("You've selected to display the entire smartphone database.");
break;
case 2:
System.out.println("You have chosen to add a smartphone to the database. ");
System.out.println("Smartphone Label: ");
smartphoneLabel = userInput.nextInt();
System.out.println("Model: ");
model = userInput.next();
System.out.println("Manufacturer: ");
manufacturer = userInput.next();
System.out.println("Year: ");
year = userInput.nextInt();
System.out.println("Price: ");
price = userInput.nextDouble();
System.out.println("Color: ");
color = userInput.next();
newPhone = new SmartPhone(smartphoneLabel, model, manufacturer, year, price, color);
phoneList.add(newPhone);
System.out.println("Here is your new database of smartphones. ");
//phoneList.displayDatabase();
break;
case 3:
System.out.println("You have chosen to delete a smartphone from the database. ");
break;
case 4:
System.out.println("You have chosen to search for a particular model." );
break;
case 5:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid selection.");
break;
}
}
}
package model;
import java.io.*;
import java.util.*;
public class FileToLinkedList extends LinkedList {
LinkedList<SmartPhone> myPhoneList;
public FileToLinkedList(){
myPhoneList = new LinkedList<SmartPhone>();
}
public LinkedList<SmartPhone> createDatabase(){
try{
Scanner scanner = new Scanner("SmartPhone_Database.txt");
while(scanner.hasNext()) {
SmartPhone newPhone = new SmartPhone();
newPhone.setLabel(scanner.nextInt());
newPhone.setModel(scanner.nextLine());
newPhone.setManufacturer(scanner.nextLine());
newPhone.setYear(scanner.nextInt());
newPhone.setPrice(scanner.nextDouble());
newPhone.setColor(scanner.nextLine());
//phoneList.add(newPhone);
((LinkedList<SmartPhone>)myPhoneList).add(newPhone);
}
}
catch(InputMismatchException e){}
return myPhoneList;
}
}
*I have listed two ways that have been suggested, one commented out--but still nothing..
package model;
import java.lang.*;
public class SmartPhone {
private int smartphoneLabel;
private String model;
private String manufacturer;
private int year;
private double price;
private String color;
//constructor
public SmartPhone(){
smartphoneLabel = 0;
model = "";
manufacturer = "";
year = 0;
price = 0.0;
color = "";
}
public SmartPhone(int myLabel, String myModel, String myManufacturer, int myYear, double myPrice, String myColor)
{
smartphoneLabel = myLabel;
model = myModel;
manufacturer = myManufacturer;
year = myYear;
price = myPrice;
color = myColor;
}
public int getLabel(){
return smartphoneLabel;
}
public String getModel(){
return model;
}
public String getManufacturer(){
return manufacturer;
}
public int getYear(){
return year;
}
public double getPrice(){
return price;
}
public String getColor(){
return color;
}
public void setLabel(int label){
smartphoneLabel = label;
}
public void setModel(String model){
model = model;
}
public void setManufacturer(String manufacturer){
manufacturer = manufacturer;
}
public void setYear(int year){
year = year;
}
public void setPrice(double price){
price = price;
}
public void setColor(String color){
color = color;
}
public void display(){
System.out.println("Label: " + getLabel() + "\n");
System.out.println("Model: " + getModel() + "\n");
System.out.println("Manufacturer: " + getManufacturer() + "\n");
System.out.println("Year: " + getYear() + "\n");
System.out.println("Price: " + getPrice() + "\n");
System.out.println("Color: " + getColor() + "\n");
}
}
And this is my text file:
1234 NC2000 Nokia 2009 100.00 Silver
3874 CT4500 iPhone 2012 450.00 White
59780 F5600 Android 2012 475.00 Black
5983 T95000 Android 2011 500.00 Silver
23300 GH3000 Samsung 2010 275.00 Black
47000 TT2700 Samsung 2009 100.00 Silver
Your problem is in your return statement for createDatabase(). You only return a LinkedList when there is an InputMismatchException, when you want to return myPhoneList every single time the method is called. That should fix things right up for you.