Parameter usage on the fly when declaring object - java

I am asking the user to input the name and his money value like this.
I tried to do this on the fly like this:
for (int i = 0; i < numOfPlayers; i++) {
players.add(new Player(JOptionPane.showInputDialog("Please enter your name: "), getIntInput(players.get(i).name + " enter your amount of money: ")));
}
getIntInput is a custom method to get int input.
It should work like this:
Please enter your name:
Alex
Alex enter your amount of money:
Whatever int...
Can I do this on the fly, or should I traditionally use another for loop to ask for the money?

Coding like you are, is asking for troubles and difficulties.
Try to follow these steps:
Ask name
Put name in variable
Ask amount of money
Put money in variable
Create Person with name and variable
Instead of trying to do everything in 1 line.

If you look at Wesley's answer, IMO it's the more "obvious" and simple way to achieve your goal.
However, I may suggest you the Builder pattern here.
for (int i = 0; i < numOfPlayers; i++) {
players.add( PlayerBuilder.init().askName().askMoney().create() );
}
public final class PlayerBuilder {
private String name = "-No name-";
private int money = 0;
private PlayerBuilder() {
}
public static PlayerBuilder init() {
return new PlayerBuilder();
}
public PlayerBuilder askName() {
this.name = JOptionPane.showInputDialog("Please enter your name: ");
return this;
}
public PlayerBuilder askMoney() {
this.money = getIntInput(this.name + " enter your amount of money: ");
return this;
}
public Player create() {
return new Player(name, money);
}
private int getIntInput(String msg) {
// ...
}
}
If you want to save some time writing the PlayerBuilder class, you can transfer the dirty job to Lombok. It will to do it on the fly for you...

Related

How to add data into array in another class in Java?

