Not printing lines until after completion Java - java

I created a mortgage calculator which works just fine but I don't want to use println() when asking for user input. I want the user to be able to type on the same line; however, everytime i use print() the user input is taken but the print statements do not get read into the output until the very end.
Example of Current Output
2000
4.12
10
Principal: Annual Interest Rate: Period (years): Mortgage: $20.36
Current Code
package demos1;
import java.text.NumberFormat;
import java.util.Scanner;
/**
*
* #author nicka
*/
public class MortgageCalculator {
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
final byte MONTHS = 12;
final byte PERCENTAGE = 100;
Scanner scanner = new Scanner(System.in);
System.out.print("Principal: ");
double principal = scanner.nextDouble();
System.out.print("Annual Interest Rate: ");
double annInterest = scanner.nextDouble();
System.out.print("Period (years): ");
double periodY = scanner.nextDouble();
double monInterest = (annInterest/MONTHS)/PERCENTAGE;
double periodM = periodY*MONTHS;
double n = Math.pow((1 + monInterest) ,periodM);
double mortgage = principal*((monInterest*n)/(n-1));
String formatMortgage = NumberFormat.getCurrencyInstance().format(mortgage);
System.out.println("Mortgage: " + formatMortgage);
}
}
I was using println() before and the problem didn't occur. I also tried moving some stuff around but still the same issue..

Related

Operators can't be applied to java string

I am writing a program that takes the loan amount, interest rate, and total paid from a text file. It is supposed to update the interest rate to total interest and the same for total paid. Then it is supposed to calculate the monthly payments.
I keep getting the error operators can't be applied to java string for the calculations including loan. I'm guessing this is because you can't use strings in calculations? Maybe i'm wrong. I am stumped.
Example input:
56750.00 .065 72.00
43675.00 .075 48.00
64950.00 .045 36.00
24799.00 .085 48.00
My code
import java.io.*;
import java.util.*;
import java.text.*;
public class DB4
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException
{
String loan;
int Count = 0;
double interest = 0;
double Numberofmonths = 0;
double totint;
double totpay;
double monthly;
Scanner inFile= new Scanner(new FileReader("Project4InData.txt"));
PrintWriter outFile = new PrintWriter("Project4.out");
while (inFile.hasNext())
{
loan = inFile.next();
interest = inFile.nextDouble();
Numberofmonths = inFile.nextDouble();
// calcs
totint = interest * loan;
totpay = totint + loan;
monthly = loan / 12;
outFile.print("Loan Amount: " + loan);
outFile.print(" ");
outFile.println("Interest: " + totint);
outFile.print(" ");
outFile.println("Total paid: " + totpay);
outFile.print(" ");
outFile.println("Monthly payment: " + monthly);
}
inFile.close();
outFile.close();
}
}
loan is a string, so interest * loan doesn't make sense.
To realize why it doesn't make sense to apply * to a string, consider what "abc" * 2 or "def" * "ghi" would mean. (Absolutely nothing, which is why Java doesn't allow you to perform those operations on string objects).
You can apply + to strings, but it doesn't do addition, it does concatenation.
Same logic applies to the / operator.
Make loan a double.

New to programming, need slight assistance

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;

confused on how to call on method inside class

