SimpleDateFormat showing too much info - java

This is a exercise that computes compatibility between two persons based on https://en.wikipedia.org/wiki/Biorhythm, it works well. However when executing, the program shows the date as for example "Fri Apr 08 00:00:00 EET 2014", but I would like it to show this info without hours, minutes, seconds and time zone. What to do?
import java.util.Scanner;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class bior {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String nameOne;
String nameTwo;
String dobOneIn;
String dobTwoIn;
Date dobOne = new Date();
Date dobTwo = new Date();
boolean validEntry;
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Enter name of first person!");
nameOne = input.nextLine();
while (nameOne.equals("")) {
System.out.println("Enter name of first person!");
nameOne = input.nextLine();
}
System.out.println("Enter name of second person!");
nameTwo = input.nextLine();
while (nameTwo.equals("")) {
System.out.println("Enter name of second person!");
nameTwo = input.nextLine();
}
do {
try {
System.out.println("Enter date of birth of " + nameOne + "! (MM/DD/YYYY)");
dobOneIn = input.nextLine();
dobOne = format.parse(dobOneIn);
validEntry = true;
}
catch (ParseException e) {
validEntry = false;
}
} while (!validEntry);
do {
try {
System.out.println("Enter date of birth of " + nameTwo + "! (MM/DD/YYYY)");
dobTwoIn = input.nextLine();
dobTwo = format.parse(dobTwoIn);
validEntry = true;
}
catch (ParseException e) {
validEntry = false;
}
} while (!validEntry);
int diff = Math.abs((int)((dobOne.getTime() - dobTwo.getTime()) / (24 * 60 * 60 * 1000)));
System.out.println();
System.out.println("Name of second person: " + nameTwo + ".");
System.out.println("DOB of " + nameOne + ": " + dobOne + ".");
System.out.println("DOB of " + nameTwo + ": " + dobTwo + ".");
System.out.println("Difference between DOBs (days): " + diff + ".");
float physicalBio = diff % 23;
float emotionalBio = diff % 28;
float intellectualBio = diff % 33;
physicalBio = physicalBio / 23;
emotionalBio = emotionalBio / 28;
intellectualBio = intellectualBio / 33;
if (physicalBio > 0.5) {
physicalBio = 1 - physicalBio;
}
if (emotionalBio > 0.5) {
emotionalBio = 1 - emotionalBio;
}
if (intellectualBio > 0.5) {
intellectualBio = 1 - intellectualBio;
}
physicalBio = 100 - (physicalBio * 100);
emotionalBio = 100 - (emotionalBio * 100);
intellectualBio = 100 - (intellectualBio * 100);
System.out.println("Physical compatibility: " + java.lang.Math.round(physicalBio) + " %.");
System.out.println("Emotional compatibility: " + java.lang.Math.round(emotionalBio) + " %.");
System.out.println("Intellectual compatibility: " + java.lang.Math.round(intellectualBio) + " %.");
}
}

You declared a SimpleDateFormat but never used it:
Try this:
System.out.println("DOB of " + nameOne + ": " + format.format(dobOne) + ".");

You should make the following modification :
System.out.println("DOB of " + nameOne + ": " + format.format(dobOne) + ".");
System.out.println("DOB of " + nameTwo + ": " + format.format(dobTwo) + ".");
SimpleDateFormat has the format(Date date) method for this purpose.

You can print dobOneIn and dobTwoIn in your println statement which already has format you need:
System.out.println();
System.out.println("Name of second person: " + nameTwo + ".");
System.out.println("DOB of " + nameOne + ": " + dobOneIn + ".");
System.out.println("DOB of " + nameTwo + ": " + dobTwoIn + ".");
System.out.println("Difference between DOBs (days): " + diff + ".");

Related

Format to show percentages with decimal points