[EDIT: I've solved the problem. I just need to make the arrays static. I can't believe I didn't of that. Thanks for everyone's help!]
I have a bookstore program where people can buy a maximum of 5 different books. Once they choose a title, it will be added to an array for the invoice later. Choosing the titles and putting it into the array is in 2 different classes. Just for trial, I'm buying 2 books: Athletics and Autosport.
Expected output:
You bought 2 book(s)!
1) Athletics Weekly Magazine
2) Autosport Magazine
Edited List.java: I've tried both things. First is changing to i-1
In SportsMag.java:
import java.util.Scanner;
public class SportMag extends Magazine{
Scanner scan = new Scanner(System.in);
public void title() {
System.out.println("");
System.out.println("What do you want to buy?");
System.out.println("1. Athletics Weekly");
System.out.println("2. Autosport");
int choice = scan.nextInt();
List l = new List();
if (choice==1) {
l.totalbooks(1);
l.booknames(1,"Athletics Weekly", "Magazine");
} else {
l.totalbooks(1);
l.booknames(1,"Autosport", "Magazine");
}
System.out.println("Do you want to go back to menu? (Yes/No)");
String back = scan.next();
if (back.equalsIgnoreCase("Yes")) {
BookType b = new BookType();
b.bookMenu();
}
if (back.equalsIgnoreCase("No")) {
l.printInvoice();
}
}
}
In List.java (where I print the invoice):
public class List {
static int total=0;
public void totalbooks(int num) {
total+=num;
}
String[] bookname = new String[5];
String[] booktype = new String[5];
static int a=0;
public void booknames(String newBookName, String newBookType) {
bookname[a]=newBookName;
booktype[a]=newBookType;
a++;
}
public void printInvoice() {
System.out.println("You bought "+total+" book(s).");
for (int i=0; i<total; i+=1) {
System.out.println((i+1)+") "+bookname[i]+" "+booktype[i]);
}
}
}
The output for this is:
You bought 2 book(s).
1) null null
2) Autosport Magazine
I also tried using ArrayList:
In SportMag.Java:
//same as above, only a little difference here
List l = new List();
if (choice==1) {
l.totalbooks(1);
bookname.add("Athletics Weekly");
} else {
l.totalbooks(1);
bookname.add("Autosport");
}
In the List.java:
ArrayList<String> bookname = new ArrayList<String>();
public void printInvoice() {
System.out.println("You bought "+total+" book(s).");
for (int i=0; i<total; i+=1) {
System.out.println(bookname.get(i));
}
}
I got an error in the SportMag.java that says bookname cannot be resolved. A quick fix offered was to create a local variable bookname but then it won't go to the array in List.java
I haven't learned about ArrayList so I'm not really sure what to do here.
I also tried making another version where everything is in the main method and only calls the methods in other classes to display the titles, not actually scanning the input in the other methods. I did this so that no objects die after each functions. The main became really long tho.
I don't know if this works fine for 2 books because I can't loop since everything is in the main.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BookType b = new BookType();
List l = new List();
b.bookMenu();
int booktypechoice = scan.nextInt();
if (booktypechoice ==1) {
Magazine mag = new Magazine();
mag.magtype();
int magtypechoice = scan.nextInt();
if (magtypechoice==1) {
SportMag smag = new SportMag();
smag.title();
int smagchoice = scan.nextInt();
SportMag sportmag = new SportMag();
if (smagchoice==1) {
l.totalbooks(1);
l.booknames("Athletics Weekly", "Magazine");
System.out.println("Do you want to go back to menu? (Yes/No)");
String goback = scan.next();
if (goback.equalsIgnoreCase("Yes")) {
b.bookMenu();
}
if (goback.equalsIgnoreCase("No")) {
l.printInvoice();
}
} else {
l.totalbooks(1);
l.booknames("Autosport", "Magazine");
System.out.println("Do you want to go back to menu? (Yes/No)");
String goback = scan.next();
if (goback.equalsIgnoreCase("Yes")) {
b.bookMenu();
}
if (goback.equalsIgnoreCase("No")) {
l.printInvoice();
}
}
} else {
//all the other book choices goes here.
//It's really long, but it's just like sportmag up there
}
}
}
}
How do I input the book names into the array and have it displayed correctly?
I think you are having trouble with the scope of the variable List l. You create this variable inside the function title and you work with it, inserting in it the product the client requested. But then, where does the variable go from there? It just dies out at the end of the function. This object should be in a scope that will exist for as long as it is interesting.
For exemple, you can transform this variable into a property of your main class. It can be even a static class. You should find the better way to preserve your List object. As it is, it is dying as soon as the title function ends.

Java: How to output user input (multiple Strings/Ints) from another method