So I need to get input from a user, which I have done, but then I need it to print out the giveFirstClassStamps amount and givePennyStamps amount, and I am at a loss as how to do this.
Any help or pointers in the right directions would be greatly appreciated.
import java.util.*;
/**
*/
public class StampMachine
{
public static final int FIRST_CLASS_STAMP_PRICE = 44;
private int balance;
/**
Constructs a stamp machine with a zero balance.
*/
public StampMachine()
{
balance = 0;
}
public static void main( String[ ] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter 16-Digit Credit Card Number: ");
String cardNumber = input.nextLine();
System.out.print("Enter Month/Year of Expiration Date in MM/YY format: ");
String expirationDate = input.nextLine();
System.out.print("Stamp Purchase Amount: ");
int dollars = input.nextInt();
}
/**
Adds a given number of dollar bills into this machine.
#param dollars the number of dollar bills
*/
public void insert(int dollars)
{
balance = balance + 100 * dollars;
}
/**
Dispenses first class stamps for the inserted payment.
#return the number of first class stamps
*/
public int giveFirstClassStamps()
{
int firstClassStamps = balance / FIRST_CLASS_STAMP_PRICE;
balance = balance - firstClassStamps * FIRST_CLASS_STAMP_PRICE;
return firstClassStamps;
}
/**
Dispenses penny stamps for the inserted payment.
#return the number of penny stamps
*/
public int givePennyStamps()
{
int pennyStamps = balance;
balance = 0;
return pennyStamps;
}
You can create an instance of the class and then call the methods. Try the following after getting your input variables:
StampMachine sm = new StampMachine();
sm.insert(dollars);
You can continue using that same instance "sm" to call other methods as well.
In main, after getting the dollars
call insert method. Modify method sigantures to pass dollars entered by the user
call giveFirstClassStamps and assign the returned value to a local variable inside main
do the same for givePennyStamps and now print the values
Hope this helps.

Tax rate java program

I am new to java and I can't figure out what is wrong with my code. After the user inputs annual income and # of exemptions, the code stops working. There are no error messages on my console either. Please help me.
The program:
My code:
import java.util.Scanner;
public class TaxRate {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
// before asking the user for input
final double TAX_RATE = 0.12;
System.out.println ("Type in your name:");
String name;
name = sc.next();
System.out.println (name + ", type in your annual income and number of exemptions, separated by spaces:");
double income, exempt;
income = sc.nextDouble();
exempt = sc.nextDouble();
sc.close();
} // main method
} // lab class
Where you have
double num2 = 2000 * exempt;
num2 = sc.nextDouble();
you are calculating num2 and then waiting for the user to enter it.
Where you have
double adjustedGrossIncome = income - num2;
adjustedGrossIncome = sc.nextDouble();
you are calculating adjustedGrossIncome and then waiting for the user to enter it.
Where you have
double tax = TAX_RATE * adjustedGrossIncome;
tax = sc.nextDouble();
you are calculating tax and then waiting for the user to enter it.
If you take out the nextDouble() lines in those three cases, your program will run along instead of stopping for user input.
Your problem is that you ask for an input for tax that you already calculated, since that would be a useless line of code.

Making a GUI program from Commandline

import java.util.Scanner;
I am trying to turn this into a GUI program, and what I kind of came up with gives me a lot of errors, so if anyone could help me figure that out, that would be great.
public class Problemtwo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the side: ");
double side = input.nextDouble();
double area = 3 * 1.73205 * side * side / 2;
System.out.println("The area " + area);
}
}
This is the GUI I tried to create
import java.swing.JOptionPane;
import java.lang.Math;
public class GUI_Problemtwo {
public static void main(String[] args) {
double side;
double area;
StringsideString = JOptionPane.showInputDialog("Enter the side: ");
return;
}
// Convert string to double
double side = Double.parseDouble(sideString);
double side = input.nextDouble();
// Compute the area
double area = 3 * 1.73205 * side * side / 2;
// Display results
String output = "The area is " + area;
}
I just know that I'm really doing something wrong. Also I have another GUI that I'm able to input into a dialog box, but I can't get it to pull up any output in a dialog box, it just looks like it doesn't even stop running...
import javax.swing.JOptionPane;
import java.io.*;
public class GUI_Account {
public static void main(String[] args)throws IOException {
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
double bal=0;
int month,i;
// Prompts user to enter a number of months
String MString = JOptionPane.showInputDialog("Enter number of months: ");
if (MString == null) {System.out.println("User prompt cancelled");
return;
}
month=Integer.parseInt(kb.readLine());
for(i=0;i<month;i++) {
bal=(bal+100)*1.00417;
}
// Convert string to double
double M =Double.parseDouble(MString);
// Display results in dialog box
String output = "The amount is " + bal; JOptionPane.showMessageDialog(null, output);
}
}

Categories