Implementing methods: Writing two classes, one with a main, other with not - java

I'm suppose to write a class with the following.
First Name
Last Name
ID
Score1
Score2
Score3
Average
Grade (for A, A-, B+, ...E).
All the data members are suppose to be private.
Below this is what I have and I named the class, Student.
import java.util.Scanner;
public class Student {
private String fname;
private String lname;
private int id;
private int score1;
private int score2;
private int score3;
private double average;
private String grade;
public void readInfo()
{
Scanner k = null;
k = new Scanner (System.in);
System.out.println ("Please enter the first name: (Enter John as first name and Doe as last name to stop) ");
fname = k.next();
System.out.println("Please enter the last name: ");
lname = k.next();
if (fname.equalsIgnoreCase("John")&&lname.equalsIgnoreCase("Doe"))
System.exit(0);
System.out.println("Please enter the student ID: ");
id = k.nextInt();
System.out.println("Please enter the first score: ");
score1 = k.nextInt();
System.out.println("Please enter the second score: ");
score2 = k.nextInt();
System.out.println("Please enter the third score: ");
score3 = k.nextInt();
}
private void computeAverage()
{
average = (score1+score2+score3)/3;
}
private void computeGrade()
{
if (average>=90&&average<=100)
grade = "A";
else if (average>=80&&average<=89.9)
grade = "B";
else if (average>=70&&average<=79.9)
grade = "C";
else if (average>=60&&average<=69.9)
grade = "D";
else
grade = "F";
}
private String getName()
{
return fname + " " + lname;
}
private double getAverage()
{
return average;
}
public void printAll()
{
System.out.printf("%-9s%-10s %-9s %-3s %-3s %-3s %-5s %-5s", "LastName","FirstName","ID","S1","S2","S3","AVG","GRADE");
System.out.println();
System.out.println("-----------------------------------------------------");
System.out.printf("%-9s%-9s %-9d %-3d %-3d %-3d %-3.2f%-2s",lname,fname,id,score1,score2,score3,average,grade);
System.out.println();
System.out.println("-----------------------------------------------------");
The problem I'm having is how to actually get the information to display on the console. I went ahead and created an instance and called it Averages of the Student class (the class thats listed above.)
Here is what I have of the other class called 'Averages'. I'm lost on what to do. First time actually in Java, only been studying it for two weeks. My book does not clarify anything. So? I assume I'm still learning the ropes and feeling annoyed, I cannot figure this probably (easy) part out. Thanks.
import java.util.Scanner;
public class Averages {
public static void main(String[] args) {
Scanner k= new Scanner(System.in);
Student[] students = new Student[36];
Student st, st2;
st = new Student();
st2 = new Student();
System.out.printf("%-9s%-10s %-9s %-3s %-3s %-3s %-5s %-5s", "LastName","FirstName","ID","S1","S2","S3","AVG","GRADE");
System.out.println();
System.out.println("-----------------------------------------------------");
//System.out.printf("%-9s%-9s %-9d %-3d %-3d %-3d %-3.2f%-2s",lname,fname,id,score1,score2,score3,average,grade);
System.out.println();
System.out.println("-----------------------------------------------------");

Here is a piece of code to help you.
It mainly populates the array with students' data, and computes and prints the class average :
public static void main(String[] args) {
int classSize = 36;
double cumulatedAverages = 0d;
Student[] students = new Student[classSize];
for(int i =0;i<students.length;i++){
Student student = new Student();
// populate student's data
student.readInfo();
// make calculations
student.computeGrade();
student.computeAverage();
cumulatedAverages = cumulatedAverages + student.getAverage();
// add the student to the array
students[i] = student;
}
// compute the class average
double classAverage = cumulatedAverages / classSize;
System.out.printf("%s %-3.2f","Class average is",classAverage);
}

Related

Why won't my array pass to the other class?

I have looked at similar examples or other programs that call array from another class and it seems like I have done it the correct way but I am still getting errors.
This is where the arrarys are stored:
import java.util.Scanner;
public class DriverProgram {
public static int[] IDs = new int[10];
public static String[] names = new String[10];
public static double[] grades = new double[10];
public static int i = 0;
static Student call = new Student();
public static void main(String[] args){
call = new Student();
Scanner command = new Scanner(System.in);
System.out.println("Please Enter a command(i, r, s, or d): ");
while(command.hasNext()){
char command1 = command.next().charAt(0);
if(command1 == 'i'){
call.AddToArray(IDs[], names[] , grades[], i);
}else if(command1 == 'r'){
call.RemoveFromArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 's'){
call.SortArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'd'){
call.DisplayArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'z') {
break;
}
else System.out.println("Invalid command enter a valid command next time.");
System.out.println("Please Enter a command(i, r, s, or d) or z to finish: ");
}
}
And this is what I am tryign to call the arrays to:
import java.util.Scanner;
public class Student {
public static void AddToArray(int[] IDs, String[] names, double[] grades, int i) {
if (i >= 10) {
System.out.println("You have already inputted 10 students please delete one first.");
} else {
Scanner readin = new Scanner(System.in);
Scanner readinname = new Scanner(System.in);
Scanner readingrade = new Scanner(System.in);
System.out.println("Please enter student ID: ");
IDs[i] = readin.nextInt();
System.out.println("Please enter student name: ");
names[i] = readinname.nextLine();
System.out.println("Please enter student grade: ");
grades[i] = readingrade.nextDouble();
System.out.println(IDs[i] + " " + names[i] + " " + grades[i]);
i++;
for (int j = 0; j < i; j++) {
if (IDs[j] == IDs[i]) {
System.out.println("This student has already been entered.");
}else{
System.out.println("The student has been added");
break;
}
}
}
}
I am not sure what else I need or what I am missing in order to call those arrays.
call.AddToArray(IDs[], names[] , grades[], i);
should be replaced with
call.AddToArray(IDs, names , grades, i);
P.S. Design notes
Student has only static method, so this is utilitly class and should not allowed an instance creation
call.AddToArray() and others static methods should be called as Student.AddToArray()
array is not correct data strucutre where you can add or remove elements. There're more suitable data structures like List or Map.
It's better to use only one instance of Scanner.
This is how you DriverProgram could look like.
public class DriverProgram {
public static void main(String[] args) {
Map<Integer, Student> students = new HashMap<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.println("Please Enter a command [1-5]:");
System.out.println("1. add new student");
System.out.println("2. remove existed student");
System.out.println("3. sort existed students by grades desc");
System.out.println("4. show existed students");
System.out.println("5. exit");
System.out.print("> ");
int menu = scan.nextInt();
if (menu == 1)
addStudent(scan, students);
else if (menu == 2)
removeStudent(scan, students);
else if (menu == 3)
sortStudents(students);
else if (menu == 4)
showStudents(students);
else if (menu == 5)
break;
System.err.println("Unknown command. Try again");
}
}
private static void addStudent(Scanner scan, Map<Integer, Student> students) {
if (students.size() == 10) {
System.err.println("You have already inputted 10 students please delete one first.");
return;
}
System.out.print("Please enter student ID: ");
int id = scan.nextInt();
if (students.containsKey(id)) {
System.err.println("This student with this id has already been entered.");
return;
}
System.out.print("Please enter student name: ");
String name = scan.nextLine();
System.out.print("Please enter student grade: ");
double grade = scan.nextDouble();
students.put(id, new Student(id, name, grade));
}
private static void removeStudent(Scanner scan, Map<Integer, Student> students) {
}
private static void sortStudents(Map<Integer, Student> students) {
}
private static void showStudents(Map<Integer, Student> students) {
}
public static final class Student {
private final int id;
private final String name;
private final double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
}
}

Need help sorting ArrayList & Calculating averages of test scores

I tried adding a new class per a suggestion I was given, which is seen at line 67. I am unsure how to link the new class with the entries created from user input and the goal is to sort the ArrayList by the last name and to calculate averages of each of the entries 4 test scores, resulting in an average score - I would like the average score to be added to each students entry and added to the final ArrayList
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
//information given by user input that will eventually go into the ArrayList
public class studentInformation {
public static <T> void main(String[] args) {
//creating ArrayList to hold the objects created above
ArrayList<Object> studentdatabase = new ArrayList<Object>();
char cont;
do {
Scanner fnInput = new Scanner(System.in);
System.out.println("Enter Student's First Name & Press Enter");
//String fn = fnInput.nextLine();
studentdatabase.add(fnInput.nextLine());
Scanner lnInput = new Scanner(System.in);
System.out.println("Enter Student's Last Name & Press Enter");
//String ln = lnInput.nextLine();
studentdatabase.add(lnInput.nextLine());
Scanner score1Input = new Scanner(System.in);
System.out.println("Enter Student's First Exam Score & Press Enter");
//int score1 = score1Input.nextInt();
studentdatabase.add(score1Input.nextInt());
Scanner score2Input = new Scanner(System.in);
System.out.println("Enter Student's Second Exam Score & Press Enter");
//int score2 = score2Input.nextInt();
studentdatabase.add(score2Input.nextInt());
Scanner score3Input = new Scanner(System.in);
System.out.println("Enter Student's Third Exam Score & Press Enter");
//int score3 = score3Input.nextInt();
studentdatabase.add(score3Input.nextInt());
Scanner score4Input = new Scanner(System.in);
System.out.println("Enter Student's Fourth/Final Exam Score & Press Enter");
//int score4 = score4Input.nextInt();
studentdatabase.add(score4Input.nextInt());
Scanner continueInput = new Scanner(System.in);
System.out.println("Enter 'C' to end or 'A' to Add More");
cont = continueInput.next().charAt(0);
//calculate the average score for each student
//sort the ArrayList prior to printing
//Collections.sort(studentdatabase);
//Prints out the arrayList
System.out.println(studentdatabase);
}
while(cont != 'c' || cont != 'C');
}
class Students {
String firstName, lastName;
int firstScore, secondScore, thirdScore, fourthScore, averagescore;
char lettergrade;
}
}
Fisrt, create a real Student class (singular, not plural). An instance of this class is only one student. It will handle average calculation in a dedicated method.
Think about using getters and setters with the correct accessors on your attributes.
public class Student {
private String firstName, lastName;
private int firstScore, secondScore, thirdScore, fourthScore, averagescore;
private char lettergrade;
public float computeAverage(){
int sum = firstScore + secondScore + thirdScore + fourthScore;
return (float) sum / 4;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getFirstScore() {
return firstScore;
}
public void setFirstScore(int firstScore) {
this.firstScore = firstScore;
}
public int getSecondScore() {
return secondScore;
}
public void setSecondScore(int secondScore) {
this.secondScore = secondScore;
}
public int getThirdScore() {
return thirdScore;
}
public void setThirdScore(int thirdScore) {
this.thirdScore = thirdScore;
}
public int getFourthScore() {
return fourthScore;
}
public void setFourthScore(int fourthScore) {
this.fourthScore = fourthScore;
}
public int getAveragescore() {
return averagescore;
}
public void setAveragescore(int averagescore) {
this.averagescore = averagescore;
}
public char getLettergrade() {
return lettergrade;
}
public void setLettergrade(char lettergrade) {
this.lettergrade = lettergrade;
}
}
Then, don't use Object in your list but Student. You created an object. Use it !
You can't sort the list until you're done with feeding it. Put the sort out of the loop.
cont != 'c' || cont != 'C'
will always be true. So you will never get out of your loop.
Finally, I would suggest something like this.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static <T> void main(String[] args) {
//creating ArrayList to hold the objects created above
ArrayList<Student> studentdatabase = new ArrayList<Student>();
char cont;
do {
Student currentStudent = new Student();
Scanner fnInput = new Scanner(System.in);
System.out.println("Enter Student's First Name & Press Enter");
currentStudent.setFirstName(fnInput.nextLine());
Scanner lnInput = new Scanner(System.in);
System.out.println("Enter Student's Last Name & Press Enter");
currentStudent.setLastName(lnInput.nextLine());
Scanner score1Input = new Scanner(System.in);
System.out.println("Enter Student's First Exam Score & Press Enter");
currentStudent.setFirstScore(score1Input.nextInt());
Scanner score2Input = new Scanner(System.in);
System.out.println("Enter Student's Second Exam Score & Press Enter");
currentStudent.setSecondScore(score2Input.nextInt());
Scanner score3Input = new Scanner(System.in);
System.out.println("Enter Student's Third Exam Score & Press Enter");
currentStudent.setThirdScore(score3Input.nextInt());
Scanner score4Input = new Scanner(System.in);
System.out.println("Enter Student's Fourth/Final Exam Score & Press Enter");
currentStudent.setFourthScore(score4Input.nextInt());
studentdatabase.add(currentStudent);
Scanner continueInput = new Scanner(System.in);
System.out.println("Enter 'C' to end or 'A' to Add More");
cont = continueInput.next().charAt(0);
//Prints out the arrayList
System.out.println(studentdatabase);
}
while(cont != 'c' && cont != 'C');
//sort the arrayList prior to printing
studentdatabase.sort(Comparator.comparing(Student::getLastName));
//studentdatabase.sort(Comparator.comparing(Students::getLastName).reversed());
for (Student student:studentdatabase) {
System.out.println(student.getLastName() + " " + student.getFirstName() + " : " + student.computeAverage());
}
}
}

How to initialize object variable in another object constructor (more details)?

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.

Computing average in a class

right now I am working on a program that is printing out a students name, id number, scores on exams, average score, and grade. For some reason there is a problem with the method that computes the average score. I have tried adding parenthesis and that didn't change the result either. This ultimately messes up the grade because the grade is calculated with the average score. Any help is appreciated, thanks! Here is my code:
import java.util.Scanner;
public class Student {
private String fname;
private String lname;
private int id;
private int score1;
private int score2;
private int score3;
private double average;
private String grade;
public void readInfo()
{
Scanner k = null;
k = new Scanner (System.in);
System.out.println ("Please enter the first name: (Enter John as first name and Doe as last name to stop) ");
fname = k.next();
System.out.println("Please enter the last name: ");
lname = k.next();
if (fname.equalsIgnoreCase("John")&&lname.equalsIgnoreCase("Doe"))
System.exit(0);
System.out.println("Please enter the student ID: ");
id = k.nextInt();
System.out.println("Please enter the first score: ");
score1 = k.nextInt();
System.out.println("Please enter the second score: ");
score2 = k.nextInt();
System.out.println("Please enter the third score: ");
score3 = k.nextInt();
}
//The problem lies in here:
private void computeAverage()
{
average = score1+score2+score3/3.0;
}
private void computeGrade()
{
if (average>=90&&average<=100)
grade = "A";
else if (average>=80&&average<=89.9)
grade = "B";
else if (average>=70&&average<=79.9)
grade = "C";
else if (average>=60&&average<=69.9)
grade = "D";
else
grade = "F";
}
private String getName()
{
return fname + " " + lname;
}
private double getAverage()
{
return average;
}
public void printAll()
{
System.out.printf("%-9s%-10s %-9s %-3s %-3s %-3s %-5s %-5s", "LastName","FirstName","ID","S1","S2","S3","AVG","GRADE");
System.out.println();
System.out.println("-----------------------------------------------------");
System.out.printf("%-9s%-9s %-9d %-3d %-3d %-3d %-3.2f%-2s",lname,fname,id,score1,score2,score3,average,grade);
System.out.println();
System.out.println("-----------------------------------------------------");
}
}
I guess the problem is because, you are not initializing the variable average anywhere.
Though, you have a method computeAverage(). Its not been called from anywhere in the program. Probably, you might also do it anywhere outside.
And please include parenthesis which will definitely produce the correct result.
Order of operations. What you are doing is sum 1 + sum 2 plus the quotient of sum3 and 3. When you divide, you must divide by exactly what you need to be divided. You should be doing (sum 1+ sum 2+ sum 3)/3
If you don't want to divide by 2, you can also multiply by one half, that won't change anything, but it's just another option.
(sum 1+ sum 2+ sum 3)*1/2
Keep in mind what you want to divide. If it is more term, take advantage of grouping symbols!
{Rich}

Input skipped when using a scanner for text containing spaces

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 ?

Categories