I'm brand new to Java, and also new to this site, so please go easy on me. :)
I'm attempting to write a program which will ask the user for several pieces of information. After gathering the information from the user, I then need to call another method to print the information back to the console screen.
The problem that I'm having is that my final method to reprint all of the information to the screen is a wreck, and I don't know where to start to fix it. I ran my code prior to writing and calling the final method (printToScreen), and the program worked as expected with no errors or anomalies. Code is below, and I really REALLY appreciate any assistance.
import java.util.*;
public class Program5 {
//Create constants
public static final int TOTAL_SEATS = 50;
public static Scanner console = new Scanner(System.in);
public static void main (String[] args) {
//Create variables and objects
String courseCode, courseName;
int studentsReg;
int openSeats;
//Call method to print three lines of 55 asterisks to screen
screenBreak();
//Call method to prompt the user for input
promptCodeName();
//Call method to ask for pre-requisites
getPrereqs();
//Call method to ask how many students are currently registered
numStudents();
screenBreak();
printToScreen();
}//Close the main method
public static void screenBreak() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 55; j++) {
System.out.print("*");
} //Close inner for loop
System.out.println();
} //Close outer for loop
} //Close screenBreak method
public static void promptCodeName() {
String courseCode, courseName;
System.out.print("Please enter the course code: ");
courseCode = console.nextLine();
System.out.print("Please enter the course name: ");
courseName = console.nextLine();
}//close promptCodeName method
public static void getPrereqs() {
int numPrereqs;
String listPrereq;
System.out.print("How many pre-requisites does the course have? ");
numPrereqs = console.nextInt();
console.nextLine();
for (int i = 1; i <= numPrereqs; i++) {
System.out.print("List Pre-requisite #" + i + "? ");
listPrereq = console.nextLine();
}//Close for loop
}//Close getPrereqs method
public static void numStudents() {
int studentsReg;
System.out.print("How many students are currently registered for this course? ");
studentsReg = console.nextInt();
}//Close numStudents method
public static int calcAvail (int seatsTaken) {
return (TOTAL_SEATS - seatsTaken);
}//Close calcAvail method
public static void printToScreen () {
String courseCode = console.nextLine;
String courseName = console.nextLine;
numPrereqs = console.nextLine;
int studentsReg = console.nextInt;
String listPrereq = console.nextLine;
System.out.println(courseCode + ": " + courseName);
System.out.print("Pre-requisites: ");
for (int i = 1; i <= numPrereqs; i++) {
System.out.print(listPrereq);
}//Close for loop
System.out.println("Total number of seats = " + TOTAL_SEATS);
System.out.println("Number of students currently registered = " + studentsReg);
openSeats = calcAvail(studentsReg);
System.out.println("Number of seats available = " + openSeats);
if (openSeats >= 5) {
System.out.println ("There are a number of seats available.");
}//Close if loop
else {
if (openSeats <= 0) {
System.out.println ("No seats remaining.");
}//Close if loop
else {
System.out.println ("Seats are almost gone!");
}//Close else
}//Close printToScreen method
}//Close Program5 class
Your problem is becouse courseCode, courseName are local variables which means they are only available in this promptCodeName (for example ofc) method.
If You want to store informations from user in variables, u should create fields in Your class and store informations user in it.
So create fields at the beginning of class (e.q. private String courseCode;)
and then, method should looks like that:
public static void promptCodeName() {
String courseCode, courseName;
System.out.print("Please enter the course code: ");
courseCode = console.nextLine();
this.courseCode = courseCode;
System.out.print("Please enter the course name: ");
courseName = console.nextLine();
this.courseName = courseCode;
}
Read more about "this" word, i think it will let You understand this. :)
Don't forget about scope of your variables. For example in method promptCodeName() you declare local variables courseCode and courseName and assign them to input from console, but you never use this variables (their values). So you have to declare class variables (in the same way as TOTAL_SEATS and scanner) and assign respective values to them or use your local variables from main method, but in this case you have to send them to respective methods as method parameters.

Creating and Returning Values from an ArrayList in Java

