I'm trying to make condition in which
If an invoice number is less than 1000, force the invoice number to 0.
If the month field is less than 1 or greater than 12, force the month field to 0.
If the day field is less than 1 or greater than 31, force the day field to 0.
If the year field is less than 2011 or greater than 2017, force the year field to 0.
but when I try to run it, it forces all the fields to 0 even when I put the correct value for the variable :
Please type your invoice number: ...1111
What month is the balance due?(Choose from 1-12)... 1
What day is the balance due?(Choose from 1-31).... 12
What year is the balance due? (Choose from 2011-2017) ....2011
Your invoice number is 0 and your balance due is on 0/0/0.
public class Invoice
{
private int inNum;
private double balDue;
private int m;
private int d;
private int yy;
public Invoice ()
{
super();
setInNum(inNum);
getInNum();
setBalDue(balDue);
setM(m);
setD(d);
setYy(yy);
}
public int getInNum ()
{
return inNum;
}
public void setInNum (int inNum)
{
if (inNum < 1000)
this.inNum = 0;
else
this.inNum = inNum;
}
public double getBalDue ()
{
return balDue;
}
public void setBalDue (double balDue)
{
this.balDue = balDue;
}
public int getM ()
{
return m;
}
public void setM (int m)
{
if (m < 1 || m > 12)
this.m = 0;
else
this.m = m;
}
public int getD ()
{
return d;
}
public void setD (int d)
{
if (d < 1 || d > 31)
this.d = 0;
else
this.d = d;
}
public int getYy ()
{
return yy;
}
public void setYy (int yy)
{
if (yy < 2011 || yy > 2017)
this.m = 0;
else
this.yy = yy;
}
public void displayInfo ()
{
int inNum;
int m, d, yy;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type your invoice number: ");
inNum = keyboard.nextInt();
System.out
.print("What month is the balance due?(Choose from 1-12) ");
m = keyboard.nextInt();
System.out
.print("What day is the balance due?(Choose from 1-31) ");
d = keyboard.nextInt();
System.out
.print("What year is the balance due? (Choose from 2011-2017) ");
yy = keyboard.nextInt();
System.out.println("Your invoice number is " + getInNum()
+ " and your balance due is on " + getM() + "/" + getD()
+ "/" + getYy() + ".");
}
public static void main (String[] args)
{
Invoice invoice = new Invoice();
invoice.displayInfo();
}
}
This is failing because your call to displayInfo is occurring AFTER your call to all the setter methods. It needs to happen first, otherwise the setters don't have anything to do.
I think it's a mistake to call those setter methods in the constructor. You need to call each one once you have the value that needs to be passed to it.
So you might have a local variable for each value that you input, which you'd then pass to the setter
int invoiceNumber = keyboard.nextInt();
setInNumber(invoiceNumber);
and so on for all the other fields.
You made all those pretty setters for the class and didn't use them!
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type your invoice number: ");
setInNum(keyboard.nextInt());
System.out.print("What month is the balance due?(Choose from 1-12) ");
setM(keyboard.nextInt());
System.out.print("What day is the balance due?(Choose from 1-31) ");
setD(keyboard.nextInt());
System.out.print("What year is the balance due? (Choose from 2011-2017) ");
setY(keyboard.nextInt());
System.out.println("Your invoice number is " + getInNum() + " and your balance due is on " + getM() + "/" + getD() + "/" + getYy() + ".");
Related
I already have these 3 codes made but our prof said to revise it again using methods now. Can you help or can you show me what to revise in each code?
1.)
public class HeadsOrTails {
public static void main(String[] args) {
int Heads = 0;
int Tails = 0;
for(long simulation = 1; simulation <= 2000000; simulation += 1)
{
int FlipResult = FlipCoin();
if(FlipResult == 1)
{
Heads += 1;
}
else if(FlipResult == 0)
{
Tails += 1;
}
}
System.out.println("Numer of heads appeared: " + Heads);
System.out.println("Numer of tails appeared: " + Tails);
}
private static int FlipCoin()
{
return (int) (Math.random() + 0.5);
}
}
2.)
import java.util.Scanner;
public class DecToHex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int number = input.nextInt();
int rem;
String result = "";
char
hex[]= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(number > 0)
{
rem = number % 16;
result = hex[rem]+result;
number = number/16;
}
System.out.println("Hexadecimal Number: "+result);
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
/* *****************************************************************************
METHOD NAME : main
DESCRIPTION : Executes the main program to test the class
DayOfTheWeek
********************************************************************************/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
Your professor wants you to avoid typing duplicate code. They want you to minimize the amount of code you have to repeatedly type. For example, look at the main method from your DayOfTheWeek class.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
//After this is more code below that we don't care about for now
}
You had to do 3 System.out.print() calls. You also did 3 input.nextInt() calls. That's 6 calls total.
Notice how there is a System.out.print() call, and then a input.nextInt() call immediately after? We can slim that down to something like this.
public static int fetchInput(Scanner input, String message) {
System.out.print(message);
return input.nextInt();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = fetchInput(input, "Enter Year: (e.g., 2012): ");
int month = fetchInput(input, "Enter Month: 1-12: ");
int day = fetchInput(input, "Enter the Day of the month: 1-31:");
//After this is more code below that we don't care about for now
}
Now, we only have to type fetchInput() 3 times, which has a call to both System.out.print() and input.nextInt(), giving us a total of 5 calls.
So, 5 is less than 6, which means we have made progress towards our goal, but since it is only one less call, it may not seem significant. But in reality, there's a lot more repeats in your code - I just handed you one of them. On top of that, your professor is teaching you good habits that will help you if you ever become a programmer. What if instead of fetching 3 things, you needed to fetch 20? This is common in the real world, by the way. Using your old style, you would have had to type 20 System.out.print() and 20 input.nextInt() calls at least, putting you at around 40 calls. But doing it this new way, you would only need to type 20 fetchInput() calls, which has a System.out.print() call and an input.nextInt() call within it, putting our total at 22 calls for the new method. 40 vs 22 things to type is an easier to see example of how writing code that minimizes retyping the same thing saves you time.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
This is Selection Based Java Program. So in these program user have to provide the Vegetarian as V and Non-Vegetarian as N and it will take integer value for quantity and distance. So, when I saved and run the program it takes the value of the user parameter but didn't print the output I also check the errors in the eclipse editor.
#Program
'''
package demo;
import java.util.Scanner;
public class FoodCorner {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int vegCombo = 12;
int nonvegCombo = 15;
int totalCost = 0;
int charge = 0;
System.out.println("Enter the type of Food Item as Vegeterian 'V' and for Non-Vegeterian as 'N'");
String foodType = scan.nextLine();
System.out.println("Enter the Quantity of food Item");
int quantity = scan.nextInt();
System.out.println("Enter the Distance for delivery");
float distance = scan.nextFloat();
while(distance > 3) {
charge++;
distance = distance - 3;
}
if(distance > 0 && quantity >= 1) {
if(foodType == "V") {
totalCost = (vegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
else if(foodType == "N") {
totalCost = (nonvegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
}
else {
System.out.println("the bill amount is -1");
}
}
}
'''
Use below code snippet. Notice the line if("V".equals(foodType)) instead of if(foodType == "V").
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int vegCombo = 12;
int nonvegCombo = 15;
int totalCost = 0;
int charge = 0;
System.out.println("Enter the type of Food Item as Vegeterian 'V' and for Non-Vegeterian as 'N'");
String foodType = scan.nextLine();
System.out.println("Enter the Quantity of food Item");
int quantity = scan.nextInt();
System.out.println("Enter the Distance for delivery");
float distance = scan.nextFloat();
while(distance > 3) {
charge++;
distance = distance - 3;
}
if(distance > 0 && quantity >= 1) {
if("V".equals(foodType)) {
totalCost = (vegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
else if("N".equals(foodType)) {
totalCost = (nonvegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
}
else {
System.out.println("the bill amount is -1");
}
}
So I've this assignment of coding a Lucky Racer Game in Java, strictly following the constraints of OOP and writing a maintainable / elegant code. There are 5 cars (objects), with random speeds in every round (there are 10 total rounds) and after 10 rounds, I need to find which car (object) covered the most Total Distance i.e which car won the race. Since it's an automatic car, I'm updating gears at each speed entry too - irrelevant info but thought I might explain the context before I show the code.
So here is AutomaticCar.java (Class):
public class AutomaticCar {
private String model;
private int year;
private int speed;
private int gear;
private int odoMeter;
private totalDistance = 0;
private gearAverage = 0;
public AutomaticCar(String model, int year) {
setModel(model);
setYear(year);
}
public void setSpeed(int speed) {
if (speed < 0) {
System.out.println("Invalid speed - please try again.");
} else {
this.speed = speed;
setGear();
}
}
public int getSpeed() {
return speed;
}
public void setModel(String model) {
this.model = model;
}
public String getModel() {
return model;
}
public void setYear(int year) {
this.year = year;
}
public int getYear() {
return year;
}
public void setOdoMeter(int currentRound) {
odoMeter = (currentRound * speed);
setTotalDistance(odoMeter);
}
public int getOdoMeter() {
return odoMeter;
}
public void setTotalDistance(int odoMeter) {
totalDistance += odoMeter;
}
public int getTotalDistance() {
return totalDistance;
}
public void setGear () {
if (speed > 0 && speed <= 100) {
gear = 1;
} else if (speed >= 101 && speed <= 200) {
gear = 2;
} else if (speed >= 201 && speed <= 300) {
gear = 3;
} else if (speed >= 301 && speed <= 400) {
gear = 4;
} else if (speed > 401 && speed <= 500) {
gear = 5;
}
gearAverage += gear;
}
public int getGear () {
return gear;
}
public int gearAverage() {
return (gearAverage/10);
}
public String printDashes(int distance) {
int dashesToPrint = (int)(distance/100);
String storedDashes = "";
for(int i = 0; i < dashesToPrint; i++) {
storedDashes = (storedDashes + "-");
}
return storedDashes;
}
public void declareWinner() {
}
}
Main Class:
import java.util.Scanner;
import java.util.Random;
public class LuckyRacer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
String model;
int year;
int totalRounds = 10;
int currentRound;
System.out.println("Enter Car Model & Year for Car One");
model = input.nextLine();
year = input.nextInt();
input.nextLine();
AutomaticCar car1 = new AutomaticCar(model, year);
car1.setSpeed(rand.nextInt(501));
System.out.println("Enter Car Model & Year for Car Two");
model = input.nextLine();
year = input.nextInt();
input.nextLine();
AutomaticCar car2 = new AutomaticCar(model, year);
car2.setSpeed(rand.nextInt(501));
System.out.println("Enter Car Model & Year for Car Three");
model = input.nextLine();
year = input.nextInt();
input.nextLine();
AutomaticCar car3 = new AutomaticCar(model, year);
car3.setSpeed(rand.nextInt(501));
System.out.println("Enter Car Model & Year for Car Four");
model = input.nextLine();
year = input.nextInt();
input.nextLine();
AutomaticCar car4 = new AutomaticCar(model, year);
car4.setSpeed(rand.nextInt(501));
System.out.println("Enter Car Model & Year for Car Five");
model = input.nextLine();
year = input.nextInt();
AutomaticCar car5 = new AutomaticCar(model, year);
car5.setSpeed(rand.nextInt(501));
for (currentRound = 1; currentRound <= totalRounds; currentRound++) {
car1.setOdoMeter(currentRound);
car2.setOdoMeter(currentRound);
car3.setOdoMeter(currentRound);
car4.setOdoMeter(currentRound);
car5.setOdoMeter(currentRound);
System.out.println("After " + currentRound + " hour/s");
System.out.println("Car 1 " + car1.printDashes(car1.getOdoMeter()) + " :" + car1.getOdoMeter() + " km passed.");
System.out.println("Car 2 " + car2.printDashes(car2.getOdoMeter()) + " :" + car2.getOdoMeter() + " km passed.");
System.out.println("Car 3 " + car3.printDashes(car3.getOdoMeter()) + " :" + car3.getOdoMeter() + " km passed.");
System.out.println("Car 4 " + car4.printDashes(car4.getOdoMeter()) + " :" + car4.getOdoMeter() + " km passed.");
System.out.println("Car 5 " + car5.printDashes(car5.getOdoMeter()) + " :" + car5.getOdoMeter() + " km passed.");
car1.setSpeed(rand.nextInt(501));
car2.setSpeed(rand.nextInt(501));
car3.setSpeed(rand.nextInt(501));
car4.setSpeed(rand.nextInt(501));
car5.setSpeed(rand.nextInt(501));
}
if (car1.getTotalDistance() > car2.getTotalDistance() &&
car1.getTotalDistance() > car2.getTotalDistance() &&
car1.getTotalDistance() > car2.getTotalDistance() &&
car1.getTotalDistance() > car2.getTotalDistance() &&
car1.getTotalDistance() > car2.getTotalDistance() &&
)
input.close();
}
}
So basically, I want to find which Car has the most total distance traveled. I know I can do it in a messy way by comparing Car 1's total distance with the other 4 cars etc etc but I'm hoping to find a more elegant and simpler way to do it, possibly within the boundaries of OOP and it's practices.
I'm hoping I can find a way to make a private method in the AutomaticCar Class that I can just call to declare the winner with it's total distance - but then, I don't know if I can tell which car's total distance is being declared as the most total distance..
So if there is any other way to do it - please comment below, thank you.
I am still having trouble figuring out how the heck the most efficient way to do this is.. Basically, I am trying to make the balance = 0 for every object in the Account array created. I tried using a for loop and set balance = 0for each account created, but I am unsure of how to make this work since the balance variable is created in the class that has all of the methods. I have been trying to this problem all day, but no luck. Thanks.
Main method:
import java.util.Scanner;
import java.text.NumberFormat;
public class Account2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Account[] acct = new Account[30];
for (int count2; count2 < 30; count2++)
{
balance = 0; //Initial balance is always set to zero to be able to run fresh program every time
}
System.out.println("Enter your account number (1-30): ");
int key = scan.nextInt() - 1;
int reset = 0;
while (reset == 0)
{
System.out.println("Enter W for withdrawl; D for deposit; X to escape");
char choice = scan.next().charAt(0);
if (choice == 'W' || choice == 'w' || choice == 'D' || choice == 'd' || choice == 'x' || choice == 'X')
{
if (choice == 'W' || choice == 'w')
{
System.out.println("Enter amount to withdraw: ");
Double withdraw1 = scan.nextDouble();
if (withdraw1 <= acct[key].getBalance())
{
acct[key].withdraw(withdraw1);
System.out.println("User # " + key++ + " funds after withdraw: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Insufficient funds.");
}
if (choice == 'D' || choice == 'd')
{
System.out.println("Enter amount to deposit: ");
Double deposit1 = scan.nextDouble();
if (deposit1 > 0)
{
acct[key].deposit(deposit1);
System.out.println("User # " + key++ + " funds after deposit: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Use the withdrawl feature to withdrawl money.");
}
if (choice == 'x' || choice == 'X')
System.out.println("Thank You for using this bank.");
reset++;
}
else
{
System.out.println("Invalid entry, please try again");
reset = 0;
}
}
}
}
Supporting class:
public class Account
{
private final double RATE = 0.03; //Interest is 3%
private int acctNumber;
private String name;
private balance;
//Defines owner, account number, and initial balance.
public Account(String owner, int account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//deposits a specified amount and returns new balance
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//withdraws the specified amount from the account and applies the fee
// + returns balance
public double withdraw(double amount)
{
int fee = 1;
balance = balance - amount - fee;
return balance;
}
//Adds interest to the account
public double addInterest()
{
balance += (balance * RATE);
return balance;
}
public double getBalance()
{
return balance;
}
//returns a one line description of the account as a string
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "/t" + name + "/t" + fmt.format(balance);
}
}
From an outside class, you can only interact with Account in the way exposed in its visible (e.g. public) API.
In this case, the current way to do this would be to withdraw() the current balance:
acct[i].withdraw(acct[i].getBalance());
Though this specific case would put the balance into the negatives because you charge a fee for a withdrawal (which is hidden from the calling class).
If you were to expose a setBalance method on Account, you could instead do
acct[i].setBalance(0);
However on closer look, it seems like what you are having trouble with is actually initializing the array of accounts. You can do this like this:
for (int count2; count2 < 30; count2++)
{
acct[count2] = new Account(owner, count2, 0);
}
My program has no syntax error, I can input all the value, but I just can't get the final average number right. Can anyone help me find out the problem?
The following is what I input:
How many employees do you have? 4
How many days was Employee #1 absent? 4
How many days was Employee #2 absent? 2
How many days was Employee #3 absent? 1
How many days was Employee #4 absent? 3
Final answer should be: 2.5
This is the code I use:
import java.util.Scanner;
class Number {
public static void main(String[] args) {
int numEmployee = Number.workers();
int absentSum = Number.totaldays(numEmployee);
double averageAbsent = Number.average(numEmployee, absentSum);
}
public static int workers() {
int number = 0;
Scanner input = new Scanner(System.in);
while (number > 0 || number < 0 || number == 0) {
System.out.println("How many employees do you have?");
number = input.nextInt();
if (number >= 0) {
return number;
} else {
System.out
.println("You can not enter a negative number."
+ " Please enter another number.");
}
}
return number;
}
public static int totaldays(int numEmployee) {
int absentDays = 0;
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
return absentSum;
}
public static double average(int numEmployee, int absentSum) {
double averageAbsent = (double) absentSum / (double) numEmployee;
System.out.println("Your employees averaged " + averageAbsent
+ " days absent.");
return averageAbsent;
}
}
Move absentSum += absentDays; into the loop body in totaldays. If you restrict the visibility of absentSum then the compiler will tell you that you are accessing it out of scope. Something like
public static int totaldays(int numEmployee) {
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
int absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
// absentSum += absentDays;
return absentSum;
}
With the above output (and your provided input) I get (the requested)
2.5