Simplest Dialog/Message Box for beginners? - java

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);
}

Related

How to compare attributes from multiple class instances?

Alright, so here's the pickle. I'm taking this course that teaches logic programming in Java. I only know a bit of JavaScript so Java is pretty much alien tech for me.
I'm doing this assignment where I need to create a conference manager app (which is console-based only). Each conference holds lectures (as many as you want). Each conference has attributes such as the conference manager's name, his telephone number, his hourly rate etc; and it's the same for the lectures. I wanted to be able to input these data with Scanner method. So this is what I did so far:
Started creating two classes:
1) a conference creator
import java.util.*;
public class Conference {
String nameConference;
String nameManagerConference;
String telManagerConference;
String dateStartConference;
String dateEndConference;
float hourlyRateManager;
float hoursAmountConference;
public void setConferenceData() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Conference name: ");
this.nameConference = keyboard.nextLine();
System.out.print("Conference manager name: ");
this.nameManagerConference = keyboard.nextLine();
System.out.print("Conference manager telephone number: ");
this.telManagerConference = keyboard.nextLine();
System.out.print("Conference start date: ");
this.dateStartConference = keyboard.nextLine();
System.out.print("Conference end date: ");
this.dateEndConference = keyboard.nextLine();
System.out.print("Manager hourly rate: ");
this.hourlyRateManager = keyboard.nextFloat();
System.out.print("Conference amount of hours: ");
this.hoursAmountConference = keyboard.nextFloat();
System.out.println(this.nameManagerConference + ", manager of the conference " + "\"" + this.nameConference +"\"" + ", cost R$ " + (this.hoursAmountConference * this.hourlyRateManager));
}
}
2) a lecture creator
import java.util.*;
public class Lectures {
float totalCost = 0;
String lecturesList = "Lectures list: ";
ArrayList<Float> arrLecturesCostTotal = new ArrayList<>();
ArrayList<String> listLectures = new ArrayList<>();
public void getLecturesTotalCost() {
for (int i = 0; i < arrLecturesCostTotal.size(); i++) {
totalCost += arrLecturesCostTotal.get(i);
}
System.out.println("The total lectures cost is $ " + totalCost);
}
public void getLecturesList() {
for (int i = 0; i < listLectures.size(); i++) {
lecturesList += "\n" + "- " + listLectures.get(i);
}
System.out.println(lecturesList);
}
public class Lecture{
String lectureTitle;
String lectureStartHour;
String lecturerName;
String lecturerTelephone;
String lectureDescription;
float lecturerHourlyRate;
float lectureHoursAmount;
float lectureCost = 0;
public void setDataLecture() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Lecture title: ");
this.lectureTitle = keyboard.nextLine();
System.out.print("Lecture start time: ");
this.lectureStartHour = keyboard.nextLine();
System.out.print("Lecturer name: ");
this.lecturerName = keyboard.nextLine();
System.out.print("Lecturer telephone number: ");
this.lecturerTelephone = keyboard.nextLine();
System.out.print("Lecture description: ");
this.lectureDescription = keyboard.nextLine();
System.out.print("Lecturer hourly rate ");
this.lecturerHourlyRate = keyboard.nextFloat();
System.out.print("Lecture hours amount: ");
this.lectureHoursAmount = keyboard.nextFloat();
this.lectureCost = this.lecturerHourlyRate * this.lectureHoursAmount;
System.out.println("The cost of the lecture " + this.lecturerName + " is $ " + this.lectureCost);
arrLecturesCostTotal.add(this.lecturerHourlyRate * this.lectureHoursAmount);
listLectures.add(this.lectureTitle + " by " + this.lecturerName);
}
}
}
As you can see, there are a lot of attributes to each class.
Then, I proceeded to create another class to create the objects using these setters (setConferenceData() and setDataLecture()).
public class Manager {
public static void main(String[] args) {
Conference conference01 = new Conference();
Lectures lectureSet = new Lectures();
Lectures.Lecture lecture01 = lectureSet.new Lecture();
Lectures.Lecture lecture02 = lectureSet.new Lecture();
conference01.setConferenceData();
lecture01.setDataLecture();
lecture02.setDataLecture();
lectureSet.getLecturesList();
lectureSet.getLecturesTotalCost();
}
}
So, one of the deliverables is a comparison between the lectures' costs. I need to return the most and the least expensive lectures (their costs and their names). However, I can't figure out how to do that because I don't know how to compare instances' attributes values. Specially because they're created by inputting data in the console.
My logic is probably wrong as I'm pretty much experimenting and crossing my fingers so I don't see an error in the console, but this is all I could come up with.
Could someone assist me, please?
Few tips here.
You probably should not call Scanner in you data classes. Instead call scanner in your main method and just feed the results to your classes through constructor or setters. This way you separate concerns and classes like Conference and Lecture don't need to know anything about your input method (scanner in this case).
Conference should contain lectures means that List<Lecture> should probably be field inside the class Conference among other fields.
Lecture should probably have two fields (among other stuff) double lengthHours and double hourlyCost. Then you could have a method in Lecture:
public double totalCost() {
return hourlyCost * lengthHours;
}
And then you could have a method in Conference:
public double totalCost() {
double lecturesTotal = 0.0;
for (Lecture lecture : lectures {
lecturesTotal += lecture.totalCost();
}
return lecturesTotal + //other stuff like conference managers pay;
}
Hope that gets you going in the right direction.

Struggling with Java assignment that reads name, age and height

I am working on a java assignment for class. Very basic but just starting to learn programming. The main jist of the assignment is to write a Java program that reads a student name, his/her age, and his/her height (in feet) from the console and prints out all pieces of data related to a student on one line. This is what I have so far but I am getting a few errors.
import java.util.Scanner;
public class assignment1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String Name = Mike;
int age = 21;
double height = 5.9;
Scanner inReader = new Scanner(System.in);
System.out.println("Mike");
Name = inReader.nextLine("Mike");
System.out.print("21");
age = inReader.nextInt("21");
System.out.println("5.9");
height = inReader.nextDouble ("5.9");
System.out.println ("Mike" + "21" + "5.9");
}
}
You are off track in a few ways.
inReader.nextLine("Mike"); should be inReader.nextLine();. You cannot put something between those brackets in this case.
String Name = Mike; int age = 21;double height = 5.9;
just need to be declared. You want to enter the data in the console, not the code itself.
String Name; int age = 0;double height = 0;
System.out.println("Mike"); is not where you put inputs. Rather, it is where you put prompts that go to the user. You want to ask the user for their input there.
To print the variables in a string, you want to put the variable name in the string like so: System.out.println (height);
The full working code is below, but I encourage you to try and understand how this works. Feel free to ask any questions in the comments below.
public static void main(String[] args) {
// TODO Auto-generated method stub
String Name;
int age = 0;
double height = 0;
Scanner inReader = new Scanner(System.in);
System.out.println("What is their name?");
Name = inReader.nextLine();
System.out.println("What is their age?");
age = inReader.nextInt();
System.out.println("What is their height?");
height = inReader.nextDouble ();
System.out.println (Name + " " + age + " " + " " + height);
}
Here ist a first solution to give you a starting point:
public static void main(String[] args) {
String name ;
int age ;
double height;
Scanner inReader = new Scanner(System.in);
System.out.println("Enter name:");
name = inReader.nextLine();
System.out.println("Enter age:");
age = inReader.nextInt();
System.out.println("Enter height");
height = inReader.nextDouble();
System.out.println ("name: " + name + ", age: " +age + ", height: " + height);
}
The above code will work as long as you enter valid input. Try it. Then input something invalid (for example a char for age)