I'm working on an assignment for a low-level java class. I have it mostly finished, but I'm stuck on how to use an ArrayList. There are two classes, the second one (PizzaMaker) is the client. I need to initialize an ArrayList in the first class and then add three items to it via user input from the client. I know how to initialize the ArrayList, but I'm having problems adding items to the list. When I run the code I have now, it returns with empty brackets [ ] or null.
I'm not expecting someone to do my homework for me, but a clue as to where I'm going wrong with this code would be helpful.
import java.util.*;
public class Pizza {
private String brand;
private int size;
private ArrayList<String> toppings = new ArrayList<String>();
public Pizza(String brand, int size) {
this.brand = brand;
this.size = size;
}
public void changeBrand(String brandName) {
brand = brandName;
}
public void changeSize(int pizzaSize) {
size = pizzaSize;
}
public void addTopping(String topping) {
toppings.add("topping");
}
public String getPizzaInfo() {
String result = "You want a "+ size +" inch pizza made by: "+ brand +" with these
toppings:" + toppings;
return result;
}
}
public class PizzaMaker {
public static void main( String[] args) {
int size = -1;
String brand = "";
String topping = "";
brand = getBrand();
size = getSize();
topping = getTopping();
Pizza newPizza = new Pizza(brand, size);
System.out.println(newPizza.getPizzaInfo());
}
public static String getBrand() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a brand name: ");
String brandName = kb.nextLine();
return brandName;
}
public static int getSize() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a size: ");
int pizzaSize = kb.nextInt();
kb.nextLine();
return pizzaSize;
}
public static String getTopping() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter topping: ");
String topping = kb.nextLine();
return topping;
}
public static boolean getAgain() {
return true;
}
}
You need to call addTopping. Eg, newPizza.addTopping(topping). Also, correct the addTopping method. Replace toppings.add("topping") with toppings.add(topping);
And I am sure you need to put more effort to learn Java :)
You never added any toppings to your pizza,
Pizza newPizza = new Pizza(brand, size);
// Keep adding toppings, check for empty string to end?
while ((topping = getTopping()).length() > 0) {
newPizza.addTopping(topping); // <-- add the topping to the pizza.
}
System.out.println(newPizza.getPizzaInfo());
You also need to fix your method addTopping
public void addTopping(String topping) {
// toppings.add("topping");
toppings.add(topping);
}
As you specifically asked not to have us do your homework for you (which is good :) ) I will only give you the clues and pseudocode for what you need to do:
Right now you are just creating the Pizza object in PizzaMaker, but you are not doing anything with it. You have already created the methods to retrieve the toppings in PizzaMaker, the method getTopping(). You also have the method to add the toppings to the pizza in Pizza which is addTopping(). Now you just need to call the methods from PizzaMaker so they will be used.
The psuedocode should be like this:
Create the pizza object
For the number of toppings you want to add call getTopping()
For each topping you get you need to add that topping to you Pizza object with your addTopping() method.
Once all the toppings have been added, you can print out your pizza object.
It looks like you want to be able to ask the user for multiple toppings. So as a first approximation, let's assume the topics are single word only, separated by commas (something easy to test using the Scanner you have set up). I recommend two changes to your source code:
First, change the ArrayList of toppings to be called toppingList
private ArrayList<String> toppingList = new ArrayList<String>();
Next, change the addToppings(String toppings) to break the tuple entered by the user into tokens (delimited by spaces):
public void addToppings(String toppings) {
// Let's assume the user enters all toppings as single words delimited
// / by space
StringTokenizer strtok = new StringTokenizer(toppings);
while (strtok.hasMoreTokens()) {
String topping = strtok.nextToken();
toppingList.add(topping);
}
}
Lastly, you will need to call the addToppings method from your main program:
public static void main(String[] args) {
int size = -1;
String brand = "";
String topping = "";
brand = getBrand();
size = getSize();
topping = getTopping();
Pizza newPizza = new Pizza(brand, size);
newPizza.addToppings(topping);
System.out.println(newPizza.getPizzaInfo());
}
One final note: make sure to close your Scanner instances, or you will have a resource leak. It's okay for this simple program, but if it were long-running, you have memory leaks.
To beef up your program, you could try:
Use a different delimiter, allowing multiple words in your toppings (like "Canadian Bacon" - two words),
Modify the getTopping() method to ask for the toppings one-at-a-time until the user presses some special key ("q to quit" is always a good one).
Have fun!
First mistake is you are not calling the methods you have defined in Pizza Class.
You are simply passing by constructor and initilizing the class variable and displaying those variable, but you are not passing the tropping value by constructor.
These below methods you are not calling anywhere .
/*public void changeBrand(String brandName) {
brand = brandName;
}
public void changeSize(int pizzaSize) {
size = pizzaSize;
}*/
Just Use this below code:-
public static void main( String[] args) {
int size = -1;
String brand = "";
String topping = "";
brand = getBrand();
size = getSize();
topping = getTopping();
Pizza newPizza = new Pizza(brand, size);
newPizza.addTopping(topping);
System.out.println(newPizza.getPizzaInfo());
}
Output :-
Enter a brand name:
Manoj
Enter a size:
20
Enter topping:
pizaset 1
You want a 20 inch pizza made by: Manoj with these toppings:[pizaset 1]
Hope it will help you.
Its working now, I have tested.

