I've started writing my own Java program during my freetime called the "Book A Ticket Machine", it's a Java console program with no GUI. It will Ask you for your FullName, FrequentFlyer ID, Age, then match you to your designated airline and flight number. While you travel your fuel will decrease and when it lands the fuel will fill up (I will create a fill method for this). I am having problems with calling a method from outside a scope.
Currently I have two files:
Flights.java --> Launching file. Linked with flightUserDatabase.
flightUserDatabase.java --> Contains all methods and class/blueprints all username, age, frequentFlyer, etc.
Code from Flights.java:
import java.io.Console;
public class Flights {
public static void main (String[] args) {
Console console = System.console();
//Book a Ticket Machine
//From Database otherwise Name not found on Database. Put Database in Another Class. Call it flightUserDatabase.
/* firstName: DONE
lastName: DONE
frequentFlyerID: Otherwise Invalid Number parseInt
Age: parseInt
FUEL MINUS AND FUEL ADD WHEN LAND.
*/
flightUserDatabase database = new flightUserDatabase();
System.out.println("Enter Creditials: ");
database.getDatabase();
String airline = console.readLine("ENTER YOUR AIRLINE: ");
String flightNumber = console.readLine("ENTER YOUR FLIGHT NUMBER: ");
String gate = "B7"; /* Declare data type String called "gate" */
//Next Version, Generate Random Number
System.out.println("This is an automated system. Please Wait...");
System.out.printf("%s %s is Departuring # Gate:%s \n", airline, flightNumber, gate); /* Use printf from java.io.Console library, then output Gate and Flight Number */
/* Notes: Data Types
> String name = "Ohm";
> int age = 42;
> double score = 95.5;
> char group = 'F';
*/
}
}
Code from flightUserDatabase.java:
import java.io.Console;
//Book a Ticket Machine
class flightUserDatabase {
Console console = System.console();
public String fullName;
public boolean getDatabase() {
boolean namesInDatabase;
do {
fullName = console.readLine("ENTER YOUR FULLNAME: ");
namesInDatabase = (fullName.equals("Ohm Passavudh") || fullName.equals("Matt"));
if (!namesInDatabase) {
console.printf("Sorry, that name is not in our database yet. \n");
}
if (namesInDatabase) {
console.printf("Welcome, Mr. %s \n", fullName);
}
} while(!namesInDatabase);
return namesInDatabase;
}
//If Ohm: FFID = 1234569
//If Matt: FFID = 246810
//FFID == FrequentFlyerID
/* Get name from inside scope fullName namesInDatabase variable */
public boolean frequentFlyerID()
I HAVE PROBLEMS HERE!!! I WANT TO SET Ohm's FFID to 1234569. But how to I determine if the user enters Ohm or Matt. I cannot access the String fullName from the other scope. I hope you understand me. If there is any misunderstanding I can clarify.
}
First, please, do work on your formatting, reading that code was awful.
You can create a class field and a getter in flightUserDatabase, so you can get the name after you've determined the name is in the database.
Or you can return it with getDatabase()
Like this...
public String getDatabase()
{
String fullName;
...
return fullName;
}
After all, you're not using that boolean.
... or this ...
class flightUserDatabase
{
private String fullName = "";
...
public String getName()
{
return this.fullName;
}
}
You have to initialize variable public String fullName; -> public String fullName = "";
Work on formating code
Name class begin from upper sign in your case FlightUserDatabase
Remember about encapsulation (private variable)
Related
Okay, so I'm working on a homework assignment where I have a staff of 10 salespeople. We have a contest for the greatest number of sales. The assignment wants the user to enter 10 integer values as a number of sales and then once they've all been entered the salesperson with the highest value will be returned.
What she wants:
A Class "Sales" with (String name and Integer sales) values.
A while loop where the user inputs integers for number of sales
What I'm attempting to do. I assume the names of the salespeople at the company are known, so I just created an array strSalesPerson of 10 fictitious names. I created a counter salespersonCounter to create the counter for the while loop for user input. I'm trying to basically create salesperson1, salesperson2, salesperson3, and so on by creating a variable with the string "salesperson" concatenated with the counter. I want to use that as the name of the instance for each salesperson entered into the Sales Class.
Sales Class
Just for reference, the class I've created and trying to create instances of is as follows:
private String salesname;
private Integer numsales;
public Sales(String name, Integer sales) {
this.salesname = name;
if (sales >= 0.0) {
this.numsales = sales;
}
}
// Setter for name
public void setName(String name) {
this.salesname = name;
}
// Getter for name
public String getName() {
return salesname;
}
// Setter for Sales
public void setSales(Integer sales) {
if (sales >=0) {
this.numsales = sales;
}
}
// Getter for Sales
public int getSales() {
return numsales;
}
} // End of Class
TestSales
This is where I will get the user input and save it as an instance of the Sales class. However, right now I'm just going to use the current instance from the array of names and the static integer 3 to ensure that I get the other pieces functioning correctly and then I'll switch over to user inputs from there.
// Import Scanner
import java.util.Scanner;
public class TestSales {
public static void main(String[] args) {
// create scanner to obtain input from command window
Scanner input = new Scanner(System.in);
// Initialize variables
int salespersonCounter = 1;
// Fill Salesperson names
String[] strSalesPerson = new String[]{"Mark Hasselback","Gary Moore","Shelly Hemingway", "Susan Meagre","Nick Pantillo","Craig Grey","Alice Reese","Mickey Greene","Chaz Ramirez","Kelly Southerland"};
while (salespersonCounter <=10) {
String salespersoninstance = ("salesperson"+ salespersonCounter);
String currsalesperson = strSalesPerson[salespersonCounter -1];
System.out.printf("%s");
Sales salespersoninstance = new Sales(strSalesPerson[salespersonCounter -1],);
System.out.printf("%s is %s!%n",salespersoninstance,currsalesperson);
salespersonCounter += 1;
}
}
}
The problem I am running into is here:
Sales salespersoninstance = new Sales(strSalesPerson[salespersonCounter -1],3);
instead of accepting the string value of salespersoninstance (in this case salesperson1) as the name of the instance of the Sales Class, it is telling me that salespersoninstance is a duplicate local variable. It is interpreting it I guess as me trying to define a new variable with the same name as one I've already declared?
Basically what I want is with the while counter, create a string variable salesperson1, salesperson2, salesperson3 and so on with "salesperson" + salespersonCounter, and use that resulting string to name the instance of the Sales class. That way I can then say Sales salespersoninstance = new Sales(strSalesperson[salespersoncCounter -1], userinput)
To help you a bit forward:
String[] salePersonNames = new String[]{"Mark Hasselback", "Gary Moore", "Shelly Hemingway", "Susan Meagre", "Nick Pantillo", "Craig Grey", "Alice Reese", "Mickey Greene", "Chaz Ramirez", "Kelly Southerland"};
for (int i = 0; i < salePersonNames.length; i++) {
Sales salesPerson = new Sales(salePersonNames[i], 3);
System.out.printf("%s is %s!%n", salesPerson.getName(), salesPerson.getSales());
}
So I've been given the method below and I'm not allowed to change it. What I need is it to create a couple of objects with the variables below but keeps coming up with an error that says "The constructor menu(int, String, String) is undefined." Am I doing something wrong?
import java.util.Scanner;
import java.util.*;
public class menu {
private static void addNewStudent()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the correct details below");
System.out.println("ID: ");
int userId = scanner.nextInt();
System.out.println("First name: ");
String userFirst = scanner.next();
System.out.println("Last name: ");
String userLast = scanner.next();
System.out.println("English assignment 1 mark: ");
int english1 = scanner.nextInt();
System.out.println("English assignment 2 mark: ");
int english2 = scanner.nextInt();
System.out.println("English assignment 3 mark: ");
int english3 = scanner.nextInt();
System.out.println("Math assignment 1 mark: ");
int math1 = scanner.nextInt();
System.out.println("Math assignment 2 mark: ");
int math2 = scanner.nextInt();;
System.out.println("Math assignment 3 mark: ");
int math3 = scanner.nextInt();
menu userStudentObj = new menu(userId, userFirst, userLast);
menu userEnglishObj = new menu(english1, english2, english3);
menu userMathObj = new menu(math1, math2, math3);
// Asks the user for the student information (ID, First, Last, Assignments)
// Then creates the appropriate objects and adds the students to the student list
I would expect to have created 3 new object that contain the user input variables within the objects if that makes sense.
The main problem is that you didn't specify any non default constructor, to create objects so compiler have no ideas what do you want to create if object is not specified for that. But there is another problem. Your object is designed in not the best way. So if you want to handle it correctly you could change your class design so you handle it in right way.
For example you could make it a bit different, like in this example (it's not perfect, it still can be more separate and better designed):
class User {
int userId;
String userFirstName;
String userSecondName;
private ArrayList<Integer> mathSums = new ArrayList<>();
private ArrayList<Integer> englishSums = new ArrayList<>();
User(int userId, String userFirstName, String userSecondName) {
this.userId = userId;
this.userFirstName = userFirstName;
this.userSecondName = userSecondName;
}
public void addMathSums(int mathSums) {
this.mathSums.add(mathSums);
}
public void addEnglishSums(int englishSums) {
this.englishSums.add(englishSums);
}
}
So by the help of this class you could change the way, how you define and set the values for your object and it would look like that:
1) You define constructor with arguments so you're able to use it for object creation:
User user = new User(userId, userFirst, userLast);
2) Then you can add sums into ArrayLists that are member variables (fields) in User class:
user.addMathSums(math1);
user.addMathSums(math2);
user.addMathSums(math3);
user.addEnglishSums(english1);
user.addEnglishSums(english2);
user.addEnglishSums(english3);
It could be performed in different ways using arrays, lists or other data structure, but you really need to pay attention for your class design. More time you spend on designing object less modifications you will need later.
3) You probably want to interact with this object so you need to get a reference for it somehow. You could change the method signature so you will "return" created object after you finish your input. So you need to make some changes:
On the method change the signature return type to User:
private static User addNewStudent() { ... }
Then add return for that and return created user:
private static User addNewStudent() {
/* code */
User user = new User(userId, userFirst, userLast);
/* add sums */
return user;
}
4) Use this method in your main():
public static void main(String[] args) {
User createdUser = User.addNewStudent();
}
I am working on a program that stores data in an Array from the user and outputs that data.
For example:
An input:
Happy HAPPY#foo.com
The output:
NAME: Happy
EMAIL: HAPPY#foo.com
I was hoping someone could look at what I've got so far and give me a pointer on how to continue. I know I have to use the scanner class and scan.nextLine, I'm not sure what comes next. I understand I don't have much, I'm not looking for someone to complete this, but maybe someone who can give me some pointers or point me in the right direction. I believe I have the correct base to my program.
My Code So Far:
import java.util.ArrayList;
import java.util.Scanner;
public class Program5 {
void loadContacts()
{
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine());
scan.close();
}
void printContacts()
{
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
}
Better name the class "person" or like this, but nevermind for the explanation :
public class Program5 {
private String name;
private String mail;
public Program5(){}
void loadContacts(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a name and a mail like this : name email#email.com (separate with ' ')");
String[] line = scan.nextLine().split(" ");
while(line.length!=2){
System.out.println("Again, enter a name and a mail like this : name email#email.com (separate with ' ')");
line = scan.nextLine().split("/");
}
this.setName(line[0]);
this.setMail(line[1]);
scan.close();
}
void printContacts() {
System.out.println("NAME : "+this.name+"\nEMAIL : "+this.mail);
}
public static void main(String[] args) {
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
public void setName(String name) {
this.name = name;
}
public void setMail(String mail) {
this.mail = mail;
}
}
In the loadyou ask the user, check it he enter 2 element separate by '/' and if yes store them as attributes to be able to get them in another method ;)
You should have a global varible to store the name and the email. Try adding these lines on the top of the code. after public class Program5 {.
private String Name, Email;
The you must assing this values to void loadContacts(). Spliting the string you read.
void loadContacts()
{
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String arr[] = input.split("\\s+");
Name = arr[0];
Email = arr[1];
scan.close();
}
And finally on void printContacts().
void printContacts()
{
System.out.println("NAME: " + Name + "\nEMAIL: " + Email);
}
Here is the code runnig: http://ideone.com/mjyfHK
You can do a variety of things.
You can make loadContacts() and printContacts() static methods, and also change loadContacts() so that it returns an Array or 2D array or however you choose to represent a name-email pair. Then change printContacts()` to take in that type and iterate through that Array to print out each name/email pair. This solution is a bit more work but you won't have to create an object of the same class within the main method of that class.
or
You can keep your method as they are and instead create a new field for the program class, called contacts and it would be of the type that you choose for representing name/email pairs. You would add items to contacts in loadContacts() and iterate through it in printContacts(). Then you don't have to change anything in your main method.
I have a text file containing all the persons in my program (staff, employee, instructor, and students) and their relevant information depending on the type of person. I have a directory class with all my methods, and a directoryServer which is the interface class.
My add method is not working properly because when I add a new type of person, it sets the first four fields to null when I try to update my text file. Also after I add a new person and then try to find (find is another method in my program), it says the name is not in the directory even though it is. The fields after the fourth field are what the user inputted, which is showing in my text file correctly.
This is my add method and close method in my directory class:
public boolean add(Person obj) throws IOException {
boolean added = true;
String s = obj.toString();
dir[directorySize++] = s;
return added;
}
public void closeDirectory() {
directoryDataIn.close();
PrintStream directoryDataOut = null;
try {
directoryDataOut = new PrintStream(directoryFile);
}
catch (FileNotFoundException e) {
System.out.printf("File %s not found, exiting!", directoryFile);
System.exit(0);
}
String originalDirectory[] = {"Staff 77778 Julie Chang Registrar","Adjunct 19778 Mike Thompson CS mtxxx#gmail.com GITC2400", "Staff 30041 Anne Mathews Security","Junior 98444 Serene Murray Math smyyy#gmail.com", "Freshman 98772 Bob Mathew CS bmyyy#gmail.com","Professor 19010 Joan Berry Math jbxxx#gmail.com GITC2315C","Professor 19871 Aparna Khat CS akxxx#gmail.com GITC1400","Adjunct 18821 Hari Mentor Physics hmxxx#gmail.com CK231","Staff 20112 Jim George Plant","Junior 68339 Tom Harry CS thyyy#gmail.com","Senior 78883 Vince Charles IT vcyyy#gmail.com","Freshman 87777 Susan Han EE shyyy#gmail.com","Senior 88888 Janki Khat IE jkyyy#gmail.com","Staff 5555 Aparna Sen Plant","Senior 66663 Jill Kaley it jk#jk.com","Staff 77777 Joe Batra plumbing","Staff 33333 Jim Natale Plumbing"};
if (originalDirectory == dir) //do not update text file if no changes were made
System.exit(0);
else
for (int i = 0; i < directorySize; i++)
directoryDataOut.println(dir[i]);
directoryDataOut.close();
}
And this is what an excerpt of my text file is supposed to look like:
Senior 88888 Janki Khat IE jkyyy#gmail.com
But it comes out like this instead:
null null null null MATH rwood#njit.edu
How can I fix this?
For some reason, this faulty output just came today. I closed and saved all my class files last week when everything was working correctly.
This is my Person class
public class Person {
private String Position;
private String UCID;
private String FirstName;
private String LastName;
public Person(String Position, String UCID, String FirstName, String LastName) {
Position = Position;
UCID = UCID;
FirstName = FirstName;
LastName = LastName;
}
public String toString() {
return String.format("%s %s %s %s", Position, UCID, FirstName, LastName);
}
}
And this is from my directoryServer class. In this excerpt of code I'm adding a professor or adjunct. Before this part I'm just using a scanner object to get user input for each field line by line.
p = new Instructor(pos, ucid, fname, lname, dept, email, office);
try {
d.add(p);
}
catch (Exception e) {
System.out.println("Error, cannot add");
continue;
}
The problem is the in Person class. You need to use statements like:
this.Position = Position
else you are just assigning local variables to local variables.
Additionally, for stylistic reasons, you want instance variables (fields) to be lower case.
In your add method line:
String s = obj.toString();
Probably returns wrong String representation of Person class. Have you properly overwritten public string toString() method?
In the same method I would also advice to take care of line:
dir[directorySize++] = s;
arrays have fixed size, which is specified during the initialization. In some point in the future you will face IndexOutOfBounds exception, as there will be no space for inserting new record. I would suggest using LinkedList instead, which can be dynamically enlarged with new records.
All in all it is pretty hard to give specified solution for your problem without seeing Person class, and your code, which is responsible for populating your text file
I am running into some issues with my Java program. We have to create a library, which contains the title(halo, lotr) , the format (xbox, dvd etc), the date loaned (if it is ever loaned), and the person it is loaned to (if it is ever loaned).
I am not complete with my code, however I am testing it out as I go along instead of just compiling the entire finished code after 5 hours of coding. I am running into a problem. Whenever I set a public string variable to a value, it saves in the method I declared it in, but it will display "null" when system.out.print'd in other methods.
heres my code. First class is Library.
package p1;
import java.util.Scanner;
public class Library {
// \/ FIELDS
private String[] mediaItemTitle = new String[100];
public String[] mediaItemFormat = new String[100];
public String[] mediaItemLoanedTo = new String[100];
public String[] mediaItemOnLoan = new String[100];
public String[] mediaItemDateLoaned = new String[100];
public String today = "3/9/2015";
public int numberOfItems;
// /\ FIELDS
// \/ METHODS
public static void main(String[] brad){
Scanner input = new Scanner(System.in);
MediaItem main;
main = new MediaItem();
String title;
String format;
String date;
String name;
for ( int i = 0; i != 5; ){
i = displayMenu();
if (i == 1){
System.out.println("What is the title? ");
title = input.nextLine();
System.out.println("What is the format? ");
format = input.nextLine();
main.MediaItem(title,format);
}else if (i == 2){
System.out.println("Which Item (Enter the title? ");
title = input.nextLine();
System.out.println("Who are you loaning it to? ");
name = input.nextLine();
System.out.println("When did you loan it to them? ");
date = input.nextLine();
}else if (i == 3){
main.MediaItem();
}else if (i == 4){
System.out.print("Which item? (enter the title) ");
title = input.nextLine();
main.markReturned(title);
}else if (i == 5){ // DONE
System.out.print("Goodbye!");
break;
}
}
}
public static int displayMenu(){ // DONE
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("1. Add new item");
System.out.println("2. Mark an item as on loan");
System.out.println("3. List all items");
System.out.println("4. Mark an item as returned");
System.out.println("5. Quit");
choice = input.nextInt();
return choice;
}
public void addNewItem(String title, String format){
this.mediaItemTitle[numberOfItems] = title;
this.mediaItemFormat[numberOfItems] = format;
System.out.print("TEST: " + mediaItemTitle[numberOfItems]);
}
public void incrementNumberOfItems(){
numberOfItems++;
}
public void listAllItems(){
for (int i = 0; i < numberOfItems; i++){
System.out.print(mediaItemTitle[i])
}
}
Here is the second part of code, my second class MediaItem
package p1;
public class MediaItem {
// \/ METHODS
public void MediaItem(){
Library list;
list = new Library();
list.listAllItems();
}
public void MediaItem(String title, String format){
Library call;
call = new Library();
call.addNewItem(title, format);
call.incrementNumberOfItems();
}
// /\ METHODS
}
This is driving me insane. I would love to just have me public variables save their value between methods but its not happening. the console (when 3 is chosen from displayMenu)
0
null
which means numberOfItems and mediaItemTitle[i] are read to be 0, and null. Which I dont understand, because I declared them earlier in the program!!!
I dont understand what Im doing wrong. please help me! Thank you!!
Your main mistake is that you are creating a new instance of Library inside your MediaItem method. That Library object will only live in the scope of MediaItem method. Plus Library is your main static class.
Your design is all wrong in my opinion. It looks like you are learning you way to Java or OOP, which is perfectly fine to have these mistakes.
Separate your data from your main class, create new classes just for your data. Have a look at java POJO (Plain Old Java Objects), like here
For example:
String title;
String format;
String date;
String name;
Should be in a new object, a POJO. Something like:
public class MyDataPOJO {
private String title;
private String format;
private String date;
private String name;
public MyDataPOJO(String title, String format, String date, String name) {
this.title = title;
this.format = format;
this.date = date;
this.name = name;
}
public String getTitle() {return title;}
public String getFormat() {return formate;}
// And the rest of the getter methods for date and name
}
In you Library class you may only need to hold your logic. But even that can be re-factored to another class.
On a side note, please check the java naming convention. Here is a guideline: link. In other words, start you methods name with lower case.
Example, your public void MediaItem(){/** something*/} should be public void mediaItem(){/** something*/ }
Follow the answer above and treat this as a comment, since the persons answer is correct and my statement isn't regarding your primary problem.
In your for-loop, I think you should add another else if statement. If the user enters a number that is not 1-5, they should receive an error. So maybe something like
else if (i < 1 || i > 5)
System.out.println("Error: Enter a choice 1-5\n");
Also, I think you may have forgotten a } to end your listAllItems() method.
But as I was saying, the answer to your real problem has already been handled, so give them the check mark. This is just a minor UI error I noticed.