What is wrong with my loop - java

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.

Related

random walk across 10x10 grid array

The purpose of this program is to build a 10x10 array grid made out of periods (.), allow the user to designate a starting point, and then the program will randomly choose numbers which are assigned to directions for the 'walker' to go. Each time it moves it marks its spot with the next letter in the alphabet (the starting point is marked by A). I haven't done this part yet but I know how I will; if the walker crosses out of the bounds of the array (AKA > 10 or < 0) it will say "you were arrested" and if the variable alpha == 'Z' it way say "You made it home".
The main problem as far as I can tell is with the method processing(), where I draw numbers from getRand (which I have confirmed is working) and then assign them directions which are given to the array. But for some reason when it prints the grid it only shows the starting point, and not the movement of the walker.
Another question I have of lesser importance is if there is a more brief way to display my grid than how I have been (A massive brick of text in a System.out.print)
package walktester;
import java.lang.Math;
import java.util.Random;
import java.util.Scanner;
class DrunkWalker {
private char[][] walkgrid = new char[10][10];
private static int randNSEW;
private int randomnum;
private int startrow;
private int startcol;
private char alpha = 'A';
private int nextrow;
private int nextcol;
public DrunkWalker(int r, int c) {
startrow = r;
startcol = c;
nextrow = startrow;
nextcol = startcol;
for (int i = 0; i < 10; i ++) {
for (int j = 0; j < 10; j++)
walkgrid[i][j] = '.';
}
walkgrid[r][c] = alpha;
}
public static void getRand(){
int x100 = 0;
double randomNum = 0.0;
randomNum = Math.random();
x100 = (int) (randomNum * 100);
randNSEW = x100 % 4;
}
public int getNextRow(){
return nextrow;
}
public int getNextCol(){
return nextcol;
}
public void processing(){
for(int i = 0; i < 26; i ++){
getRand();
if(randNSEW == 0){
nextcol--;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 1){
nextrow++;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 2){
nextcol++;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 3){
nextrow--;
walkgrid[nextrow][nextcol] = alpha++;
}
}
}
public char[][] DisplayGrid() {
System.out.print(
walkgrid[0][0] + " " + walkgrid[0][1] + " " + walkgrid[0][2] + " " + walkgrid[0][3] + " " + walkgrid[0][4] + " " + walkgrid[0][5] + " " + walkgrid[0][6] + " " + walkgrid[0][7] + " " + walkgrid[0][8] + " " + walkgrid[0][9] + "\n" +
walkgrid[1][0] + " " + walkgrid[1][1] + " " + walkgrid[1][2] + " " + walkgrid[1][3] + " " + walkgrid[1][4] + " " + walkgrid[1][5] + " " + walkgrid[1][6] + " " + walkgrid[1][7] + " " + walkgrid[1][8] + " " + walkgrid[1][9] + "\n" +
walkgrid[2][0] + " " + walkgrid[2][1] + " " + walkgrid[2][2] + " " + walkgrid[2][3] + " " + walkgrid[2][4] + " " + walkgrid[2][5] + " " + walkgrid[2][6] + " " + walkgrid[2][7] + " " + walkgrid[2][8] + " " + walkgrid[2][9] + "\n" +
walkgrid[3][0] + " " + walkgrid[3][1] + " " + walkgrid[3][2] + " " + walkgrid[3][3] + " " + walkgrid[3][4] + " " + walkgrid[3][5] + " " + walkgrid[3][6] + " " + walkgrid[3][7] + " " + walkgrid[3][8] + " " + walkgrid[3][9] + "\n" +
walkgrid[4][0] + " " + walkgrid[4][1] + " " + walkgrid[4][2] + " " + walkgrid[4][3] + " " + walkgrid[4][4] + " " + walkgrid[4][5] + " " + walkgrid[4][6] + " " + walkgrid[4][7] + " " + walkgrid[4][8] + " " + walkgrid[4][9] + "\n" +
walkgrid[5][0] + " " + walkgrid[5][1] + " " + walkgrid[5][2] + " " + walkgrid[5][3] + " " + walkgrid[5][4] + " " + walkgrid[5][5] + " " + walkgrid[5][6] + " " + walkgrid[5][7] + " " + walkgrid[5][8] + " " + walkgrid[5][9] + "\n" +
walkgrid[6][0] + " " + walkgrid[6][1] + " " + walkgrid[6][2] + " " + walkgrid[6][3] + " " + walkgrid[6][4] + " " + walkgrid[6][5] + " " + walkgrid[6][6] + " " + walkgrid[6][7] + " " + walkgrid[6][8] + " " + walkgrid[6][9] + "\n" +
walkgrid[7][0] + " " + walkgrid[7][1] + " " + walkgrid[7][2] + " " + walkgrid[7][3] + " " + walkgrid[7][4] + " " + walkgrid[7][5] + " " + walkgrid[7][6] + " " + walkgrid[7][7] + " " + walkgrid[7][8] + " " + walkgrid[7][9] + "\n" +
walkgrid[8][0] + " " + walkgrid[8][1] + " " + walkgrid[8][2] + " " + walkgrid[8][3] + " " + walkgrid[8][4] + " " + walkgrid[8][5] + " " + walkgrid[8][6] + " " + walkgrid[8][7] + " " + walkgrid[8][8] + " " + walkgrid[8][9] + "\n" +
walkgrid[9][0] + " " + walkgrid[9][1] + " " + walkgrid[9][2] + " " + walkgrid[9][3] + " " + walkgrid[9][4] + " " + walkgrid[9][5] + " " + walkgrid[9][6] + " " + walkgrid[9][7] + " " + walkgrid[9][8] + " " + walkgrid[9][9] + "\n"
);
return walkgrid;
}
}
public class WalkTester {
public static void main(String[] args) {
Scanner inpr = new Scanner(System.in);
Scanner inpc = new Scanner(System.in);
Scanner inpchoice = new Scanner(System.in);
int r = 0;
int c = 0;
char choice = 'y';
while(choice == 'y' || choice == 'Y') {
System.out.println("Please enter x coordinate between 1 and 10.");
r = inpr.nextInt();
r = r - 1;
System.out.println("Please enter y coordinate between 1 and 10");
c = inpr.nextInt();
c = c - 1;
if(r < 0 || r > 9 || c < 0 || c > 9){
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
DrunkWalker drunkwalker = new DrunkWalker(r, c);
drunkwalker.DisplayGrid();
System.out.println("Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
}
}
The code that moves the walker is in a method called processing(), but you never call it.
You can make your DisplayGrid() method simpler (and it will still print the same stuff):
public char[][] DisplayGrid() {
for(int y = 0; y < 10; y++) {
for(int x = 0; x < 10; x++) {
System.out.print(walkgrid[x][y] + " ");
}
System.out.println();
}
return walkgrid;
}
Your processing() method needs to check if the walker leaves the bounds of the area. If you don't, you'll get an ArrayIndexOutOfBoundsException.
public boolean processing(){
for(int i = 0; i < 26; i ++){
getRand();
if(randNSEW == 0){
nextcol--;
}
if(randNSEW == 1){
nextrow++;
}
if(randNSEW == 2){
nextcol++;
}
if(randNSEW == 3){
nextrow--;
}
if(nextrow < 0 || nextrow >= 10 || nextcol < 0 || nextcol >= 10) {
return false;
}
walkgrid[nextrow][nextcol] = alpha++;
}
return true;
}
Now you need to call processing() and check the return value to see if the walker succeeded:
DrunkWalker drunkwalker = new DrunkWalker(r, c);
boolean walkerSucceeded = drunkwalker.processing();
drunkwalker.DisplayGrid();
if(walkerSucceeded) {
System.out.println("You made it home");
} else {
System.out.println("You were arrested");
}
And keep in mind (as you will see when you test this), that the walker can cross their own tracks (so you might see some letters missing).

Convert numbers in an array to another array

I'm trying to create another array but I want it to be the array double gainT[], which is the temperature in Fahrenheit, converted to Celcius to make another array called double gainTC[]. I am also trying to do the same thing but with the precipitation. I just can't seem to find a way to do it though.
import java.io.IOException;
import java.util.Scanner;
public class AnnualClimate1 {
public static void main(String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Choose the temperature Scale (F = Fahrenheit, C = Celsius): ");
String tFC = in.nextLine();
System.out.print("Choose the precipitation Scale (I = Inches, C = Centimeters): ");
String pIC = in.nextLine();
System.out.println("");
System.out.println("");
System.out.println(" Climate Data");
System.out.println(" Location: Gainesville, Florida");
System.out.println(" Temperature " + tFC + " Precipitation " + pIC);
System.out.println("=================================================");
double gainT[]={54.3, 57.0, 62.5, 67.6, 74.3, 79.2, 80.9, 80.4, 77.8, 70.1, 62.8, 56.3};
double gainTC[] = {(gainT[] - 32) / 1.8};
double gainP[]={3.5, 3.4, 4.3, 2.9, 3.2, 6.8, 6.1, 6.6, 4.4, 2.5, 2.2, 2.6};
double gainPC[] = {gainP[] / .3937};
if(tFC.equalsIgnoreCase("F") && pIC.equalsIgnoreCase("I")){
System.out.println("Jan. " + gainT[1] + " " + gainP[1]);
System.out.println("Feb. " + gainT[2] + " " + gainP[2]);
System.out.println("Mar. " + gainT[3] + " " + gainP[3]);
System.out.println("Apr. " + gainT[4] + " " + gainP[4]);
System.out.println("May " + gainT[5] + " " + gainP[5]);
System.out.println("Jun. " + gainT[6] + " " + gainP[6]);
System.out.println("Jul. " + gainT[7] + " " + gainP[7]);
System.out.println("Aug. " + gainT[8] + " " + gainP[8]);
System.out.println("Sep. " + gainT[9] + " " + gainP[9]);
System.out.println("Oct. " + gainT[10] + " " + gainP[10]);
System.out.println("Nov. " + gainT[11] + " " + gainP[11]);
System.out.println("Dec. " + gainT[12] + " " + gainP[12]);
}
else if(tFC.equalsIgnoreCase("C") && pIC.equalsIgnoreCase("C")){
System.out.println("Jan. " + gainTC[1] + " " + gainPC[1]);
System.out.println("Feb. " + gainTC[2] + " " + gainPC[2]);
System.out.println("Mar. " + gainTC[3] + " " + gainPC[3]);
System.out.println("Apr. " + gainTC[4] + " " + gainPC[4]);
System.out.println("May " + gainTC[5] + " " + gainPC[5]);
System.out.println("Jun. " + gainTC[6] + " " + gainPC[6]);
System.out.println("Jul. " + gainTC[7] + " " + gainPC[7]);
System.out.println("Aug. " + gainTC[8] + " " + gainPC[8]);
System.out.println("Sep. " + gainTC[9] + " " + gainPC[9]);
System.out.println("Oct. " + gainTC[10] + " " + gainPC[10]);
System.out.println("Nov. " + gainTC[11] + " " + gainPC[11]);
System.out.println("Dec. " + gainTC[12] + " " + gainPC[12]);
}
}
}
Here is an incomplete example so you can fill in the blanks yourself:
double gainT[]={54.3, 57.0, 62.5, 67.6, 74.3, 79.2, 80.9, 80.4, 77.8, 70.1, 62.8, 56.3};
double gainTC[] = new double[gainT.length]; //create array which matches the size of gainT
//array.length is a property value returning the 'size' or length or the array
//Now just iterate through all the gainT[] values you populated above and read each one
for(int i = 0; i < gainT.length; i++){
double math = //use your conversion math here, and store the value
gainTC[i] = math; //assign the results of your math to the same spot in the new array
}
If you'd like more information on Loops and Arrays, check here:
For Loops: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Arrays: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

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

How can I use a while to continuously ask for input from a user and exit the program when "quit" is typed without using system.exit()?

I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
next();
}
public static void next() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
next3(expression);
}
public static void next3(String expression) {
while (!expression.equals("quit")) {
next2(expression);
next();
}
}
public static void next2(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static boolean QuitFunction(String expression) {
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return false;
}
else {
return true;
}
}
}
Take a look at this code. I think this might help you in the right direction. It's similar to what you have already written except it eliminates the need for method calls in your while loop.
Scanner input = new Scanner(System.in);
while (!input.hasNext("quit")) {
String expression = input.nextLine(); // gets the next line from the Scanner
next2(expression); // process the input
}
// once the value "quit" has been entered, the while loop terminates
System.out.println("Goodbye");
Writing it this way drastically cleans up your code and prevents a new declaration of Scanner kb = new Scanner(System.in); each time an input is processed.

SimpleDateFormat showing too much info

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 + ".");

Categories