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.
Related
How can I be able to print out the objects that I gave the program in case 2
What I'm trying to implement is case 2 giving me all the info about the stuff I put into case 1
At first I tried to just use the setters and getters but for some reason I was having a NullPointerException when I used the do-while method.
So I decided to use the constructor but at the same time it gave me an error when trying to implement case 2. so any help would be appreciated.
import java.util.Scanner;
public class GameProject {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice;
do{
GameSale[] game;
System.out.println("Hello! welcome to the menu!");
System.out.println("Please Choose your option!");
System.out.println(" 1-Enter a new game's Info \n 2-Check a game's Information \n 3- Check a game's sales \n 0-Exit");
choice = input.nextInt();
switch (choice){
case 0:
break;
case 1:
System.out.println("");
System.out.print("How many games do you want to add? : ");
int size = input.nextInt();
game = new GameSale[size];
for (int i = 0; i < size; i++) {
System.out.print("Enter Game "+(i+1) + "'s Name!: \n");
String tempname = input.next();
System.out.print("Enter the ID of the Game : \n");
int tempid = input.nextInt();
System.out.print("Enter the Game Type : \n");
String tempgametype=input.next();
System.out.print("Enter the development Company's Name : \n");
String tempgamecomp = input.next();
System.out.print("Enter the Release Sale : \n");
double temprelsale = input.nextDouble();
System.out.print("Enter the total Sales : \n");
double temptotsale = input.nextDouble();
game[i]=new GameSale(temprelsale,temptotsale,tempid,tempname,tempgamecomp,tempgametype);
}break;
case 2:
for(int i = 0; i < game.length; i++){
System.out.println(game[i].toString());
}
}while(choice!=0);
}
}
i got a class that has the setters and getters for some of the regular info
public class GameInfo {
protected int ID;
protected String GameName;
protected String DevelopmentCompany;
protected String GameType;
public GameInfo(int ID, String GameName, String DevelopmentCompany, String GameType) {
this.ID = ID;
this.GameName = GameName;
this.DevelopmentCompany = DevelopmentCompany;
this.GameType = GameType;
}
public void SetID(int id) {
this.ID = id;
}
public int GetID() {
System.out.println("The ID is " + ID);
return ID;
}
public void SetName(String Name) {
this.GameName = Name;
}
public String GetName() {
System.out.println("The Name of the Game Is " + GameName);
return GameName;
}
public void SetCompanyName(String CompanyName) {
this.DevelopmentCompany = CompanyName;
}
public String GetCompanyName() {
System.out.println("The Name Of the Development company Is " + DevelopmentCompany);
return DevelopmentCompany;
}
public void SetGameType(String GameType){
this.GameType=GameType;
}
public String GetGameType(){
System.out.println("The Game Type is : "+GameType);
return GameType;
}
}
and a super class with the sales and a constructor for the sales
public class GameSale extends GameInfo {
protected double ReleaseSales;
protected double TotalSales;
public GameSale(double ReleaseSales, double TotalSales, int ID, String GameName, String DevelopmentCompany, String GameType) {
super(ID, GameName, DevelopmentCompany, GameType);
this.ReleaseSales = ReleaseSales;
this.TotalSales = TotalSales;
}
public void SetReleaseSales(double RelSale){
this.ReleaseSales=RelSale;
}
public void SetTotalSales(double totSales){
this.TotalSales=totSales;
}
public double GetReleaseSales(){
System.out.println("The Release Sales Are "+ReleaseSales );
return ReleaseSales;
}
public double GetTotalSales(){
System.out.println("The Total Sales Are "+TotalSales);
return TotalSales;
}
}
Answered by Alex (thanks a lot dude)
here's a temporary fix just for debugging so far by initializing the array dimensions outside the do-while loop
main
import java.util.Scanner;
public class GameProject {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
int choice;
GameSale[] games = new GameSale[1];
do {
System.out.println("Hello! welcome to the menu!");
System.out.println("Please Choose your option!");
System.out.println(" 1-Enter a new game's Info \n 2-Check a game's Information \n 3- Check a game's sales \n 0-Exit");
choice = input.nextInt();
switch (choice) {
case 0:
break;
case 1:
for (int i = 0; i < games.length; i++) {
System.out.print("Enter Game " + (i + 1) + "'s Name!: \n");
String tempname = input.next();
System.out.print("Enter the ID of the Game : \n");
int tempid = input.nextInt();
System.out.print("Enter the Game Type : \n");
String tempgametype = input.next();
System.out.print("Enter the development Company's Name : \n");
String tempgamecomp = input.next();
System.out.print("Enter the Release Sale : \n");
double temprelsale = input.nextDouble();
System.out.print("Enter the total Sales : \n");
double temptotsale = input.nextDouble();
games[i] = new GameSale(temprelsale, temptotsale, tempid, tempname, tempgamecomp, tempgametype);
}
break;
case 2:
for (int i = 0; i < games.length; i++) {
System.out.println(games[i].toString());
}
}
} while ( choice != 0 );
}
}
game info
public class GameInfo {
protected int ID;
protected String GameName;
protected String DevelopmentCompany;
protected String GameType;
public GameInfo(int ID, String GameName, String DevelopmentCompany, String GameType) {
this.ID = ID;
this.GameName = GameName;
this.DevelopmentCompany = DevelopmentCompany;
this.GameType = GameType;
}
public void SetID(int id) {
this.ID = id;
}
public int GetID() {
System.out.println("The ID is " + ID);
return ID;
}
public void SetName(String Name) {
this.GameName = Name;
}
public String GetName() {
System.out.println("The Name of the Game Is " + GameName);
return GameName;
}
public void SetCompanyName(String CompanyName) {
this.DevelopmentCompany = CompanyName;
}
public String GetCompanyName() {
System.out.println("The Name Of the Development company Is " + DevelopmentCompany);
return DevelopmentCompany;
}
public void SetGameType(String GameType){
this.GameType=GameType;
}
public String GetGameType(){
System.out.println("The Game Type is : "+GameType);
return GameType;
}
}
game sale
public class GameSale extends GameInfo {
protected double ReleaseSales;
protected double TotalSales;
public GameSale(double ReleaseSales, double TotalSales, int ID, String GameName, String DevelopmentCompany, String GameType) {
super(ID, GameName, DevelopmentCompany, GameType);
this.ReleaseSales = ReleaseSales;
this.TotalSales = TotalSales;
}
public void SetReleaseSales(double RelSale){
this.ReleaseSales=RelSale;
}
public void SetTotalSales(double totSales){
this.TotalSales=totSales;
}
public double GetReleaseSales(){
System.out.println("The Release Sales Are "+ReleaseSales );
return ReleaseSales;
}
public double GetTotalSales(){
System.out.println("The Total Sales Are "+TotalSales);
return TotalSales;
}
public String toString(){
return this.ID + " " + this.GameName + " " + this.DevelopmentCompany + " " + this.GameType;
}}
Solution
toString()
In your class you should implement a toString() method.
This basically returns all the property values of your object as a String
public String toString(){
return this.ID + " " + this.GameName + " " + this.DevelopmentCompany + " " + this.GameType;
}
Then call it on your object in case2
game[i].toString()
Display
To list all games you have to iterate over your gamesArray and print out the informations with your toString() method;
for(int i = 0; i < games.length(); i++){
System.out.println(game[i].toString());
}
Scope
Create the games array outside of you case1 scope.
GameSale[] game = new GameSale[SomeFixedSize];
If you wanted to print a game's info at a given index in case 2:
if (game == null) { // Break if no game exists
System.out.println("There is no games to show!");
break;
}
System.out.print("Enter game index to show information: ");
int index = input.nextInt();
// Break if index is not in bounds
if (index < 0 || index > game.length) {
System.out.println("Incorrect index");
break;
}
System.out.println("Info of game: " + game[index].toString());
This code should ask for index as input and prints the info of the game and it will print 'There is no games to show!' if there was no any game added yet
Note you must add the toString() method in your GameSale class:
#Override
public String toString() {
return "ID: " + this.ID + " Name: " + this.GameName + " Development Company: " +
this.DevelopmentCompany + " Game Type: " + this.GameType + " Release Sales: " + ReleaseSales + " Total Sales: " + TotalSales;
}
also move the decleration of the game variable out of the scope of the do-while loop (above it) it will look like
GameSale[] game = null;
do { ...
Also if you want case 2 to show all games info you can replace the index part with a loop that iterates the whole 'game' array and prints every element's toString.
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();
So i have this homework, to create a java movie program. It should have the add movie (title, actor and date of appearance), show (all the movies added) and remove movie(by movie title) options.
Up till now i was able to create the addMovie(), and showMovie() methods...but i got really stuck ad removeMovies().
Here is the code for the Main.java:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
static ArrayList<Movies> movHolder = new ArrayList<Movies>();
public static void main(String[] args) {
int op = -1;
while (op != 0){
op= menuOption();
switch(op){
case 1:
addMovies();
break;
case 2:
removeMovies();
break;
case 3:
showMovies();
break;
case 0:
System.out.print("\n\nYou have exited the program!");
break;
default:
System.out.println("\nWrong input!");
}
}
}
public static int menuOption(){
int option;
System.out.println("\nMenu\n");
System.out.println("1. Add new movies");
System.out.println("2. Remove movies");
System.out.println("3. Show all movies");
System.out.println("0. Exit program");
System.out.print("\nChoose an option: ");
option = input.nextInt();
return option;
}
public static void addMovies(){
String t, a, d;
input.nextLine();
System.out.println("\n---Adding movies---\n");
System.out.print("Enter title of movie: ");
t = input.nextLine();
System.out.print("Enter actor's name: ");
a = input.nextLine();
System.out.print("Enter date of apearance: ");
d = input.nextLine();
Movies mov = new Movies(t, a, d);
movHolder.add(mov);
}
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
}
public static void showMovies(){
System.out.print("---Showing movie list---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
}
}
And here is the Movies.java with the Movie class:
public class Movies {
private String title;
private String actor;
private String date;
public Movies (String t, String a, String d){
title = t;
actor = a;
date = d;
}
public Movies(){
title = "";
actor = "";
date = "";
}
public String getTitle(){
return title;
}
public String getActor(){
return actor;
}
public String getDate(){
return date;
}
public String toString(){
return "\nTitle: " + title +
"\nActor: " + actor +
"\nRelease date: " + date;
}
}
As you could probably see, i am a very beginner java programmer.
Please, if there is anyway someone could help with the removeMovie() method, i would be very grateful.
Since you have the index of the movie that should be removed (choice - 1) you can use ArrayList.remove(int)
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
movHolder.remove(choice-1);
You can use the remove(int index) method:
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
// Decrement the index because you're asking the user for a 1 based input.
movHolder.remove(choice - 1)
}
}
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);
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 ?