Scanner console = new Scanner(System.in);
System.out.println("Enter Starting Balance: ");
Double balance = Double.parseDouble(console.nextLine());
System.out.println("Enter Yearly Contribution: ");
Double cont = Double.parseDouble(console.nextLine());
System.out.println("Enter Average Return On Investment as %: ");
Double avg = Double.parseDouble(console.nextLine());
System.out.println("Enter Number of years: ");
int year = Integer.parseInt(console.nextLine());
double result1 = (balance + cont) * (1 + avg / 100);
double result2 = (result1 + cont) * (1 + avg / 100);
year = 0;
while (year <= year) {
System.out.println("Year " + year + ": " + balance + "");
year = year + 1;
for (result2 = result2; result2 >= result2; result2 = result2 + result2) {
}
//I am aware that the loop is wrong, just not sure the best way to write it.
So provided there isn't a whole lot of detail, I wrote this code which results in output very close to the example you provided. Modify it as needed to match your desired output.
package various;
import java.util.Scanner;
public class Balance {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Starting Balance: ");
double balance = sc.nextDouble();
System.out.println("Enter Yearly Contribution: ");
double cont = sc.nextDouble();
System.out.println("Enter Average Return On Investment as %: ");
double avg = sc.nextDouble();
System.out.println("Enter Number of years: ");
int years = sc.nextInt();
double temp = 0;
for(int i = 0; i <= years; i++) {
double result = balance + (i*cont)+ (i*temp*(avg/100));
temp = result;
System.out.println("Year "+i+": "+result);
}
sc.close();
}
}
Related
The program is not quitting when choice 2 is entered instead it's asking to enter a positive value. It should only ask that if the choice was 1 and then the number of rooms entered was less than one. It should immediately quit the program but it's not. What can I do to fix this? Is it because of braces missing or extra ones.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Paint {
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
do {
displayMenu();
choice = keyboard.nextInt();
if (choice == 1) {
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
} while (choice != 2);
}
public static void displayMenu() {
System.out.println("1)Calculate Estimate");
System.out.println("2)Quit the program");
System.out.println("Please make a selection");
}
public static double numGallons(double sqr) {
return sqr / 115;
}
public static double numHours(double sqr) {
return (sqr / 115) * 8;
}
public static double laborCost(double cph, double nh) {
return cph * nh;
}
public static double paintCost(double ng, double cpg) {
return ng * cpg;
}
}
You should show the menu and get the choice before entering the loop, and at the end of the loop.
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
displayMenu();
choice = keyboard.nextInt();
while (choice != 2) {
//if (choice ==1)
//{
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
//}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
displayMenu();
choice = keyboard.nextInt();
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Output Error :
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of expression
I'm creating a class that calculate 1 student that take 3 quizzes 25%, 1 Midterm 25% , and 1 Final 50%
package Grading;
import java.util.Scanner;
public class Grading {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
public static double quiz1, quiz2, quiz3, midterm, finalExam, Grades, totalGrade, bothQuizzes, PfinalExam, PmidTerm;
public static String studentname;
public static int Score;
public String getstudentname( )
{
return studentname;
}
public double getquiz1()
{
return quiz1;
}
public double getquiz2 ()
{
return quiz2;
}
public double getquiz3 ()
{
return quiz3;
}
public double midterm()
{
return midterm;
}
public double finalExam()
{
return finalExam;
}
public void setquiz1 (double quiz1)
{
this.quiz1 = quiz1;
}
public void setquiz2 (double quiz2)
{
this.quiz2 = quiz2;
}
public void setquiz3 (double quiz3)
{
this.quiz3 = quiz3;
}
public void setmidterm()
{
this.midterm = midterm;
}
public void setfinalExam()
{
this.finalExam = finalExam;
}
public void setGrades ()
{
}
public String toString(){
return this.quiz1 + " " + this.quiz2 + this.quiz3 + " " + this.midterm + " " + this.finalExam;
}
public static void readInput(){
System.out.println("Please enter the grade you got for the first quiz: ");
quiz1 = grades.nextInt();
while (quiz1 <0 || quiz1>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz1 = grades.nextInt();
}
System.out.println("Please enter the grade you got for the second quiz: ");
quiz2 = grades.nextInt();
while (quiz2 <0 || quiz2>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz2 = grades.nextInt();
}
System.out.println("Please enter the grade you got for the third quiz: ");
quiz3 = grades.nextInt();
while (quiz3 <0 || quiz3>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz3 = grades.nextInt();
}
System.out.println("Please enter the grade you got on your midterm: ");
midterm = grades.nextInt();
while (midterm <0 || midterm>100)
{
System.out.println("Please enter a grade between 0 and 100: ");
midterm = grades.nextInt();
}
System.out.println("Please enter the grade you got on your final exam: ");
finalExam = grades.nextInt();
while (finalExam < 0 || finalExam > 100)
{
System.out.println("Please enter a grade between 0 and 100: ");
finalExam = grades.nextInt();
}
}
public static void output()
{
System.out.println(" your score for the first quiz was " + quiz1 );
System.out.println("your score for the second quiz was " + quiz2);
System.out.println("your score for the third quiz was " + quiz3);
System.out.println(" your score for the midterm was " + midterm );
System.out.println("your score for the final exam was " + finalExam);
bothQuizzes = ((quiz1 + quiz2 + quiz3)/100)*.25;
PmidTerm = (midterm/100) *.35;
PfinalExam = (finalExam/100) * .40;
System.out.println("Your total grade for these grades is " + totalGrade + "%");
System.out.println("Your total grade for these grades is " + totalGrade);
double letterGrade = totalGrade;
if (letterGrade >= 90)
{
System.out.println("Your grade is an A");
// grade = "A";
}
else if (letterGrade >= 80)
{
System.out.println("Your grade is a B");
}
else if (letterGrade >= 70)
{
System.out.println("Your grade is a C");
}
else if (letterGrade >= 60)
{
System.out.println("Your grade is a D");
}
else
{
System.out.println("Your grade is an F");
}
}}
I have re-written your program. I hope that this is what you wanted to achieve. I didn't know how you wanted to count the grade, so I've marked the place where you can change that code with a comment.
Since there were some major problems in your code with field declaration and function bodies, I've reorganized them. You can take a look at this code:
import java.util.Scanner;
public class Grading {
private int quiz1, quiz2, quiz3, midterm, finalExam; //quizzes exams tests what grades
public void readInput () {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the grade you got for the first quiz: ");
quiz1 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got for the second quiz: ");
quiz2 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got for the third quiz: ");
quiz3 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got on your midterm: ");
midterm = readInt(in, 0, 100);
System.out.print("Please enter the grade you got on your final exam: ");
finalExam = readInt(in, 0, 100);
}
public void output () {
System.out.println("Your score for the first quiz was " + quiz1);
System.out.println("Your score for the second quiz was " + quiz2);
System.out.println("Your score for the third quiz was " + quiz3);
System.out.println("Your score for the midterm was " + midterm);
System.out.println("Your score for the final exam was " + finalExam);
//dunno if this is the way you want to count it; change as needed
double quizzes = (quiz1 + quiz2 + quiz3) / 100 * 0.25;
double Pmidterm = midterm / 100 * 0.25;
double PfinalExam = finalExam /100 * 0.50;
double totalGrade = (quizzes + Pmidterm + PfinalExam) * 100.0;
char grade;
if (totalGrade >= 90)
grade = 'A';
else if (totalGrade >= 80)
grade = 'B';
else if (totalGrade >= 70)
grade = 'C';
else if (totalGrade >= 60)
grade = 'D';
else grade = 'F';
System.out.printf("Your grade is %c\n", grade);
}
private int readInt (Scanner in, int min, int max) {
int value = in.nextInt();
if (value < min || value > max) {
System.out.printf("Please enter a grade between %d and %d: ", min, max);
return readInt(in, min, max);
}
return value;
}
public static void main(String[] args) {
Grading grading = new Grading();
grading.readInput();
grading.output();
}
}
You never closed your main function
public static void main(String[] args) {
Scanner keybNum = new Scanner(System.in);
Scanner keybStr = new Scanner(System.in);
boolean yn = false;
//Start of program
System.out.println("Welcome to Currency Exchanger");
System.out.print("Are you an Account Holder (y or n)? ");
String AccHolder = keybStr.next();
boolean blnYN = true;
//validation of y/n answer
while (blnYN) {
if (AccHolder.equalsIgnoreCase("y")) {
yn = true;
blnYN = false;
break;
}//if
else if (AccHolder.equalsIgnoreCase("n")) {
yn = false;
blnYN = false;
break;
}//else if
else {
System.out.println("Invalid value entered. Choose either y/n.");
AccHolder = keybStr.next();
}//else
}//while
//Start of menu choices
System.out.println("Please choose from the following menu.");
System.out.println("\n1: Exchange another currency for Sterling");
System.out.println("2: Buy another currency from us");
System.out.println("0: Exit");
System.out.print("Which option? ");
int MenuChoice = keybNum.nextInt();
//Exchange Variables (First option)
double Euro = 1.37;
double USAD = 1.81;
double JapYen = 190.00;
double Zloty = 5.88;
//Buy Variables (Second Option)
double EuroB = 1.21;
double USADB = 1.61;
double JapYenB = 163.00;
double ZlotyB = 4.89;
//First menu choice screen
if (MenuChoice == 1) {
System.out.println("Currencies to exchange into sterling?");
System.out.println("Euro - EUR");
System.out.println("USA Dollar - USD");
System.out.println("Japanese Yen - JPY");
System.out.println("Polish Zloty - PLN");
System.out.print("Please enter the three letter currency: ");
//Currency input validation
String CurChoice = "";
boolean isCorrectCurrency = false;
do {
CurChoice = keybStr.next();
isCorrectCurrency = CurChoice.matches("^EUR|USD|JPY|PLN$");
if (isCorrectCurrency) {
System.out.println("");
} else {
System.out.print("Invalid Currency Entered. Please Retry: ");
}
} while (!isCorrectCurrency);
//Exchange amount calculator
System.out.print("Enter the amount you wish to exchange of " + CurChoice + ": ");
double ExcAmount = keybStr.nextInt();
double result = 0.00;
//Selection and calculation of user's input
if (CurChoice.equals("EUR")) {
result = ExcAmount / Euro;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("USD")) {
result = ExcAmount / USAD;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("JPY")) {
result = ExcAmount / JapYen;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("PLN")) {
result = ExcAmount / Zloty;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else {
System.out.println("");
}
Right, this is where I am stuck. So this program is a currency exchange converter. The part I'm unsure about is to calculate the commission. At the start I ask the user if they're an account holder. If they're they don't get charged a commission, whereas if they're then they do. If the amount they wish to exchange is less than £1000 then they get charged a commission of 2%, and if its over £1000 then they get charged a commission of 1%. I wasn't sure how to implement this into my program, so i'm asking you guys to help.
Try this after calculating the result:
double commission = 0.;
if (ExcAmount < 1000) {
commission = result * 0.02;
} else {
commission = result * 0.01;
}
result += commission;
String stringToPrint = "";
if (!yn) { //you could use meaningful variable names
stringToPrint = "Commission = " + commission;
} else {
stringToPrint = "Commission = Not charged";
}
System.out.println(stringToPrint + "\nTotal = " + (result - commission));
My program will calculate the area but I need to have each different shape in it's own method and I'm having difficulty understanding how to first separate them all into their own method and link them all together. Any help is much appreciated.
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "Please choose which area/volume to calculate: 1-Circle 2-Triangle 3-Cone 4-Cylinder 5-Sphere 6-Quit: ";
System.out.print(s);
System.out.println(" ");
int num = keyboard.nextInt();
if (num < 1 || num > 6){
System.out.print("Please choose a number between 1 and 6: ");
num = keyboard.nextInt();
}
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 2){
System.out.print("Please enter the base: ");
double b = keyboard.nextDouble();
double at;
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
at = .5 * b * h;
System.out.print("The area of the triangle is: " + at);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 3){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double v1;
v1 = (1/3) * 3.14 * r * r * h;
System.out.print("The volume of the cone is: " + v1);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 4){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double vc;
vc = 3.14 * r * r * h;
System.out.print("The volume of the cylinder is: " + vc);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 5){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double vs;
vs = (4/3) * 3.14 * r * r * r;
System.out.print("The volume of the sphere is: " + vs);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 6){
System.out.print("Thank you for using this program");
}
}
}
You can use switch..case
switch(num) {
case 1: calculateCircleArea();
break;
case 2: calculateTriangleArea();
break;
case 3: calculateConeVolume();
break;
case 4: calculateCylinderVolume();
break;
case 5: calculateSphereVolume();
break;
case 6: System.out.print("Thank you for using this program");
break;
default: System.out.print("Please choose a number between 1 and 6: ");
break;
}
You can create new private/public methods to do the calculations and seperate them.
Take this part
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
You can create a new method for the calculation like so
public static double getArea(double radius)
{
return 3.14*radius*radius;
}
Then, inside your if statement you can say
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = getArea(r);
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
you see in this case, you get a one-line method which isn't very usefull. But you can split off more extensive calculations as well, this is just as an example. In addition, instead of all the if-blocks, you can use a switch statement like the other answer shows you.
I cannot figure this problem out. Everything in the program works the way i want it to except after i use the 'o' open account option, 'w' withdrawal accout options.. etc that after completion, repeats the loop as desired, but returns the else line "Command was not recognized; please try again." and then reprints the menu. If i use the 's' command it works fine. i removed the "balance = input.nextDouble();" line and it works correctly, but i can't figure out why it returns the else statement and reprints.
import java.util.Scanner;
import java.text.*;
public class Bank
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
String eol = System.getProperty("line.separator");
DecimalFormat df = new DecimalFormat("0.00");
int numAccounts = 1;
String number = "None Selected";
String userInput;
double balance = 0;
double amount = 0;
int i = 0;
int j;
BankAccount[] accounts = new BankAccount [100];
accounts[0] = new BankAccount (number, balance);
String BBalance = df.format(accounts[i].getBalance());
while (1 < 2){
if (numAccounts == accounts.length){
BankAccount[] tempArray = new BankAccount[accounts.length * 2];
for (int k = 0; k < accounts.length; k++){
tempArray[k] = accounts[k];
}
accounts = tempArray;
}
try{
System.out.print ( eol +
"-----------------------------------------------------" + eol +
"|Commands: o - Open account c - Close account|" + eol +
"| d - Deposit w - Withdraw |" + eol +
"| s - Select account q - Quit |" + eol +
"-----------------------------------------------------" + eol +
"Current account: " + accounts[i].getNumber() + " Balance: $" + df.format(accounts[i].getBalance()) +
eol );
}
catch(java.lang.Throwable t) {
System.out.println("Account number was not found");
}
userInput = input.nextLine().trim().toLowerCase();
if (userInput.substring(0).equals("o")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
System.out.print("Enter Initial Balance: ");
balance = input.nextDouble();
accounts[numAccounts++] = new BankAccount (number, balance);
i = numAccounts - 1;
continue;
}
else if (userInput.substring(0).equals("d")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
System.out.print("Enter Amount To Deposit: ");
amount = input.nextDouble();
accounts[i].deposit(amount);
continue;
}
else if (userInput.substring(0).equals("s")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++){
if (accounts[i].getNumber().equals(number)){
break;
}
}
if (i != numAccounts){
System.out.print("Account number was not found");
}
continue;
}
else if (userInput.substring(0).equals("c")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
accounts[i] = accounts[--numAccounts];
continue;
}
else if (userInput.substring(0).equals("w")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
System.out.print("Enter Amount To Withdraw: ");
amount = input.nextDouble();
accounts[i].withdraw(amount);
continue;
}
else if (userInput.substring(0).equals("q")) {
System.exit(0);
}
else{
System.out.println("Command was not recognized; please try again.");
continue;
}
}
//System.out.print(userInput);
//System.out.print(accounts[0]);
}
}
Here's the BankAccount class:
public class BankAccount {
String number = "123-456";
double balance = 1.00;
public BankAccount(String accountNumber, double initialBalance){
number = accountNumber;
balance = initialBalance;
}
public void deposit (double amount){
balance += amount;
}
public void withdraw (double amount){
balance -= amount;
}
public String getNumber(){
return number;
}
public double getBalance(){
return balance;
}
BankAccount[] accounts = new BankAccount [100];
}
You're not skipping past the end of the lines when you're reading in the second numbers in the commands that require one.
Adding an input.nextLine() to those is one quick way around it (non I/O lines redacted).
// etc.
} else if (userInput.substring(0).equals("d")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
System.out.print("Enter Amount To Deposit: ");
amount = input.nextDouble();
input.nextLine();
continue;
} // etc.