I'm writing one of my first java codes and I can't get it to run. When I run the code it tells me there are errors but in the console at the bottom nothing appears for me to see what the error might be. Please help?
package operators;
import java.util.Scanner;
public class assignment2ifelse {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int quantity;
int packages = 99;
quantity = input.nextInt();
double dis1 = .2; // dis2 = .33, dis3 = .42, dis4 = .29;
double price = packages * quantity;
double discount = 0;
double finalprice = price * discount;
if (quantity < 20 && quantity > 9) {
System.out.println(price);
discount = price * dis1;
System.out.println(discount);
System.out.println(finalprice);
}
}
}
Try this code :
package operators;
import java.util.Scanner;
public class assignment2ifelse {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int quantity;
int packages = 99;
System.out.println("Enter a quantity : ");
quantity = input.nextInt();
double dis1 = .2; // dis2 = .33, dis3 = .42, dis4 = .29;
double price = packages * quantity;
double discount = 0;
double finalprice = price * discount;
if (quantity < 20 && quantity > 9) {
System.out.println(price);
discount = price * dis1;
System.out.println(discount);
System.out.println(finalprice);
} else {
System.out.println("Quantity doesn't match expectations.");
}
}
}
Actually, the program runs but it doesn't show you anything because it begins immediately by waiting for an input from the user:
quantity = input.nextInt();
Then, it shows you something only if your entry matches the condition of your if test.
Next time, try to create an interaction with the user by prompting them with messages using System.out.print().
Related
Im trying to insert the total_cost variable into the string in the last few lines without doing the ("its" + total_cost) method. Im trying to replicate the python {total_variable} method in java basically
import java.util.Scanner;
public class Decision2 {
public static void main(String[] arrgs) {
Scanner input = new Scanner(System.in);
int ticket = 0;
double total_cost = 0;
System.out.println("How many tickets do you want to buy?");
ticket = input.nextInt();
if (ticket >= 5) {
total_cost = total_cost + (10.95 * ticket);
} else {
total_cost = total_cost + (8.95 * ticket);
}
System.out.printf("The total cost is {total_cost}");
}
}
You can use java String Format
such as
String foo = String.format("The total cost is %.2f",total_cost);
or if printing use such as
System.out.printf("The total cost is %.2f\n",total_cost);
When I run the program and and put in a couple mortgages and then end the program it prints out the entire array of objects, mortgageArray[], but for some reason it is only printing out the last mortgage you entered. Not sure why can anybody help me out? I think the problem may lie when instantiating the objects into the array.
Mortgage Class
import java.util.*;
import java.lang.Math.*;
import java.text.DecimalFormat;
public class Mortgage {
private static int loanAmount;
private static int term;
private static double interestRate;
private static String accountNum;
private static String lastName;
private static double monthlyPayment;
private static double totalPayment;
public Mortgage(int loanAmount1, int term1, double interestRate1, String accountNum1){
loanAmount = loanAmount1;
term = term1;
interestRate = interestRate1;
accountNum = accountNum1;
}
public void promotional(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
lastName = getLastName();
accountNum = getAccountNum();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public void unique(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
m.storeLoanAmount();
m.storeInterestRate();
m.storeTerm();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public Mortgage(){
//dummy constructor
}
public static int getLoanAmount(){
return loanAmount;
}
public void storeLoanAmount(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount of the loan (Ex:75000): ");
int loanAmount1 = s.nextInt();
while(loanAmount1 < 75000 || loanAmount1 > 1000000){
System.out.println("\tValid Loan Amounts are $75000-$1000000");
System.out.println("\tPlease re-enter loan amount without $ or commas (Ex:75000): ");
loanAmount1 = s.nextInt();
}
loanAmount = loanAmount1;
}
public static int getTerm(){
return term;
}
public void storeTerm(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number of years for the loan: ");
int term1 = s.nextInt();
while(term1 < 10 || term1 > 40){
System.out.println("\tValid Loan Terms are 10-40");
System.out.println("\tPlease re-enter valid number of years: ");
term1 = s.nextInt();
}
term = term1;
}
public static double getInterestRate(){
return interestRate;
}
public void storeInterestRate(){
Scanner s = new Scanner(System.in);
System.out.println("Enter yearly interest rate (Ex: 8.25): ");
double interestRate1 = s.nextDouble();
while(interestRate1 < 2 || interestRate1 > 7){
System.out.println("\tValid Interest Rates are 2% - 7%");
System.out.println("\tPlease re-enter valid yearly interest rate (Ex: 8.25): ");
interestRate1 = s.nextDouble();
}
interestRate = interestRate1;
}
public String getLastName(){
return lastName;
}
public void storeLastName(){
Scanner s = new Scanner(System.in);
System.out.println("Enter customer's Last Name Only: ");
String lastName1 = s.nextLine();
lastName = lastName1;
}
private double calcMonthlyPayment(){
int months = term * 12;
double monthlyInterest = (interestRate / 12 / 100);
double monthlyPay = (loanAmount * monthlyInterest) / (1 - Math.pow(1+ monthlyInterest, -1 * months));
return monthlyPay;
}
private double calcTotalPayment(){
double totalPay = calcMonthlyPayment() * term * 12;
return totalPay;
}
public String getAccountNum(){
return accountNum;
}
public void storeAccountNum(){
StringBuilder accountNum1 = new StringBuilder();
Random rand = new Random();
int accNum = rand.nextInt(9900);
accNum += 100;
accountNum1.append(lastName.substring(0,4));
accountNum1.append(accNum);
accountNum = accountNum1.toString();
}
public String toString(){
DecimalFormat df = new DecimalFormat("#,###.00");
String strMonthlyPayment = ("$" + df.format(calcMonthlyPayment()));
String strTotalPayment = ("$" + df.format(calcTotalPayment()));
return("Account Number: " + accountNum + "\nThe monthly payment is " + strMonthlyPayment + "\nThe total payment is " + strTotalPayment);
}
}
MortgageApp Class
import java.util.*;
public class MortgageApp {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Mortgage m = new Mortgage();
int size = 10;
Mortgage [] mortgageArray = new Mortgage [size];
int index = 0;
for(index = 0; index < size; index++){
int choice;
System.out.println("\nPlease choose from the following choices below:");
System.out.println("\t1) Promotional Load (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("\n\t Please enter your selection (1-3): ");
choice = s.nextInt();
while(choice < 1 || choice > 3){
System.out.println("\t\tInvalid Choice. Please select 1, 2, or 3: ");
choice = s.nextInt();
}
if(choice == 1){
m.promotional();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(250000, 20, 3.2, accountNum1);
System.out.println("PROMOTIONAL LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 2){
m.unique();
int loanAmount = m.getLoanAmount();
int term = m.getTerm();
double interestRate = m.getInterestRate();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(loanAmount, term, interestRate, accountNum1);
System.out.println("UNIQUE LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 3){
System.out.println("\nPROGRAM COMPLETE");
System.out.println("Contents of Array...");
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[j].toString() + "\n");
}
}
index = 10;
}
}
}
}
The problem is with your loop at the end
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[1].toString() + "\n");
}
}
It always prints the element at index 1.
Should be
System.out.println(mortgageArray[j].toString() + "\n");
All your fields in the class Mortgage are static.
To fix this, simply remove the static keyword:
private int loanAmount;
private int term;
private double interestRate;
private String accountNum;
private String lastName;
private double monthlyPayment;
private double totalPayment;
Static fields don't belong to an instance, but to the class that gets instantiated. So everytime you call one of your getter-methods, the previous value (of all your instances) will be overriden.
If you are not familiar with classes and objects in Java, this tutorial might be helpfull for you: Understanding Class Members
I keep getting error "Error: Could not find or load main class GradesAverage" after trying to compile it.
Can anyone help me understand where it went wrong in this code?
package javaexercises.arrays;
import java.util.Scanner;
public class GradesAverage {
private final int LOWEST_GRADE = 0;
private final int HIGHEST_GRADE = 100;
// student's grades
private int[] grades;
private Scanner in;
/**
* Enter program's point.
*
* #param args
*/
public static void main(String[] args)
{
GradesAverage aGradesAverage = new GradesAverage();
aGradesAverage.in = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numStudents = aGradesAverage.in.nextInt();
aGradesAverage.run(numStudents);
}
/**
* Run program.
*
* #param numStudents
*/
private void run(int numStudents)
{
if (numStudents <= 0) {
System.out.println("Invalid number of students.");
return;
}
grades = new int[numStudents];
double sum = 0;
int i = 0;
while (i < numStudents)
{
System.out.printf("Enter the grade for student %1$d: ", (i+1));
int grade = in.nextInt();
// chek if grade is between 0 and 100
if ((grade >= LOWEST_GRADE) && (grade <= HIGHEST_GRADE)) {
grades[i] = grade;
sum += grade;
i++;
continue;
}
System.out.println("Invalid grade, try again...");
}
System.out.printf("The average is %1$.2f\n", (sum / numStudents));
}
}
Some online compilers don't handle packaging well.
Comment out this line
package javaexercises.arrays;
It should work.
So basically, my program compiles correctly and is working. However, when the program calculates the simple interest, it displays the incorrect value. Say it should be displaying $470, instead it is only printing out 4.7, sorry for the bad explanation, could anyone figure out why this is happening?
import java.io.*;
import java.util.Scanner;
import java.io.File;
//import java.nio.file.*;
//import java.nio.file.Paths;
public class BankInterest {
public static void main (String [] args) throws IOException
{
/* TASK 1: Declare variables */
Scanner user_input = new Scanner (System.in);
boolean exit;
int accountType;
double balance;
double principal;
// double userInterest;
double r;
double r2;
int year;
String commBank = ("commbank.txt");
String westPac = ("westpac.txt");
/*Check if the expected command line is provided */
if (args.length < 1) {
/* Display the Usage */
System.out.println("Usage: java BankInterest interestRateFileName");
/* Programs quits with an error code */
System.exit(-1);
}
/* TASK 2: Read interest rates from a file */
String filename = (args[0]);
Scanner textReader = new Scanner(new File(filename));
r = textReader.nextDouble();
r2 = textReader.nextDouble();
System.out.println(r);
System.out.println(r2);
/* TASK 3: Take user input - Which Account */
Scanner keyboard = new Scanner (System.in);
System.out.println("Which Account: ");
System.out.println("1 - Savings");
System.out.println("2 - Term Deposits");
accountType = keyboard.nextInt();
if (accountType == 1) {
accountType = 1;
}
else if (accountType == 2) {
accountType = 2;
}
/* TASK 4: Take user input - Principal and Period */
Scanner input = new Scanner (System.in);
System.out.println("Principal: ");
principal = keyboard.nextDouble();
System.out.println("Years: ");
year = keyboard.nextInt();
/* TASK 5: Calculate balance for the chosen account type */
if (accountType == 1) {
double userBalance = principal * Math.pow((1 + r/100), year);
double userInterest = userBalance-principal;
System.out.println("");
System.out.println("The Compound Interest is: " + userBalance);
System.out.println("The total amount of Interest earned:" + userInterest);
}
else if (accountType == 2) {
double userBalance = (principal * r2 * year) / 100;
double userInterest = userBalance-principal;
System.out.println("");
System.out.println("The Simple Interest is: " + userBalance);
System.out.println("The total amount of Interest earned:" + userInterest);
}
}
}
I guess it's just because you are giving the interest rate as percent. I mean for 20% interest rate the value in your file is 0.20. And in your calculation you divide it by 100 again. Either change your interest value to 20 or get rid of the division by 100 section in your calculation.
Firstly formula is wrong. The right one is (assuming that r2 represents %):
double userInterest = (principal * r2 * year) / 100;
double userBalance = principal + userInterest;
This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 7 years ago.
Is there anyone who could guide me in the right direction on how to create an array of these employees? The array is set to a constant SIZE=10; Here is the my employee class and the driver with the array I tried. Also, I am aware that most of the output will be blank (employee name, id, etc) As I already know how to write it but so far have not. Also the "1" in class name "Employee 1" is only there because I already had another file saved under employee. Very new to java as you can most likely tell. Thank you
class Employee1{
//variables
private String name;
private double grossPay;
// This is the constructor of the class Employee
public Employee1(String EmpName)
{
name = EmpName;
}
//calculates gross pay and returns
public double weeklyPay(double hoursWorked, double hourlyRate)
{
double timeAndHalf = (hourlyRate/2.0)+hourlyRate;
double dblOvtHours;
double dblOvtPay;
double regHours;
double ovtHours;
if (hoursWorked <= 40)
{
grossPay = hoursWorked*hourlyRate;
}
else if (hoursWorked > 40 && hoursWorked <= 60)
{
ovtHours = hoursWorked-40;
regHours = 40;
grossPay = (ovtHours*timeAndHalf) + (regHours*hourlyRate);
}
else if (hoursWorked > 60)
{
ovtHours = 20;
regHours = 40;
dblOvtHours = hoursWorked - 60;
dblOvtPay = hourlyRate * 2;
grossPay = (dblOvtPay*dblOvtHours) + (timeAndHalf * ovtHours)
+(regHours * hourlyRate);
}
return grossPay;
}/////////////////////////////////////////////////
/* Print the Employee details */
public String toString()
{
return "Employee Report\n" + "Name :" + "\nID number :"
+ "\nHours Worked" + "\nHourly Rate : " +"\nGross pay: " + grossPay ;
}
}
my driver class:
import java.util.Scanner;
public class EmployeeDriver{
public static void main(String args[]){
// Invoking methods for each object created
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
//array that does not work //
Employee1 emp = new Employee1();
emp[0] = new Employee ();
/* invoke weeklyPay() method */
grossPayf= emp.weeklyPay(hoursWorkedf,hourlyRatef);
// invoke printEmployee() method
System.out.println (emp.toString());
}
}
What you are doing is creating a single object, not an array. An array would look like this:
final int SIZE = 10;
Employee1[] emp = new Employee1[SIZE];
Then each member of the array would have to be instantiated like this:
emp[0] = new Employee1();
public static final int SIZE = 10;
public static void main(String[] args) {
Employee1[] employees = new Employee1[SIZE];
}
As per Java doc:
An array is a container object that holds a fixed number of values of a single type.
In your case you are instantiating an object (Employee1 emp) and setting it at index 0. What about other indexes? You nee to run a loop and ask user for new employee and insert it at proper index ( 0-> 1 ->2 and so on).
Also your constructor accepts name of employee which you should also provide and print it in toString method. I have made some changes and the final code looks like:
public class Employee1 {
//variables
private String name;
private double grossPay;
// This is the constructor of the class Employee
public Employee1(String EmpName)
{
name = EmpName;
}
//calculates gross pay and returns
public double weeklyPay(double hoursWorked, double hourlyRate)
{
double timeAndHalf = (hourlyRate/2.0)+hourlyRate;
double dblOvtHours;
double dblOvtPay;
double regHours;
double ovtHours;
if (hoursWorked <= 40)
{
grossPay = hoursWorked*hourlyRate;
}
else if (hoursWorked > 40 && hoursWorked <= 60)
{
ovtHours = hoursWorked-40;
regHours = 40;
grossPay = (ovtHours*timeAndHalf) + (regHours*hourlyRate);
}
else if (hoursWorked > 60)
{
ovtHours = 20;
regHours = 40;
dblOvtHours = hoursWorked - 60;
dblOvtPay = hourlyRate * 2;
grossPay = (dblOvtPay*dblOvtHours) + (timeAndHalf * ovtHours)
+(regHours * hourlyRate);
}
return grossPay;
}/////////////////////////////////////////////////
/* Print the Employee details */
public String toString()
{
return "Employee Report\n" + "Name :" + name + "\nID number :"
+ "\nHours Worked" + "\nHourly Rate : " +"\nGross pay: " + grossPay ;
}
}
And the main is:
public static void main(String[] args) {
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("How many employees you want to enter: ");
final int empSize = input.nextInt();
Employee1[] employees = new Employee1[empSize];
for (int i = 0; i <empSize; i++) {
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
employees[0] = new Employee1("John");
grossPayf = employees[0].weeklyPay(hoursWorkedf,hourlyRatef);
System.out.println (employees[0].toString());
}
}
Note: I have done only minimum changes to make the program work. There are various other things you can improve in your code. The program runs as:
How many employees you want to enter:
2
Please enter the number of hours work: 11
Employee Report
Name :John
ID number :
Hours Worked
Hourly Rate :
Gross pay: 112.75
Please enter the number of hours work: 10
Employee Report
Name :John
ID number :
Hours Worked
Hourly Rate :
Gross pay: 102.5
new code
public static void main(String[] args) {
final int SIZE=10;
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
String name = "Void";
Scanner input = new Scanner(System.in);
// System.out.println("How many employees you want to enter: ");
// final int empSize = input.nextInt();
Employee1[] employees = new Employee1[SIZE];
for (int i = 0; i <SIZE; i++)
{
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
System.out.print("Please enter employee name: ");
employees[i] = new Employee1(name);
grossPayf = employees[i].weeklyPay(hoursWorkedf,hourlyRatef);
System.out.println (employees[i].toString());