I need some tips on how to get my 2nd and 4th percentage in a ".5%" format because in my result I get the result correct but it prints in a whole percentage. So instead of it showing 4%, 4.5%, 5%, 5.5%, and 6% it gives. 4%, 4%, 5%, 6%, 6% but it still calculates the result correctly. Its like it doesn't show the 4.5% and 5.5%. Heres the code, it may seem long but its just repetitive numbers. Note aIR2 and aIR4, those are the targets
import java.util.Scanner;
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class MortgageCalculator {
public static void main(String[] args) {
double aIR, mortgageAmount;
int noY;
double aIR1, aIR2, aIR3, aIR4, aIR5;
double mIR1, mIR2, mIR3, mIR4, mIR5;
double mPayment1, mPayment2, mPayment3, mPayment4, mPayment5;
double totAmount1, totAmount2, totAmount3, totAmount4, totAmount5;
double oPay1, oPay2, oPay3, oPay4, oPay5;
double oPaypercent1, oPaypercent2, oPaypercent3, oPaypercent4, oPaypercent5;
//This establishes formats for values
NumberFormat fmt1 = NumberFormat.getPercentInstance();
NumberFormat fmt2 = NumberFormat.getCurrencyInstance();
DecimalFormat fmt3 = new DecimalFormat("0.##");
//This asks user for inputs
Scanner scan = new Scanner(System.in);
System.out.println("Enter the Annual Interest Rate: ");
aIR= scan.nextDouble();
System.out.println("Enter the Number of Years you will Pay: ");
noY = scan.nextInt();
System.out.println("Enter Amount Borrowed from the Bank: ");
mortgageAmount = scan.nextInt();
//These will give annual interest rates depending on range
aIR1 = (aIR - 1)/100;
aIR2 = (aIR - 0.5)/100;
aIR3 = (aIR)/100;
aIR4 = (aIR + 0.5)/100;
aIR5 = (aIR + 1)/100;
//These give rates by month according to which rate being taken
mIR1 = (aIR1 / 12);
mIR2 = (aIR2 / 12);
mIR3 = (aIR3 / 12);
mIR4 = (aIR4 / 12);
mIR5 = (aIR5 / 12);
//This takes the amounts per month
mPayment1 = (mIR1 * mortgageAmount)/(1-(1/Math.pow((1+mIR1),12*noY)));
mPayment2 = (mIR2 * mortgageAmount)/(1-(1/Math.pow((1+mIR2),12*noY)));
mPayment3 = (mIR3 * mortgageAmount)/(1-(1/Math.pow((1+mIR3),12*noY)));
mPayment4 = (mIR4 * mortgageAmount)/(1-(1/Math.pow((1+mIR4),12*noY)));
mPayment5 = (mIR5 * mortgageAmount)/(1-(1/Math.pow((1+mIR5),12*noY)));
//This takes the total amount per year
totAmount1 = mPayment1 * (noY*12);
totAmount2 = mPayment2 * (noY*12);
totAmount3 = mPayment3 * (noY*12);
totAmount4 = mPayment4 * (noY*12);
totAmount5 = mPayment5 * (noY*12);
//This is the overpayment because of interest
oPay1 = totAmount1 - (mortgageAmount);
oPay2 = totAmount2 - (mortgageAmount);
oPay3 = totAmount3 - (mortgageAmount);
oPay4 = totAmount4 - (mortgageAmount);
oPay5 = totAmount5 - (mortgageAmount);
//This is the overpayment percentage
oPaypercent1 = (oPay1/mortgageAmount);
oPaypercent2 = (oPay2/mortgageAmount);
oPaypercent3 = (oPay3/mortgageAmount);
oPaypercent4 = (oPay4/mortgageAmount);
oPaypercent5 = (oPay5/mortgageAmount);
//Begins printing the results in a line
System.out.println("The Mortgage Amount is: "
+ fmt2.format(mortgageAmount));
System.out.println("The Number of Years the Mortgage is Held: " + noY);
System.out.println("Range of Interest Rates: " + fmt1.format(aIR1)
+ " - " + fmt1.format(aIR5));
System.out.println("Interest Rate Monthly Payment Total Payment"
+ " $ Overpayment % Overpayment");
//Prints first interest rate
System.out.println("" + fmt1.format(aIR1) + " " +
fmt2.format(mPayment1) + " " + fmt2.format(totAmount1)
+ " " + fmt2.format(oPay1) + " "
+ fmt1.format(oPaypercent1) + "");
//Prints second interest rate
System.out.println("" + fmt1.format(aIR2) + " " +
fmt2.format(mPayment2) + " " + fmt2.format(totAmount2)
+ " " + fmt2.format(oPay2) + " "
+ fmt1.format(oPaypercent2) + "");
//Prints third interest rate
System.out.println("" + fmt1.format(aIR3) + " " +
fmt2.format(mPayment3) + " " + fmt2.format(totAmount3)
+ " " + fmt2.format(oPay3) + " "
+ fmt1.format(oPaypercent3) + "");
//Prints fourth interest rate
System.out.println("" + fmt1.format(aIR4) + " " +
fmt2.format(mPayment4) + " " + fmt2.format(totAmount4)
+ " " + fmt2.format(oPay4) + " "
+ fmt1.format(oPaypercent4) + "");
//Prints fifth interest rate
System.out.println("" + fmt1.format(aIR5) + " " +
fmt2.format(mPayment5) + " " + fmt2.format(totAmount5)
+ " " + fmt2.format(oPay5) + " "
+ fmt1.format(oPaypercent5) + "");
}
}
If you want a NumberFormat that displays 4% and 4.5%, i.e. percentage values with a single optional fraction digit, do one of the following:
// Option 1
NumberFormat fmt = NumberFormat.getPercentInstance();
fmt.setMaximumFractionDigits(1);
// Option 2
NumberFormat fmt = new DecimalFormat("0.#%");
Formatting the interest rate should be changed to handle decimal percentage values.
import java.util.Scanner;
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class HelloWorld {
public static void main(String[] args) {
double aIR, mortgageAmount;
int noY;
double aIR1, aIR2, aIR3, aIR4, aIR5;
double mIR1, mIR2, mIR3, mIR4, mIR5;
double mPayment1, mPayment2, mPayment3, mPayment4, mPayment5;
double totAmount1, totAmount2, totAmount3, totAmount4, totAmount5;
double oPay1, oPay2, oPay3, oPay4, oPay5;
double oPaypercent1, oPaypercent2, oPaypercent3, oPaypercent4, oPaypercent5;
//This establishes formats for values
NumberFormat fmt1 = new DecimalFormat("0.#%");
//NumberFormat fmt1 = NumberFormat.getPercentInstance();
NumberFormat fmt2 = NumberFormat.getCurrencyInstance();
DecimalFormat fmt3 = new DecimalFormat("0.##");
//This asks user for inputs
Scanner scan = new Scanner(System.in);
System.out.println("Enter the Annual Interest Rate: ");
aIR= scan.nextDouble();
System.out.println("Enter the Number of Years you will Pay: ");
noY = scan.nextInt();
System.out.println("Enter Amount Borrowed from the Bank: ");
mortgageAmount = scan.nextInt();
//These will give annual interest rates depending on range
aIR1 = (aIR - 1)/100;
aIR2 = (aIR - 0.5)/100;
aIR3 = (aIR)/100;
aIR4 = (aIR + 0.5)/100;
aIR5 = (aIR + 1)/100;
//These give rates by month according to which rate being taken
mIR1 = (aIR1 / 12);
mIR2 = (aIR2 / 12);
mIR3 = (aIR3 / 12);
mIR4 = (aIR4 / 12);
mIR5 = (aIR5 / 12);
//This takes the amounts per month
mPayment1 = (mIR1 * mortgageAmount)/(1-(1/Math.pow((1+mIR1),12*noY)));
mPayment2 = (mIR2 * mortgageAmount)/(1-(1/Math.pow((1+mIR2),12*noY)));
mPayment3 = (mIR3 * mortgageAmount)/(1-(1/Math.pow((1+mIR3),12*noY)));
mPayment4 = (mIR4 * mortgageAmount)/(1-(1/Math.pow((1+mIR4),12*noY)));
mPayment5 = (mIR5 * mortgageAmount)/(1-(1/Math.pow((1+mIR5),12*noY)));
//This takes the total amount per year
totAmount1 = mPayment1 * (noY*12);
totAmount2 = mPayment2 * (noY*12);
totAmount3 = mPayment3 * (noY*12);
totAmount4 = mPayment4 * (noY*12);
totAmount5 = mPayment5 * (noY*12);
//This is the overpayment because of interest
oPay1 = totAmount1 - (mortgageAmount);
oPay2 = totAmount2 - (mortgageAmount);
oPay3 = totAmount3 - (mortgageAmount);
oPay4 = totAmount4 - (mortgageAmount);
oPay5 = totAmount5 - (mortgageAmount);
//This is the overpayment percentage
oPaypercent1 = (oPay1/mortgageAmount);
oPaypercent2 = (oPay2/mortgageAmount);
oPaypercent3 = (oPay3/mortgageAmount);
oPaypercent4 = (oPay4/mortgageAmount);
oPaypercent5 = (oPay5/mortgageAmount);
//Begins printing the results in a line
System.out.println("The Mortgage Amount is: "
+ fmt2.format(mortgageAmount));
System.out.println("The Number of Years the Mortgage is Held: " + noY);
System.out.println("Range of Interest Rates: " + fmt1.format(aIR1)
+ " - " + fmt1.format(aIR5));
System.out.println("Interest Rate Monthly Payment Total Payment"
+ " $ Overpayment % Overpayment");
//Prints first interest rate
System.out.println("" + fmt1.format(aIR1) + " " +
fmt2.format(mPayment1) + " " + fmt2.format(totAmount1)
+ " " + fmt2.format(oPay1) + " "
+ fmt1.format(oPaypercent1) + "");
//Prints second interest rate
System.out.println("" + fmt1.format(aIR2) + " " +
fmt2.format(mPayment2) + " " + fmt2.format(totAmount2)
+ " " + fmt2.format(oPay2) + " "
+ fmt1.format(oPaypercent2) + "");
//Prints third interest rate
System.out.println("" + fmt1.format(aIR3) + " " +
fmt2.format(mPayment3) + " " + fmt2.format(totAmount3)
+ " " + fmt2.format(oPay3) + " "
+ fmt1.format(oPaypercent3) + "");
//Prints fourth interest rate
System.out.println("" + fmt1.format(aIR4) + " " +
fmt2.format(mPayment4) + " " + fmt2.format(totAmount4)
+ " " + fmt2.format(oPay4) + " "
+ fmt1.format(oPaypercent4) + "");
//Prints fifth interest rate
System.out.println("" + fmt1.format(aIR5) + " " +
fmt2.format(mPayment5) + " " + fmt2.format(totAmount5)
+ " " + fmt2.format(oPay5) + " "
+ fmt1.format(oPaypercent5) + "");
}
Output
Interest Rate Monthly Payment Total Payment $ Overpayment % Overpayment
4% $1,841.65 $110,499.13 $10,499.13 10.5%
4.5% $1,864.30 $111,858.12 $11,858.12 11.9%
5% $1,887.12 $113,227.40 $13,227.40 13.2%
5.5% $1,910.12 $114,606.97 $14,606.97 14.6%
6% $1,933.28 $115,996.81 $15,996.81 16%

if else only executing else in java

so i'm struggling with this problem which seems i cannot understand, im completely new in java and i need help.. so i am making a simple program which will determine if you have passed the subject or not via point grades and it seems it only determines the ELSE STATEMENT.. here's the code.. it will really help me out alot.. thanks in advance
String studID=" ",course=" ", name=" ", dept=" ", subj=" ";
double exam1=0, exam2=0, exam3=0, exam4=0;
double avg, pgrade;
String msg=" ";
studID =JOptionPane.showInputDialog("Please fill-out the following fields:"
+ "\nStudent ID: ");
name = JOptionPane.showInputDialog("Name: ");
dept = JOptionPane.showInputDialog("Department: ");
course = JOptionPane.showInputDialog("Course: ");
subj = JOptionPane.showInputDialog("Subject: ");
exam1 = Double.parseDouble(JOptionPane.showInputDialog("First Examination: "));
exam2 = Double.parseDouble(JOptionPane.showInputDialog("Second Examination: "));
exam3 = Double.parseDouble(JOptionPane.showInputDialog("Third Examination: "));
exam4 = Double.parseDouble(JOptionPane.showInputDialog("Final Examination: "));
avg = (exam1 + exam2 + exam3 + exam4)/4;
pgrade =(100 - avg + 10) / 10;
if (avg==100)
{
msg = "passed - Excellent!";
}else if (avg>100 && avg<89)
{
msg = "Passed - Very Good!";
}else if (avg>90 && avg<84)
{
msg = "Passed - Average";
}else if (avg>85 && avg<79)
{
msg = "Passed - Good";
}else if (avg>80 && avg<74)
{
msg = "Passed - Satisfactory";
}else if (avg>75 && avg<49)
{
msg = "Failed";
}else if (avg>50 && avg<0.00)
{
msg = "Dropped";
}else if (avg==0.00 && avg<0.00)
{
msg = "No such Grade";
}else
{
msg = "Out of Range or Invalid.";
}
JOptionPane.showMessageDialog(null, new JTextArea (
"|======Student Details=======|"
+ "\n|StudentID:\t" + studID +"\t |"
+ "\n|Name:\t" + name + "\t |"
+ "\n|Department:\t" +dept+ "\t |"
+ "\n|Course:\t"+course+"\t |"
+ "\n|Subject:\t"+subj + "\t |"
+ "\n|=======Grade Details======= |"
+ "\n|First Second Third Fourth |"
+ "\n|"+exam1+" "+exam2+" "+exam3+" "+exam4+"\t |"
+ "\n|Average:\t" +avg + "\t|"
+ "\n|Point Grade\t:" +pgrade+"\t|"
+ "\n|Remarks:"+msg+"\t|"
+ "\n|=============================|"));
}
}
The condition is wrong because to include a variable in a range you have to set
else if(avg>89 && avg<100)
Your comparisons were wrong to begin with so try something along the lines of what I have corrected, its not the best available, so you can improve it.
String studID=" ",course=" ", name=" ", dept=" ", subj=" ";
double exam1=0, exam2=0, exam3=0, exam4=0;
double avg, pgrade;
String msg=" ";
studID =JOptionPane.showInputDialog("Please fill-out the following fields:"
+ "\nStudent ID: ");
name = JOptionPane.showInputDialog("Name: ");
dept = JOptionPane.showInputDialog("Department: ");
course = JOptionPane.showInputDialog("Course: ");
subj = JOptionPane.showInputDialog("Subject: ");
exam1 = Double.parseDouble(JOptionPane.showInputDialog("First Examination: "));
exam2 = Double.parseDouble(JOptionPane.showInputDialog("Second Examination: "));
exam3 = Double.parseDouble(JOptionPane.showInputDialog("Third Examination: "));
exam4 = Double.parseDouble(JOptionPane.showInputDialog("Final Examination: "));
avg = (exam1 + exam2 + exam3 + exam4)/4;
pgrade =(100 - avg + 10) / 10;
if (avg==100)
{
msg = "passed - Excellent!";
}else if (avg<100 && avg>89)
{
msg = "Passed - Very Good!";
}else if (avg<90 && avg>84)
{
msg = "Passed - Average";
}else if (avg<85 && avg>79)
{
msg = "Passed - Good";
}else if (avg<80 && avg>74)
{
msg = "Passed - Satisfactory";
}else if (avg<75 && avg>49)
{
msg = "Failed";
}else if (avg<50 && avg>0.00)
{
msg = "Dropped";
}else if (avg==0.00)//no one gets below zero in a fair system
{
msg = "No such Grade";
}else
{
msg = "Out of Range or Invalid.";
}
JOptionPane.showMessageDialog(null, new JTextArea (
"|======Student Details=======|"
+ "\n|StudentID:\t" + studID +"\t |"
+ "\n|Name:\t" + name + "\t |"
+ "\n|Department:\t" +dept+ "\t |"
+ "\n|Course:\t"+course+"\t |"
+ "\n|Subject:\t"+subj + "\t |"
+ "\n|=======Grade Details======= |"
+ "\n|First Second Third Fourth |"
+ "\n|"+exam1+" "+exam2+" "+exam3+" "+exam4+"\t |"
+ "\n|Average:\t" +avg + "\t|"
+ "\n|Point Grade\t:" +pgrade+"\t|"
+ "\n|Remarks:"+msg+"\t|"
+ "\n|=============================|"));
}}

