Having a really hard time with this problem. I've tried searching to find a similar situation but I can't seem to find anything that helps. I feel like I've got it 99% of the way and it's probably something very simple but I can't for the life of me figure it out.
I have two classes. ClassA and Restaurant.
The problem is that in my method call for printRestaurant() in the main method of ClassA, some of the methods need to receive the array with restaurant names but when I use the methods, it reprompts for the restaurant names each time it hits the next method instead of only prompting once and then moving to execute the next method.
ClassA:
import java.util.Scanner;
public class ClassA
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String ownerName = "";
System.out.printf("%nWhat is the name of the owner?");
ownerName = input.nextLine();
Restaurant rest = new Restaurant(ownerName);
rest.arraySize();
rest.printRestaurant(ownerName,rest.setRestaurants(),rest.setCustomers(rest.setRestaurants()),rest.calcAvgDailyRev(rest.setRestaurants()));
input.close();
System.exit(0);
}//END main()
}//END Application Class ClassA
Restaurants:
public class Restaurant
{
//Fields
String ownerName = "";
int size = 0;
Scanner input = new Scanner(System.in);
public Restaurant()
{
}//END Restaurant()
public Restaurant(String name)
{
ownerName = name;
}//END Restaurant(String ownerName)
public void arraySize()
{
System.out.printf("%n%s, how many restaurants do you own? ",ownerName);
size = input.nextInt();
}//END arraySize()
public String[] setRestaurants()
{
String[] restNames = new String[size];
input.nextLine(); // clears buffer
for(int row = 0;row < restNames.length; row++)
{
System.out.printf("%nEnter restaurant %d",row+1);
restNames[row] = input.nextLine();
}//END for col < restNames.length
return restNames;
}//END setRestaurants()
public int[] setCustomers(String array[])
{
int[] noCustomers = new int[size];
for(int i = 0;i<noCustomers.length;i++)
{
System.out.printf("%nEnter the average number of daily customers for %s: ",array[i]);
noCustomers[i] = input.nextInt();
}//END for i < size
return noCustomers;
}//END setCustomers()
public double[] calcAvgDailyRev(String array[])
{
double[] avgBill = new double[size];
input.nextLine(); //Clears buffer
for(int i = 0;i<avgBill.length;i++)
{
System.out.printf("%nEnter the average bill for %s: ",array[i]);
avgBill[i] = input.nextDouble();
}//end for i < size
return avgBill;
}//END calcAvgDailyRev(String array)
public void printRestaurant(String name, String restName[], int customers[], double dailyAvg[])
{
System.out.printf("%n%n%S's RESTAURANTS",name);
for(int i=0;i<size;i++)
{
double avgRevenue = customers[i]*dailyAvg[i];
System.out.printf("%n%nRestaurant: %s"
+"%nAverage No of Daily Customers: %d"
+"%nAverage Bill Per Customer: $%,.2f"
+"%nAverage Daily Revenue: $%,.2f",restName[i],customers[i],dailyAvg[i],avgRevenue);
}//END for i < size
}//END printRestaurant()
}//END Restaurant
Here is an example of the desired output:
What is the name of the owner? Cliff
Cliff, how many restaurants do you own? 2
Enter restaurant 1: Eggs
Enter restaurant 2: Bacon
Enter the average number of daily customers for Eggs: 250
Enter the average number of daily customers for Bacon: 200
Enter the average bill per customer for Eggs: 12
Enter the average bill per customer for Bacon: 15
CLIFF’s RESTAURANT
Restaurant: Eggs
Average No of Daily Customers: 250
Average Bill per Customer: $12.00
Average Daily Revenue: $3,000.00
Restaurant: Bacon
Average No of Daily Customers: 200
Average Bill per Customer: $15.00
Average Daily Revenue: $3,000.00
If you need any additional information please let me know. Any help would be GREATLY appreciated.
You need the value returned by the method. But here you are calling the method, and as per the method definition is prompting for input.
So, instead of calling the method, again and again, you can save the return type and use whereever needed.
e.g.
String restName[] = rest.setRestaurants();
int numberOfCust[] = rest.setCustomers(restName);
double dailAvgRev[] = rest.calcAvgDailyRev(restName);
You can use theses values restName, numberOfCust,dailAvgRev to print Restaurant information.
I guess the problem is you don't have a while loop in your main method. So the nextLine() will get executed only once without going back to the scanning routine. You can also define a special string such as "quit" to indicate you want to quit the scanning process.
Try the following maybe? :D
import java.util.Scanner;
public class ClassA {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String ownerName = "";
System.out.printf("%nWhat is the name of the owner?");
while (!(ownerName = input.nextLine()).equals("quit")) {
Restaurant rest = new Restaurant(ownerName);
rest.arraySize();
...
}
input.close();
System.exit(0);
}//END main()
}//END Application Class ClassA
It will keep prompting until you enter the string "quit". Hope it helps.
Related
[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.
I must create 3 arrays, one to hold 5 product IDs, one to hold 5 product prices, and one to hold 5 product inventories. I need a method to print all the product IDs, print all product prices, and print all the inventories. I need a method to allow user to make edits to any of the product IDs, product prices, or inventories (this is the method I am struggling with). After each edit is made I must reprint all the data. I also need a method to print all the correct data after all the edits are made and an extra column, the total price for each product and the overall price. Thanks in advance for any help!
import java.util.Scanner;
public class Inventory {
d public static void main(String[] args) {
String[] productIDArray = new String[5];
double[] priceArray = new double[5];
int[] inventoryArray = new int[5];
input(productIDArray, priceArray, inventoryArray);
print(productIDArray, priceArray, inventoryArray);
edit(productIDArray, priceArray, inventoryArray);
}
public static void input (String[] productIDArray, double[] priceArray, int[] inventoryArray) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Enter the product ID, the price and inventory: ");
productIDArray[i] = input.next();
priceArray[i] = input.nextDouble();
inventoryArray[i] = input.nextInt();
}
}
public static void print (String[] productIDArray, double[] priceArray,
int[] inventoryArray) {
for (int i = 0; i < 5; i++) {
System.out.println(productIDArray[i]);
System.out.println(priceArray[i]);
System.out.println(inventoryArray[i]);
}
}
public static void edit (String[] productIDArray, double[] priceArray, int[] inventoryArray) {
Scanner input = new Scanner(System.in);
int whatToEdit = 0;
String oldProductID = " ";
String newProductID = " ";
double oldPrice = 0;
double newPrice = 0;
int oldInventory = 0;
int newInventory = 0;
String yesNo = " ";
while (true) {
System.out.print("Do you want to make an edit? (Y/N)");
if (yesNo = y.toUppercase) {
System.out.print("Enter what you want to edit: ");
System.out.print("Do you want to edit a product ID (1), price (2), or
inventory (3)? ");
whatToEdit = input.nextInt();
if (whatToEdit == 1) {
System.out.print("Enter the product ID you want to edit and the edit: ");
productID = input.next();
newProductID = input.next();
productIDArray[product] = newProductID;
} else if (whatToEdit == 2) {
System.out.print("Enter the price you want to edit and the edit: ");
oldPrice = input.nextDouble();
newPrice = input.nextDouble();
priceArray[oldPrice] = newPrice;
} else if (whatToEdit == 3) {
System.out.print("Enter the inventory you want to edit and the edit: ");
oldInventory = input.nextInt();
newPrice = input.nextInt();
inventoryArray[oldInventory] = newInventory;
}
}
} else if (yesNo == n.toUppercase) {
break;
}
print(productIDArray, priceArray, inventoryArray);
}
public static void totalPrice (String[] productIDArray, double[] priceArray, int[] inventoryArray) {
}
}
First check which array they want to edit. Then check which part of the array they want to change. You then just take the users input for which piece of the array and the new value for that piece.
Lets say they chose inventory array. Get input for which part of array and then the number to replace it with.
inventoryArray[usersinput] = //Users next inputted number they want to replace it with
EDIT:
To check which array they want to edit you could do something like this.
System.out.print("Enter 1 for product array, 2 for price array, and 3 for inventory: ");
Then read the users input again and use an if or switch statement to decide what to do with whichever array they chose.
EDIT 2:
Problems with your compare and toUppercase. I can't find where your defining the variable 'y' which you are using with your toUpperCase(). So you also need to define that somewhere.
if (yesNo.equals(y.toUppercase()))
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.
I am trying to assign the current array element in the temp array with the Student object returned after calling the getStudent method.... I called the getStudent method (Step 2) and have temp[i] = to assign the current element in the temp array but cannot figure out what it should = to pair it up with the Student object returned. When using getStudent() and running the program, the output is enter the number of students, the user enters the number, and that is all that happens, it does not ask for the user to enter the name and etc, I'm not sure if step 2 is the problem or if there is another issue entirely.
import java.util.Scanner;
public class Students
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Student[] students;
students = getStudents();
printStudents(students);
}
private static Student[] getStudents()
{
Student[] temp;
int how_many;
System.out.print("How many students? ");
how_many = input.nextInt();
purgeInputBuffer();
temp = new Student[input.nextInt()]; // Step 1 ???
for (int i = 0; i < temp.length; i++)
{
getStudent(); // Step 2
temp[i] = ; // <----------
}
return temp; // Step 3
}
private static Student getStudent()
{
String name,
address,
major;
double gpa;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter address: ");
address = input.nextLine();
System.out.print("Enter major: ");
major = input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
purgeInputBuffer();
return new Student (name, address, major, gpa); // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(getStudent()); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
So first problem is first on the line:
temp = new Student[input.nextInt()];
in that line you have already asked the user to enter how many Students and store it in how_many. So i'm assuming you want to instead do:
temp = new Student[how_many];
Also what i said in my comment:
But please do also look at your private static void printStudents(Student[] s) method and acutally on the line //step 6 i don't believe that is how you want to be doing that. Instead you want System.out.println(s[i]); not System.out.println(getStudent()); For my code substitution to work though you will need to Override the toString method so it can actually display the information
I am unsure of how to do this. I am in a intro to java class and it asks us to use a message box (instead of just system.out.println) I remember we imported something and it was an easy change, but I am unable to find any notes on it.
Furthermore all examples I've found across the web and this site are taking it beyond the scope of this class.
I apologize in advance if this is an incorrect format, this is my first time posting here.
TLDR: Trying to change
System.out.print("Enter renter name: ");
renterName = input.next();
to appear in a message box instead of in the Eclipse Console
I know we imported something (same way we import Scanner) to make this work, but every example I find is essentially saying create your own dialog box methods which is beyond my scope of knowledge, and this class.
COMPLETE CODE IS FOLLOWS:
import java.util.Scanner;
public class RentYourVideo {
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
Scanner input = new Scanner(System.in);
String renterName;
System.out.print("Enter renter name: ");
renterName = input.next();
System.out.print("Enter number of videos to rent: ");
numberOfRentals = input.nextInt();
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
System.out.println(renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
input.close();
}
}
//CHANGE ALL PROMPTS & OUTPUT TO DIALOG/MESSAGE BOX!!!!
public class VideoRental {
private int rentalFee, finalBill, numberOfRentals;
public VideoRental() { //constructor method
rentalFee = 0;
finalBill = 0;
}
public void setRentalFee() { //set method
rentalFee = 5;
} //the assignment claims this must set rentalFee = 5
public void calculateBill(int inRented) {
numberOfRentals = inRented;
finalBill = rentalFee * numberOfRentals;
}
public int getFinalBill() {
return finalBill;
}
}
Check this out:
String name = JOptionPane.showInputDialog(null, "Enter name here:");
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
import javax.swing.JOptionPane;
[...]
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
String renterName;
renterName = JOptionPane.showInputDialog(null, "Enter renter name: ");
numberOfRentals = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number of videos to rent: "));
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
JOptionPane.showMessageDialog(null, renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
}