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);
Related
I am trying to write a simple Java program for school that does the following:
Gym Membership: "Write code that will input the customer’s age and number of months, and print the monthly rate and total amount to be charged. Prompt the user for the appropriate input, and display a meaningful output message. Make sure that the months are greater than 0 and the age is greater than 0."
My problems are:
custMonths int is always getting returned as 0 and I don't know why.
I can't seem to find a way to loop back to the start of my selectAge method if the user gives bad input (negative number or zero).
Here is my Java code:
import java.util.*;
public class GymMembership {
public static void main (String[] args) {
//create test customer (customer0) via the constructor
GymMembership customer0 = new GymMembership(70, 12);
customer0.selectAge(customer0.custAge);
customer0.printCustomer();
customer0.getMonthlyRate(customer0.ageNamed);
//prompt user for two integer inputs to create customer1
Scanner scnr = new Scanner(System.in);
System.out.println("Enter customer age, then number of months for contract: ");
GymMembership customer1 = new GymMembership(scnr.nextInt(), scnr.nextInt());
customer1.selectAge(customer1.custAge);
customer1.printCustomer();
}
//the constructor
GymMembership(int custAge, int custMonths) {
this.custAge = custAge;
this.custMonths = custMonths;
}
//instance variables
private int custAge;
private int custMonths;
int monthlyRate;
int childRate = 15;
int adultRate = 25;
int seniorRate = 20;
String ageNamed;
public String selectAge(int custAge) {
Scanner x = new Scanner(System.in);
int age = custAge;
ageNamed = "badInput";
do {
if (age >= 1 && age <= 18) {
ageNamed = "child";
}
else if (age >= 19 && age <= 64) {
ageNamed = "adult";
}
else if (age > 64 && age <= 120) {
ageNamed = "senior";
}
else {
ageNamed = "badInput";
System.out.println("Age must be a positive number between 1 and 120.");
break;
}
} while(ageNamed.equals("badInput"));
return ageNamed;
}
public int getMonthlyRate(String ageNamed) {
if (ageNamed.equalsIgnoreCase("child")) {
monthlyRate = 15;
} else if (ageNamed.equalsIgnoreCase("adult")) {
monthlyRate = 25;
} else {
monthlyRate = 20;
}
return monthlyRate;
}
public void printCustomer() {
if (ageNamed.equals("badInput") != true) {
System.out.println("The customer is a/an " + ageNamed + " and is " + custAge + " years old.");
System.out.println("The customer is signed up for a " + custMonths + " month contract.");
System.out.println("The monthly rate is " + monthlyRate);
}
else {
selectAge(customer1.custAge); //this is broken since I cannot access customer1 object from this "printCustomer" method.
}
}
}
I realize I am very likely making some bad beginners mistakes here as well, but am not quite sure what they are.
You seem to be over-complicating things. Some issues here including
You've got user I/O within the GymMembership class where it doesn't belong. Get it out and into its own UI class or simply the main method.
This includes not using Scanner within GymMembership as you're creating more than one Scanner based on System.in, a dangerous thing to do. Leave that in main.
Get the input in main, and then use it to create your GymMembership object. Repeat as needed.
I/O validation for age and months should also be in main. Again GymMembership should concern itself with just simply holding the state and behaviors of the object.
Or I suppose you could give GymMembership a static boolean method that checks for valid age and months, and use that in the main method to tell if data entered is valid.
The selectAge method is completely unnecessary as you're setting the age in the GymMembership's constructor. Again most of that code should be in the I/O section (main).
This, selectAge(customer1.custAge); isn't valid or necessary. You're within the GymMembership class, the current object's age field is visible to you directly, use it.
Your getMonthlyRate(...) method is dangerous in that it requires that a separate unnecessary field be calculated and passed in as a String, and this String is completely unnecessary, and likely this is causing you problems. The class already knows the information needed to calculate the rate via the age and months fields -- get rid of the String parameter and use the class's own fields.
e.g., the GymMembership class could be as simple as something like:
public class GymMemb2 {
private int age;
private int months;
public GymMemb2(int age, int months) {
this.age = age;
this.months = months;
}
public int getAge() {
return age;
}
public int getMonths() {
return months;
}
public double getMonthlyRate() {
// calculations using age and months for monthly rate
// return result
}
public String print() {
String text = "age: " + age + ", months: " + months;
// also add monthly rate info
return text;
}
}
Then in the main method, create the new Scanner(System.in) again, do this only once, and use it to get input. Within the main you'd use a while loop to keep looping until valid input has been entered, and then create your gym membership object(s). I think that the GymMembership class shouldn't have any println's within it but rather return Strings that may be printed by main if it desires.
Also at the end of main, close the Scanner by calling .close() on it. This should only be done with the program is completely done getting user input, since once closed it may not be reopened.
I am trying to write a java program which have two classes. The second class will have the main method and for checking the balance of the account and. The first class will have three methods one for opening an bank account, one for deposit and one for withdrawal. All input needs to be given by user. I am new to java and stuck after at one point any help would be appreciated.
import java.util.Scanner;
class Balance {
static int account()
{ Scanner minimumAmount = new Scanner(System.in);
int openingAmount = minimumAmount.nextInt();
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account:" + openingAmount);
if (openingAmount > 1000)
{
System.out.println("Your Bank account has opened successfully");
int ac = minimumAmount.nextInt();
System.out.println("Enter your account number" + ac);
}
}
static int withdrawal() {
Scanner withdrawalAmount = new Scanner(System.in);
int w = withdrawalAmount.nextInt();
System.out.println("Withdrawal Amount is :" + w);
int b = openingAmount - w;
if (b < 100) {
System.out.println("Unable to process your request");
}
}
void deposit() {
Scanner depositAmount = new Scanner(System.in);
int d = depositAmount.nextInt();
System.out.println("Deposited amount is :" + d);
int b = openingAmount + d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
}
}
i) Is there a way where an user input variable declared under one method can be used in another method to declare another variable?
ii) ow to return a value from a method so that the value received works in different method while declaring a variable?
Is there a way where an user input variable declared under one method
can be used in another method to declare another variable?
You can declare your attribute in your class and use constructor to initialize it for example :
class A{
private String name;
public A(String name){
this.name = name
}
public int account(){
//can use and change the name
}
public int withdrawal(){
//can use and change the name
}
public int deposit(){
//can use and change the name
}
}
Main class
public class B{
public static void main(String[] args) {
A s = new A("Hello");
//------------^^---pass your attribute in the constructor
s.account();
s.withdrawal();
s.deposit();
}
}
How to return a value from a method so that the value received works
in different method while declaring a variable?
You can use the result of each method in another method for example :
s.withdrawal(s.account());
//--------------^^-------account return a result that can be used by withdrawal
I don't know what you really want to do, but I can explain some things.
Methods account() & withdrawal() don't have to be static.
You can use instance attribute like I do to store values.
Balance & AccountBalance should be in different files.
Take a look about private & public on attribut & methods (& getter/setter)
Scanner is a little bit tricky so you should declare it once, and reuse it.
If you want to use returned value from function, change void by int (in this case) and use "return var" (var is what you want to return). So when you can call the function like this -> int value = s.account();
Try this code, it works.
Cheers !
import java.util.Scanner;
class Balance {
private Scanner scanner;
public int userAccount;
public int userAccountNumber;
public Balance() {
scanner = new Scanner(System.in);
}
public void account() {
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account : ");
int openingAmount = scanner.nextInt();
if (openingAmount > 1000) {
System.out.println("Your Bank account has opened successfully");
userAccount = openingAmount;
System.out.println("Enter your account number : ");
userAccountNumber = scanner.nextInt();
} else {
System.out.println("Not enought money");
this.account(); //Ask again for opening an account
}
}
public void withdrawal() {
System.out.println("Withdrawal Amount is : ");
int w = scanner.nextInt();
int b = userAccount - w;
if (b < 100) {
System.out.println("Unable to process your request");
} else {
userAccount = b;
}
}
public void deposit() {
System.out.println("Deposited amount is : ");
int d = scanner.nextInt();
userAccount += d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
System.out.println("Final amount is : "+s.userAccount);
}
}
I created a method that returns a row of arrays via user input. I managed to display the set of inputted number on the same class using System.out.println by assigning each value in userDigits.
My question is, how can I pass the same value in another class?
public class LottoTicket extends Ticket {
public int NUM_DIGITS = 5;
public int[] userDigits = new int[NUM_DIGITS];
#Override
public void buyTicket() {
Scanner input = new Scanner(System.in);
int number = 0;
double amount = 0;
System.out.println("-------=======LOTTO TICKET SCREEN=======--------");
System.out.println("");
System.out.println("There are three Types (Prima, Ambo and Terro)");
System.out.print("Please select one (P, A, T): ");
String lotteryOption = input.next();
switch (lotteryOption) {
case "P": {
break;
}
case "A": {
break;
}
case "T": {
amount = getAmount(amount);
getUserData(userDigits);
int ticketSold;
ticketSold = +1;
int tik = ticketSold +1;
System.out.println(amount);
System.out.println("Your numbers are: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " ");
System.out.println("Ticket/s Sold: " + tik);
System.out.println("Thank you for playing");
Ticket.pressAnyKeyToContinue();
LotteryApplication.loginScreen();
break;
}
default: {
System.out.println("Invalid Input. Please try again.");
System.out.println("");
buyTicket();
break;
}
}
}
#Override
public double getAmount(double amount) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter amount of money: ");
amount = input.nextDouble();
//input.close();
return amount;
}
#Override
public int getUserData(int[] userInput) {
Scanner input = new Scanner(System.in);
System.out.print("Choose a number from 1 to 90: ");
userDigits[0] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[1] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[2] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[3] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[4] = input.nextInt();
//key.close();
//Returns last value of array
return userDigits[4];
}
//public int userDigits[];
public static void printTicket(){
// System.out.println(getUserData.userDigits[4]);
// for (int i = 0; i < array.length)
}
}
Well, in this case, since you defined userDigits as public, you can do it easily - it is accessible to any class that has a visibility to your instance of LottoTicket. With the current setup you could do something like this:
// you need to instantiate LottoTicket somewhere in your app
LottoTicket ticket = new LottoTicket();
// get the input from user
ticket.buyTicket();
// at this point you can access the numbers and pass them to some other method like this
checkNumbers(ticket.userDigits);
The example posted above needs you to provide a method checkNumbers that has, for example, the following signature:
public void checkNumbers(int[] numbers) {
// the comparison code goes here...
Also, this is somewhat unrelated to your question, but I'd like to point out two issues with your current code:
defining class fields as public is done rather rarely, more common approach is to define these as private and provide methods for getting/setting the field values; this restricts the operation on these fields to only those you allow - having public field allows anyone who has a visibility to that field to perform basically any operations, which is usually not what you want
you call buyTicket() from default in case user didn't select valid lottery type; in extreme cases this could lead to StackOverflowError - better approach would be to use a loop that keeps asking user for input until a valid one is provided
Hope this helps at least a bit.
You can easily pass input array to method of another class arguments.
class PassValue{
public static void display(int[] elements){
Anotherclass obj= new Anotherclass();
obj.display2(elements);
}
}
class Anotherclass{
public void display2(int[] values){
do whatever you want
}
}
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".
}
I have tried various suggestions already given on the website.. But honestly i couldnt find something to fix it.
Basically when i try to use any variable created in Accept... it cant be used in other functions. Is there a simple solution to fix this? (Without changing the main code)
import java.util.Scanner;
class x4Salary
{
Scanner input = new Scanner(System.in);
public void accept()
{
System.out.println("Please input the name of the teacher");
String name = input.next();
System.out.println("Please input the address ");
String adress = input.next();
System.out.println("Please input the phone number");
long num = input.nextLong();
System.out.println("Please input the subject specialization");
String subjectSpecialization = input.next();
String subS = subjectSpecialization;
System.out.println("Please input the Monthly Salary");
long sal = input.nextLong();
if(sal>175000)
{
tax();
}
display();
double tax = 0.0;
}
public void tax()
{
System.out.println("Your current salary is : " + sal);
tax = sal + ((5/sal)*100);
System.out.println("The salary + Tax : " +tax);
display();
}
public void display()
{
System.out.println("The name of the teacher : " + name);
System.out.println("The Address of the teacher :" +adress);
System.out.println("The Phone number of the Teacher: "+num);
System.out.println("The Subject Specialization of the Teacher" + subS);
System.out.println("The Monthly salary of the teacher" +sal + tax);
}
}
You can make those variables as class members
class x4Salary
{
protected String name, address; //and so on
and then instead of String name = input.next();
name = input.next();
name would be visible in all methods of X4Salary
Those variables are scoped to the method alone. If you want to retain those values entered your options are:
create member variables in the containing class and populate those. Those values would be available for the lifetime of that class
return the values from the method. Since you have multiple values you would likely want an object containing these values to be returned
call another object from within that method, and pass the data that way.
For option 2 you could define a return object thus:
class Teacher {
private String name;
private String phone;
// add appropriate constructor
}
I suspect Teacher is a key object in your application and you would likely want to add the method display() to the Teacher class itself. Remember that OO is about creating objects and getting them to do things for you, not handling discrete related variables yourself.
you cant use the local variables(variables defined inside your method) outside of that method. they are only confined to that method. you either have to make it an instance variable or return that variable so that the other methods can use it.
in your case.
if you want to use sal outside method accept . make it an instance variable.
Class classname {
public long sal;
public void accept(){
//can access sal here
sal = input.nextLong();
}
public void display(){
//cvan access sal here
}
}
Define your variables as Member Variables in the Class then it can be accessible in all the member methods.
import java.util.Scanner;
class x4Salary
{
private double tax=0.0;
private string name, adress, subS;
private long num, sal;
Scanner input = new Scanner(System.in);
public void accept()
{
System.out.println("Please input the name of the teacher");
name = input.next();
System.out.println("Please input the address ");
adress = input.next();
System.out.println("Please input the phone number");
num = input.nextLong();
System.out.println("Please input the subject specialization");
subS = input.next();
System.out.println("Please input the Monthly Salary");
sal = input.nextLong();
if(sal>175000)
{
tax();
}
display();
}
public void tax()
{
System.out.println("Your current salary is : " + sal);
tax = sal + ((5/sal)*100);
System.out.println("The salary + Tax : " +tax);
display();
}
public void display()
{
System.out.println("The name of the teacher : " + name);
System.out.println("The Address of the teacher :" +adress);
System.out.println("The Phone number of the Teacher: "+num);
System.out.println("The Subject Specialization of the Teacher" + subS);
System.out.println("The Monthly salary of the teacher" +sal + tax);
}
}
You would need to make those variables as instance variables.
The variables created in a method, in confined to that method scope only. It is not visible outside that method. It will be created when the method is invoked, and then when the method is finished with execution, that variable becomes eligible for Garbage Collection.
This is true for any block scope you have. The variables created in one block, will not be visible outside that block.
For e.g: -
{ // A block
int num = 10;
}
System.out.println(num); // Error. num not visible here.
So, to access the variable in all methods, declare it as: -
public class Demo {
private int num; // Instance variable declaration. Outside every method.
public void setNum(int num) {
this.num = num;
}
public int getNum() {
return this.num;
}
}
So, as you can see, variable num is used in both the methods: - setNum and getNum.
Go to this tutorial to get started with classes, objects, and member declarations: -
http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html