java user input assigned to variable can't be an integer to be divided?

So I can't get the variables to be divisible, I need to be able to do this, otherwise I don't know of a way to finish building the lock that I want to build.
It uses 20 inputted numbers, and then arranges them into a Algebra2/calculus system of equations, and then solves for the "s", "a", "f", and "e" it starts by removing "e" from the equation by substituting.
I would greatly appreciate help, I'm open to ideas as well, because sofar I have 25 of these to build, and this is only 1/3 of the first one.
In short, how do I divide variables?
import java.util.Scanner;
public class Lock
{
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
String num_a;
System.out.print("Enter the first number: ");
num_a = user_input.next();
String num_b;
System.out.print("Enter the second number: ");
num_b = user_input.next();
String num_c;
System.out.print("Enter the third number: ");
num_c = user_input.next();
String num_d;
System.out.print("Enter the fourth number: ");
num_d = user_input.next();
String num_e;
System.out.print("Enter the fifth number: ");
num_e = user_input.next();
String num_f;
System.out.print("Enter the sixth number: ");
num_f = user_input.next();
String num_g;
System.out.print("Enter the seventh number: ");
num_g = user_input.next();
String num_h;
System.out.print("Enter the eigth number: ");
num_h = user_input.next();
String num_i;
System.out.print("Enter the ninth number: ");
num_i = user_input.next();
String num_j;
System.out.print("Enter the tenth number: ");
num_j = user_input.next();
String num_k;
System.out.print("Enter the eleventh number: ");
num_k = user_input.next();
String num_l;
System.out.print("Enter the twetlth number: ");
num_l = user_input.next();
String num_m;
System.out.print("Enter the thirteenth number: ");
num_m = user_input.next();
String num_n;
System.out.print("Enter the fourteenth number: ");
num_n = user_input.next();
String num_o;
System.out.print("Enter the fifteenth number: ");
num_o = user_input.next();
String num_p;
System.out.print("Enter the sixteenth number: ");
num_p = user_input.next();
String num_q;
System.out.print("Enter the seventeenth number: ");
num_q = user_input.next();
String num_r;
System.out.print("Enter the eighteenth number: ");
num_r = user_input.next();
String num_s;
System.out.print("Enter the nineteenth number: ");
num_s = user_input.next();
String num_t;
System.out.print("Enter the twentieth number: ");
num_t = user_input.next();
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_d + "e = " + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_i + "e = " + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_n + "e = " + num_o);
System.out.println(num_p + "s + " + num_q + "a + " + num_r + "f + " + num_s + "e = " + num_t);
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_d + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_i + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_n + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_o);
// THIS creates the fourth equation items/order to be substituted into the other first three equations.
int t = num_t;
int s = num_s;
int num_ts = (t / s);
num_ts =
num_ps = (num_p / num_s);
num_qs = (num_q / num_s);
num_rs = (num_r / num_s);
// THIS is the Fourth equation being substituted into the First Equation
num_dts = (num_d * num_ts);
num_dps = (num_d * num_ps);
num_dqs = (num_d * num_qs);
num_drs = (num_d * num_rs);
// THIS is the Fourth equation being substituted into the Second Equation
num_its = (num_i * num_ts);
num_ips = (num_i * num_ps);
num_iqs = (num_i * num_qs);
num_irs = (num_i * num_rs);
// THIS is the fourth equation being substituted into the Third Equation
num_nts = (num_n * num_ts);
num_nps = (num_n * num_ps);
num_nqs = (num_n * num_qs);
num_nrs = (num_n * num_rs);
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_dts + " " + num_dps + "s + " + num_dqs + "a " + num_drs + "f = " + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_its + " " + num_ips + "s + " + num_iqs + "a " + num_irs + "f = " + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_nts + " " + num_nps + "s + " + num_nqs + "a " + num_nrs + "f = " + num_o);
}
}
You can't add, subtract, divide, or multiply String variables. You have to make your variables into ints in order to do that. Also, you can use an array to hold your variables, since there is so many of them.
String, Integer, Float, are not the same types. you can't apply operators like / or * on String for instance. + is special because it has a definition for String, which means concatenate.
Since you need to do some operations on the user inputs, you can read them directly as int:
System.out.print("Enter the first number: ");
int num_a = user_input.nextInt();
System.out.print("Enter the second number: ");
int num_b = user_input.nextInt();
Then you can do
int num_ab = a / b;
Note that if a < b, then num_ab will be 0, since this is an integer. You may want to do something like
float num_ab = (float)a / b;
Now, this code is quite tedious. If you accept to handle indices instead of letters for the variables, you can initialise them in a loop, e.g.
Scanner in = new Scanner(System.in);
int[] numbers = new int[20];
int index = 0;
while (index < numbers.length) {
System.out.println("Enter the "+(index+1)+"th number");
int n = in.nextInt();
numbers[index] = n;
index++;
}
System.out.println(Arrays.toString(numbers));
And use the array of numbers
// arrays start at 0
int num_ab = numbers[0] / numbers[1];
And if you want to be able to access the variables through names, you can define constants
static final int a = 0;
static final int b = 1;
static final int c = 2;
//...
int num_ab = numbers[a] / numbers[b];
But in your case, it may be handy to store initial variables and computed ones in some place where you can retrieve them for further computations:
// the store for all the variables and their value
static Map<String, Integer> vars = new HashMap<>();
// the function to read in the store
static Integer var(String name) {
return vars.get(name);
}
The store is initialised by a loop:
Scanner in = new Scanner(System.in);
// The 20 variables...
String alpha = "abcdefghijklmnopqrst";
for (char c : alpha.toCharArray()) {
String varName = String.valueOf(c);
System.out.println("Enter the value for "+ varName);
int n = in.nextInt();
vars.put(varName, n);
}
System.out.println(vars.toString());
int num_ab = var("a")/var("b");
// Store ab for further computation
vars.put("ab", num_ab);
System.out.println("ab is " + var("ab");

How can I format this to print the month name instead of number?

This is a piece of the code I have so far... I need it to print out June 8, 2008 instead of 6/8/2014. How can I do this? If you need to see more of the other code, just ask.
public void weatherRecord(int month, int date) {
for (int loc = 0; loc < weatherRecord.length; loc++) {
System.out.print("Location: " + weatherRecord[loc][month][date].getLocation() + "\t\t");
System.out.print("Date: " + weatherRecord[loc][month][date+1].getDateToString() + "\n");
System.out.print("High Temp: " + weatherRecord[loc][month][date].getHighTemp() + "\t\t\t");
System.out.print("Low Temp: " + weatherRecord[loc][month][date].getLowTemp() + "\n");
System.out.print("Avg Wind: " + weatherRecord[loc][month][date].getAvgWind() + "\t\t\t");
System.out.print("Max Wind: " + weatherRecord[loc][month][date].getMaxWind() + "\n");
System.out.print("Precipitation: " + weatherRecord[loc][month][date].getPrecip() + " inches.\n\n");
}
}
Edit: I see other posts that talk about DateFormatSymbols, but how would I implement it?
Edit Edit: Here's the code that someone asked for...
public String getDateToString() {
return "" + this.date.get(Calendar.MONTH) + "/"
+ this.date.get(Calendar.DAY_OF_MONTH) + "/"
+ this.date.get(Calendar.YEAR) + " ";
}
You could use a SimpleDateFormat and something like
private static final DateFormat SDF = new SimpleDateFormat("MMMM d, yyyy");
public String getDateToString() {
return SDF.format(date.getTime());
}
The four M characters become the full-name of the month. The single d is the day of the month and yyyy is a four digit year.
import java.text.DateFormatSymbols;
public String getDateToString() {
return "" + monthNumToName(this.date.get(Calendar.MONTH)) + " "
+ this.date.get(Calendar.DAY_OF_MONTH) + ", "
+ this.date.get(Calendar.YEAR) + " ";
}
private String monthNumToName(int month) {
return new DateFormatSymbols().getMonths()[month-1];
}

What is wrong with my loop

I'm a beginner Java student trying to make this code list the amount saved and interest for 8 years. I'm trying to use a for loop for it. It calculates the interest but only lists it for 1 year. Would appreciate any help solving this problem.
import javax.swing.JOptionPane;
import java.text.*;
public class RetirementGoal3
{
private static DecimalFormat percentFormat = new DecimalFormat("###.##%");
private static DecimalFormat moneyFormat = new DecimalFormat("$###,###,###.00");
private static double interest;
private static double saveAmount;
private static double total;
private static int Max_Year = 8;
private static int year;
private static double totalSave;
private static double totalInterest;
public static void main(String[] args)
{
calculateR();
}
public static double calculateR()
{
String result = JOptionPane.showInputDialog(null, "Enter how much money you can save annually.");
if(result != null)
saveAmount = Double.parseDouble(result);
String result1 = JOptionPane.showInputDialog(null, "Enter your interest rate(As a decimal)");
if(result1 != null)
interest = Double.parseDouble(result1);
totalSave = saveAmount;
for(year = 1; year <= Max_Year; ++ year)
{
totalInterest = saveAmount + saveAmount * interest;
JOptionPane.showMessageDialog(null, " If you save " + moneyFormat.format(totalSave) + " each year for " + Max_Year + " years" + "\n With " + percentFormat.format(interest) + " Interest" + " Without Interest" + "\n\nAfter year " + year + " " + moneyFormat.format(totalSave) + " " + moneyFormat.format(totalInterest));
return total;
}
return total;
}
}
You have a return statement inside your for loop. So, the first iteration returns, exiting the for loop right away.
You have a return statement already in the correct location, after the for loop, so all you have to do is remove the return statement that is inside the for loop.
Change you loop to :
for(year = 1; year <= Max_Year; ++ year)
{
totalInterest = saveAmount + saveAmount * interest;
JOptionPane.showMessageDialog(null, " If you save " + moneyFormat.format(totalSave) + " each year for " + Max_Year + " years" + "\n With " + percentFormat.format(interest) + " Interest" + " Without Interest" + "\n\nAfter year " + year + " " + moneyFormat.format(totalSave) + " " + moneyFormat.format(totalInterest));
}
Remove the return. As soon as you do a return it stops execution of that function and return to the callers.
for(year = 1; year <= Max_Year; ++ year)
{
totalInterest = saveAmount + saveAmount * interest;
JOptionPane.showMessageDialog(null, " If you save " + moneyFormat.format(totalSave) + " each year for " + Max_Year + " years" + "\n With " + percentFormat.format(interest) + " Interest" + " Without Interest" + "\n\nAfter year " + year + " " + moneyFormat.format(totalSave) + " " + moneyFormat.format(totalInterest));
return total; //<-- PROBLEM
}
The problem is the return inside the loop. It executes one iteration and when it gets to the return statement it exits the loop. I guess you want to move it outside the loop.
Update after your comment: Try this
String resultString = "";
for(year = 1; year <= Max_Year; year++)
{
totalInterest = saveAmount + saveAmount * interest;
resultString += " If you save " + moneyFormat.format(totalSave) +
" each year for " + Max_Year + " years" + "\n" +
" With " + percentFormat.format(interest) + " Interest" +
" Without Interest" + "\n\nAfter year " + year + " " +
moneyFormat.format(totalSave) +
" " + moneyFormat.format(totalInterest) + "\n";
}
JOptionPane.showMessageDialog(null, resultString);
return total;
}
Note that this will display things the way you want to but i think your calculations go wrong somewhere.

Categories