Trying to call a method in another class to use in a IF statement

I am trying to call a class when running an IF statement which will ask the user if they want to view the program in English or Spanish. The Spanish Code is in a different class and I want to call is so when/if the user chooses to view the program in Spanish and disregards the English code written below.
Error: Java cannot find symbol
symbol: method Spanish()
location: variable span of type source.Spanish
Below is my second class(that I want to call):
package source;
import java.util.Scanner;
import java.lang.String;
public class Spanish {
public Spanish() {}
}
And below is how I am trying to call in my main class:
if (language.equals("Span")) {
source.Spanish span = new source.Spanish();
span.Spanish();
}
else {
//More code.
}
My first time asking a question so I am sorry if the format isn't right or if the question has already been answered, I looked at a few of the past questions but no luck so far. Thank you :)
EDIT
package source;
import java.util.Scanner;
import java.lang.String;
public class CashRegister {
public static void main(String[] args) {
String registerfloat;
String input;
String name;
String anotherTransaction;
String item2;
String choice;
String language = "";
double balance;
double cost;
double change = 0;
double cash = 0;
double amountRequired = 0;
double totalAmount = 0;
Scanner in = new Scanner(System.in);
System.out.println("Hello! Welcome to the Cash Register.\n");
while (true) {
if (language.equals("Eng"))break;
if (language.equals("Span"))break;
else {
System.out.println("Which language would you like to use? English (Eng) or Spanish (Span)?:");
language = in.nextLine();
}
}
if(language.equals("Span")) {
source.Spanish span = new source.Spanish();
span.Spanish();
}
else {
System.out.print("Please enter cash register's float: $");
registerfloat = in.nextLine();
balance = Double.parseDouble(registerfloat);
boolean loop = true;
while (loop == true) {
System.out.println("Do you wish to continue this transaction?: (Yes/No)");
choice = in.nextLine();
loop = false;
switch (choice) {
case "Yes":
System.out.print("Please enter the item's name:\n");
input = in.nextLine();
name = input;
System.out.print("Please enter the item's cost:");
input = in.nextLine();
cost = Double.parseDouble(input);
System.out.println("Do you wish to add another item?: Yes/No");
item2 = in.nextLine();
while (true) {
if (item2.equals("No"))
break;
else {
System.out.print("Please enter the item's name:\n");
input = in.nextLine();
name = input;
System.out.print("Please enter the item's cost:");
input = in.nextLine();
cost = Double.parseDouble(input);
System.out.println("Do you wish to add another item?: Yes/No");
item2 = in.nextLine();
}
}
Transaction trans = new Transaction(name, cost);
amountRequired = amountRequired + trans.getCost();
totalAmount = totalAmount + trans.getCost();
System.out.print("Please enter the cash amount tendered: $");
input = in.nextLine();
cash = cash + Double.parseDouble(input);
amountRequired = amountRequired - cash;
balance = balance + cash;
change = cash - totalAmount;
System.out.println("Amount of change required = " + change);
loop = true;
break;
case "No":
balance = balance - change;
System.out.print("Balance of the Cash Register: $" + balance + "\n");
System.out.println("\nThank you for using the Cash Register!");
System.exit(0);
default:
loop = true;
System.out.println("Wrong input, try again!");
break;
}
}
}
}
}
Above is my entire code from CashRegister. "Spanish" has the EXACT same code except the print statements are in Spanish rather than English. Also, sorry if its hard to read or there is unnecessary stuff in there, its a group assignment and in early stages so is a bit of a mess. Cheers
Update 2
package source;
import java.util.Scanner;
public class RunClass {
public static void main(String[] args) {
String registerfloat;
String language = " ";
double balance;
Scanner in = new Scanner(System.in);
System.out.println("Hello! Welcome to the Cash Register.\n");
System.out.print("Please enter cash register's float: $");
registerfloat = in.nextLine();
balance = Double.parseDouble(registerfloat);
while (true) {
if (language.equals("Eng")) break;
if (language.equals("Span")) break;
else {
System.out.println("Which language would you like to use? English (Eng) or Spanish (Span)?:");
language = in.nextLine();
}
}
if (language.equals("Eng")) {
source.CashRegister.CashRegister();
}
else {
// trying to enter Spanish.register here but it does not even show as its not on the current branch.
}
}
}
In your Spanish class you have
public class Spanish {
public Spanish() {}
}
but public Spanish() is not an ordinary method, it's a constructor that only can be called with the keyword new which you already do.
if (language.equals("Span")) {
Spanish span = new Spanish();
span.Spanish();
}
(I removed the package name since it isn't needed) So you need another method in your Spanish class that does the actual work.
The main problem though, apart from the fact that you have duplicated all the code, is that you are trying to do everything in the main() method of CashRegister
I would, for a start, create a simple starting class, lets call it Starter that ask the language question and then lets the CashRegister or Spanish class handle the main functionality.
class Starter {
public static void main(String[] args) {
//Ask question about language as before
if (language.equals("Span")) {
Spanish.register();
} else {
CashRegister.register();
}
}
}
And then you implement a register method in both CashRegister and Spanish that contain the code after else, note that I made the method static
public class CashRegister {
public static void register() {
System.out.print("Please enter cash register's float: $");
registerfloat = in.nextLine();
balance = Double.parseDouble(registerfloat);
//... rest of code
}
}
This should get you started but there are many further improvements that can be done.
If you don't want to have a static method the Starter class needs to be modified as below but I think a static method makes more sense.
if (language.equals("Span")) {
Spanish spanish = new Spanish();
spanish.register();
} else {
CashRegister cashRegister = new CashRegister();
cashRegister.register();
}

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.

Main class java does not return the value i passed in using scanner [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this main class
public class Hotel
{
Scanner scan = new Scanner(System.in);
Register[] items = new Register[15];
int count = 0;
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register deluxe = new Deluxe();
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
run.enterItems();
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
}
public double calcTotal()
{
double total = 0;
for(int i = 0;i<count;i++)
{
total += items[i].total();
}
return total;
}
that is supposed to return the value i put in in the scanner here in the enterItems() that is in the class as the main class
public void enterItems()
{
int type, quantity, sale,night;
double price;
............................
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
}
So this will pass to the class called Deluxe where i have this method called displayInfo()
public class Deluxe implements Register
{
int quantity,night;
double sale;
public Deluxe(){}
....................................
public double total()
{
double total, price = 200.0;
price = price*quantity*night;
total = price - (price * (sale/100));
total += total *.06;
return total;
}
public void displayInfo(){
if (quantity > 0){
System.out.println("Room Type : Deluxe Room");
System.out.println("Quantity: " +quantity);
System.out.println("Discount: " +sale);
}
}
}
the problem is, in checking for quantity > 0, it actually does not get any value that i put in in the scanner. It will always return 0 for quantity regardless what amount i put in.
But the calculation works fine. Calculation is to calculate how many (quantity) rooms book x night stay x the room's price.
The calculation is also in the same class as the displayInfo() which is in class Deluxe.
So i was wondering what did i do wrong here.
The quantity which you input here:
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
Goes into main(String[] args).quantity that's defined here:
public class Hotel
{
....
public static void main(String[] args)
{
...
int quantity, sale,night;
...
}
The quantity that you check here:
if (quantity > 0){...}
Is a different parameter - it's Deluxe.quantity and is defined here:
public class Deluxe implements Register
{
int quantity,night;
...
}
Those two parameters have no relation. If you want them both to be the same, you need to pass to class Deluxe the main(String[] args).quantity parameter. You can do this via your own constructor under Hotel.main(String[] args), like so:
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
quantity = run.enterItems();
Register deluxe = new Deluxe(quantity,0,0); // entering the default value for the other two parameters like the empty constructor would leave them.
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
if you change your enterItems() function to return the quantity parameter you need, like so:
public int enterItems()
{
int type, quantity, sale,night;
double price;
.........
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
return quantity;
}
Notice, this solves this only for the quantity parameter. if you need more, you might need to return the Deluxe structure from enterItems(). Good luck!

Categories