How do I add strings together with different names

I've already created the ticketAgent and ticketType class and I'm having a tough time trying to add the strings. I've tried using a wrapper class but not sure if that's even the right approach. I've pasted my code and then the prompt respectively. Thanks for the help. I'm a first time poster, so I hope I've followed the posting guidelines.
Prompt:
Write a program called TicketBooth that instantiates at 3 different ticket agents. The TicketBooth program should prompt the user for the ticket agent they wish to purchase a ticket from and then display the list of ticket types and prices that are available. The TicketBooth program should allow the user to make a selection for the ticket to purchase. After a ticket type is selected, the TicketBooth program should display the:
• total sales for that ticket agent
• total number of tickets sold by the ticket agent
• total number of tickets sold by all ticket agents
The TicketBooth program should continue to prompt the user to purchase tickets from one of the ticket agents until the user types quit.
package Exercises;
import java.util.Scanner;
public class TicketBooth {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
String ticketAgent = "sam", "nicole" , "alex";
String ticketType = "one";
int t = Integer.parseInt(ticketAgent);
int s = Integer.parseInt(ticketType);
int sum;
System.out.println("Please select your ticket agent: ");
ticketAgent = input.next();
System.out.println("Please select your ticket type or press -1 to quit: ");
ticketType = input.next();
sum = t +s;
System.out.println("The total tickets that were sold were: " + sum);
}
}
package exercises;
public class TicketAgent {
private static int numOfTicksPerAgent;
private String agentName;
private int numSold = 0;
private double totalSales = 0.0;
public TicketAgent(String agent) {
agentName = agent;
numSold = 0;
totalSales = 0.0;
numOfTicksPerAgent += 1;
}
public void sellTicket(TicketType tt) {
numSold++;
totalSales = totalSales + tt.getticketPrice();
numOfTicksPerAgent++;
}
public double gettotalSales() {
return totalSales;
}
public double getnumSold() {
return numSold;
}
public double getnumOfTicksPerAgent() {
return numOfTicksPerAgent;
}
}
package exercises;
public enum TicketType
{
CHILD (6.50),
ADULT (9.50),
SENIOR (6.50);
private double tikPrice;
TicketType(double price)
{
tikPrice = price;
}
public double getticketPrice()
{
return tikPrice;
}
}
The problem is, that it seems that this is your homework and
nobody wants to make your homeworks for you.
edit: I saw that you added your classes just now.
All you have to do is to add the do while loop
and instantiate your Agents in the right way.
Where, exactly, is your problem? So we can help you better.
My first approach would be, to make it simple,
to write a TicketAgent class and a TicketType class.
Write the TicketAgent in a way, you can put the name of
the agent and the types into the constructor.
TicketAgent agentSam = new TicketAgent("Sam", new ExpensiveTicket());
Add setter and getter methods.
And the TicketType needs a float value for the price and maybe a String description
or something like that.
After you are done with this, go back to your main class.
Open a do while loop and set as the loop argument a boolean
value for the user abort, which is false at the beginning and
changes if the user types in the quit command.
Before the loop, instantiate the Agents with the tickets.
Display names and prices. Display tickets. Count together. Ask for abort.
Hope this helps a little.
And sorry for my english, it is not my mother-tongue.
additional:
private boolean userWantsToQuit = false;
private List<TicketAgent> avaibleAgents = new ArrayList<TicketAgent>();
private List<TicketAgent> usedAgents= new ArrayList<TicketAgent>();
private List<TickeType> boughtTickets= new ArrayList<TicketType>();
main(...){
agents.add(new TicketAgent("Sam"));
agents.add(new TicketAgent("wise"));
agents.add(new TicketAgent("gamgee"));
do{
usedAgents.add(askUserForAgent()); //extra static method
boughtTickets.add(askUserForType(agent)); //extra static method
userWantsToQuit = askUserToQuit();//extra static method
}while(!userWantsToQuit);
displayAgentSummary(usedAgents);
displayTicketSummary(boughtTickets);
}
[...]
public static displayAgentSummary(List<TicketAgent> agents)
{
for(TicketAgent agent : agents)
{
System.out.println("Served by: " + agent.getName());
}
}
public static displayTicketSummary(List<TicketType> tickets)
{
float totalPrice = 0;
for(TicketType ticket : tickets)
{
totalPrice =+ ticket.getPrice();
System.out.println("You bought a " + ticket.getName() + " for " + ticket.getPrice()";
}
System.out.println("You bought tickets in total for " + totalPrice + " dollar".
}

looping, get/set methods, and multiple classes, oh my

I am really struggling with get/set methods. I understand the basic concept - first you set the value then you retrieve it. I am finding it rather difficult to find information about it with the minimal concepts I have already learned. I am on the 6th chapter or my first Java and programming class and it is all online. I created a couple other classes that used set/get methods, but those don't really seem to fit this project.
public class Purchase{
int inv;
double sale;
double tax;
double taxAmount = 0.05;
public int getInv()
{
return inv;
}
public void setInv(int inv)
{
inv = inv;
}
public void setSale(double s)
{
sale = s;
tax = sale * taxAmount;
}
public double getSale()
{
return sale;
}
//display
public void display()
{
System.out.println("Invoice number: " + getInv() + "\nSale amount: $" + getSale() + "\nTax: $" + tax + "\nTotal: $" + (tax + sale));
}
}
import java.util.Scanner;
public class CreatePurchase{
public static void main(String[] args)
{
Purchase one = new Purchase();
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
one.setInv(inv);
}
while(inv < 1000 && inv > 8000);
{
System.out.println("Please enter the amount of your sale. ");
sale = input.nextInt();
}
}
}
The CreatePurchase class is not finished, but I compile it and get the below for every variable every time it appears:
CreatePurchase.java:16: error: cannot find symbol
inv = input.nextInt();
^
It was my understanding that a default constructor is made, so I didn't add one, but called it in CreatePurchase.
Any suggestions?
You've failed to declare the variable inv any where, for example...
public static void main(String[] args) {
Purchase one = new Purchase();
// !! Variable must be declared before it can be used !! //
int inv = 0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
one.setInv(inv);
} while (inv < 1000 && inv > 8000);
{
System.out.println("Please enter the amount of your sale. ");
// This will be your next problem...
sale = input.nextInt();
}
}
Your Purchase class is also going to have problems...
The following method is essentially assigning the value of inv back to itself, which is meaningless in this context...
public void setInv(int inv)
{
inv = inv;
}
Instead, you should be assigning to the instance of the Purchase class's inv variable...
public void setInv(int inv)
{
this.inv = inv;
}
You have at least two problems. First, you can create a new variable with the same name as another variable that's in a bigger container (scope). In this case, the new variable "hides" or "shadows" the outer one. In your setInv method, when you say inv = inv, both invs refer to the innermost variable, the one in the method signature. To save the argument to the class's field, you need to specify the outer inv: this.inv = inv;.
In your CreatePurchase class, you don't have any inv defined; there's one in Purchase, but that's over there, not here. You just need to declare int inv; right after your Purchase one.
Based on these two errors, I would recommend reading an article or tutorial about variable scope in Java to learn the rules about which variables are accessible where.
You havent declared the variable inv in main method, at this step
inv = input.nextInt();
Change your program to below
int inv = 0;
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
if(inv >1000 & inv <8000)
one.setInv(inv);//add to one variable only if its correct,otherwise ignore it
}
while(inv < 1000 && inv > 8000);

Categories