I'm building this weird BMI/BMR calculator for school and right now the code does what I want it to do. But I need to add an if (I think) that makes sure that the user doesn't type in values that are too small or too big. The user is only allowed to type in "vikt" between 0.5 and 2.2. If the user types in a faulty value I need the program to execute an else that prints out a "nope you did it wrong".
My problem is that I do not know where to put the if so that the code still works.
So my question is, where and how do I add an if to my code?
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
// Ledtext
System.out.println("Beräkna ditt BMI");
System.out.print("Tryck j för att starta: " );
char fortsätt = input.next().charAt(0);
System.out.println(" ");
do
{
//Användaren matar in sin data
System.out.print("Ange personens vikt (kg): ");
double vikt = input.nextDouble();
System.out.print("Ange personens längd (m): ");
double längd = input.nextDouble();
System.out.print("Ange personens ålder: ");
double ålder = input.nextDouble();
System.out.println(" ");
System.out.println("Beräknat BMI för både män och kvinnor är " + bmi(vikt, längd));
System.out.println("Beräknat BMR för män är: " + kalorier_Män(vikt, längd, ålder));
System.out.println("Beräknat BMR för kvinnor är: "+ kalorier_Kvinnor(vikt, längd, ålder));
System.out.println(" ");
System.out.print("Fortsätta? (j/n): ");
fortsätt = input.next().charAt(0);
}
while (fortsätt != 'n');
}
static double bmi(double vikt, double längd){
double bmiMänochKvinnor;
bmiMänochKvinnor = (1.3 * vikt) / Math.pow(längd, 2.5);
return bmiMänochKvinnor;
}
static double kalorier_Män (double vikt,double längd,double ålder){
double manBmr;
manBmr = (9.99 * vikt) + (6.25 * längd) - (4.92 * ålder) + 5;
return manBmr;
}
static double kalorier_Kvinnor (double vikt,double längd,double ålder){
double kvinnaBmr;
kvinnaBmr = (9.99 * vikt) + (6.25 * längd) - (4.92 * ålder) - 161;
return kvinnaBmr;
}
}
From my understanding you want to constrain the values the user can use as an input for this line:
double vikt = input.nextDouble();
You can simply do this by adding an if statement right after that where you check the entered value. If the value doesn't match the condition, you can send a message and continue the loop.
if (vikt < 0.5 || vikt > 2.2) {
// send some message
continue;
}
You can check the values directly after they are read, with an if else statement like this:
if(vikt > 2.2 || vikt < 0.5){
System.out.println("nope you did it wrong");
return; // this will stop the code
}
A better way of handling this problem would be the following function:
private static double retrieveValue(Scanner input, double min, double max, String requestMessage){
while(true){
System.out.println(requestMessage);
double measure = input.nextDouble();
if (measure >= min && measure <= max){
return measure;
} else{
System.out.println("This values is not allowed, please try again:");
}
}
}
You can call it like this:
double vikt = retrieveValue(input, 0.5, 2.2, "Ange personens vikt (kg):");
Related
I am a bit confused, I have a little program I wrote for a school assignment, the constraints I am required to work with is that no method can contain more than 15 lines of code, and we cannot use any for next loops.
What I cant seem to figure out is why I am able to pass an integer to my rounding method and it even returns the rounded value, but then it jumps back to my if / then statements (which it shouldnt be doing) and does not pass the variable.
It is a very rudimentary program I know...my coding skills are not very good, but any help would be appreciated.
The variables I need passed back are testscore and GPA, those need to go back to the main method so they can be stored to new variables and finally pushed off into the results method.
Im still pretty new to coding and the community and how things work...
import java.util.*;
public class Admit {
public static void main(String[] Args) {
Scanner console = new Scanner(System.in);
Introduction();
double testscore = 0;
double GPA = 0;
int Student = 1;
ACTSATScores(1,0,console);
double StudentOneTestScore = testscore;
GPAInfo(0,console);
double StudentOneGPAScore = GPA;
Student = 2;
ACTSATScores(2,0,console);
double StudentTwoTestScore = testscore;
GPAInfo(0,console);
double StudentTwoGPAScore = GPA;
DisplayResults(StudentOneTestScore,StudentOneGPAScore,StudentTwoTestScore,StudentTwoGPAScore);
}
public static void Introduction() {
System.out.println("This program compares two applicants to");
System.out.println("determine which one seems like the stronger");
System.out.println("applicant. For each candidate I will need");
System.out.println("either SAT or ACT scores plus a weighted GPA.");
System.out.println();
}
public static double ACTSATScores(int Student,double testscore,Scanner console) {
System.out.println("Information for applicant #" + Student + ":");
System.out.print("do you have 1) SAT scores or 2) ACT scores? ");
int ACTSAT = console.nextInt();
if ( ACTSAT == 1) {
SAT(Student,testscore,console);
}
if ( ACTSAT == 2) {
ACT(Student,testscore,console);
}
return testscore;
}
public static double SAT(int Student,double testscore,Scanner console) {
System.out.print("SAT math? ");
int SATMath = console.nextInt();
System.out.print("SAT critical reading? ");
int SATReading = console.nextInt();
System.out.print("SAT writing? ");
int SATWriting = console.nextInt();
testscore = ( ( 2 * SATMath + SATReading + SATWriting ) / 32);
System.out.println("exam score = " + roundNumber(testscore));
return ( ( 2 * SATMath + SATReading + SATWriting ) / 32);
}
public static double ACT(int Student,double testscore,Scanner console) {
System.out.print("ACT English? ");
int ACTEnglish = console.nextInt();
System.out.print("ACT math? ");
int ACTMath = console.nextInt();
System.out.print("ACT reading? ");
int ACTReading = console.nextInt();
System.out.print("ACT science? ");
int ACTScience = console.nextInt();
testscore = ( ( 2 * ACTMath + ACTEnglish + ACTReading + ACTScience ) / 1.8 );
System.out.println("exam score = " + roundNumber(testscore));
return testscore;
}
public static double GPAInfo(double GPA,Scanner console) {
System.out.print("overall GPA? ");
double OverallGPA = console.nextDouble();
System.out.print("max GPA? ");
double MaxGPA = console.nextDouble();
System.out.print("Transcript Multiplier? ");
double TranscriptMultiplier = console.nextDouble();
GPA = ( OverallGPA / MaxGPA * 100 * TranscriptMultiplier );
System.out.println("GPA score = " + roundNumber(GPA));
return GPA;
}
public static double roundNumber(double number) {
return (Math.round(number * 10)) / 10.0;
}
public static double DisplayResults(double StudentOneTestScore, double StudentOneGPAScore, double StudentTwoTestScore, double StudentTwoGPAScore) {
System.out.println("First applicant overall score = " + StudentOneTestScore + StudentOneGPAScore);
System.out.println("Second applicant overall score = " + StudentTwoTestScore + StudentTwoGPAScore);
if ( StudentOneTestScore + StudentOneGPAScore > StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The first applicant seems to be better");
}
else if ( StudentOneTestScore + StudentOneGPAScore < StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The second applicant seems to be better");
}
else {
System.out.println("The two applicants seem to be equal");
}
return StudentOneTestScore;
}
}
Expected output:
This program compares two applicants to
determine which one seems like the stronger
applicant. For each candidate I will need
either SAT or ACT scores plus a weighted GPA.
Information for applicant #1:
do you have 1) SAT scores or 2) ACT scores? 1
SAT math? 450
SAT critical reading? 530
SAT writing? 490
exam score = 60.0
overall GPA? 3.4
max GPA? 4.0
Transcript Multiplier? 0.9
GPA score = 76.5
Information for applicant #2:
do you have 1) SAT scores or 2) ACT scores? 2
ACT English? 25
ACT math? 20
ACT reading? 18
ACT science? 15
exam score = 54.4
overall GPA? 3.3
max GPA? 4.0
Transcript Multiplier? 0.95
GPA score = 78.4
First applicant overall score = 136.5
Second applicant overall score = 132.8
The first applicant seems to be better
My output
This program compares two applicants to
determine which one seems like the stronger
applicant. For each candidate I will need
either SAT or ACT scores plus a weighted GPA.
Information for applicant #1:
do you have 1) SAT scores or 2) ACT scores? 1
SAT math? 450
SAT critical reading? 530
SAT writing? 490
exam score = 60.0
overall GPA? 3.4
max GPA? 4.0
Transcript Multiplier? 0.9
GPA score = 76.5
Information for applicant #2:
do you have 1) SAT scores or 2) ACT scores? 2
ACT English? 25
ACT math? 20
ACT reading? 18
ACT science? 15
exam score = 54.4
overall GPA? 3.3
max GPA? 4.0
Transcript Multiplier? 0.95
GPA score = 78.4
First applicant overall score = 0.00.0
Second applicant overall score = 0.00.0
The two applicants seem to be equal
Corrected Code for anyone that needs it
import java.util.*;
public class Admit {
public static void main(String[] Args) {
Scanner console = new Scanner(System.in);
Introduction();
int Student = 1;
double StudentOneTestScore = ACTSATScores(1,console);
double StudentOneGPAScore = GPAInfo(0,console);
Student = 2;
double StudentTwoTestScore = ACTSATScores(1,console);
double StudentTwoGPAScore = GPAInfo(0,console);
DisplayResults(StudentOneTestScore,StudentOneGPAScore,StudentTwoTestScore,StudentTwoGPAScore);
}
public static void Introduction() {
System.out.println("This program compares two applicants to");
System.out.println("determine which one seems like the stronger");
System.out.println("applicant. For each candidate I will need");
System.out.println("either SAT or ACT scores plus a weighted GPA.");
System.out.println();
}
public static double ACTSATScores(int Student,Scanner console) {
double testscore = 0;
System.out.println("Information for applicant #" + Student + ":");
System.out.print(" do you have 1) SAT scores or 2) ACT scores? ");
int ACTSAT = console.nextInt();
if ( ACTSAT == 1) {
testscore = SAT(console);
}
if ( ACTSAT == 2) {
testscore = ACT(console);
}
return testscore;
}
public static double SAT(Scanner console) {
System.out.print(" SAT math? ");
int SATMath = console.nextInt();
System.out.print(" SAT critical reading? ");
int SATReading = console.nextInt();
System.out.print(" SAT writing? ");
int SATWriting = console.nextInt();
double testscore = ( ( 2 * SATMath + SATReading + SATWriting ) / 32);
System.out.println(" exam score = " + roundNumber(testscore));
return testscore;
}
public static double ACT(Scanner console) {
System.out.print(" ACT English? ");
int ACTEnglish = console.nextInt();
System.out.print(" ACT math? ");
int ACTMath = console.nextInt();
System.out.print(" ACT reading? ");
int ACTReading = console.nextInt();
System.out.print(" ACT science? ");
int ACTScience = console.nextInt();
double testscore = ( ( 2 * ACTMath + ACTEnglish + ACTReading + ACTScience ) / 1.8 );
System.out.println(" exam score = " + roundNumber(testscore));
return testscore;
}
public static double GPAInfo(double GPA,Scanner console) {
System.out.print(" overall GPA? ");
double OverallGPA = console.nextDouble();
System.out.print(" max GPA? ");
double MaxGPA = console.nextDouble();
System.out.print(" Transcript Multiplier? ");
double TranscriptMultiplier = console.nextDouble();
GPA = ( OverallGPA / MaxGPA * 100 * TranscriptMultiplier );
System.out.println(" GPA score = " + roundNumber(GPA));
System.out.println();
return GPA;
}
public static double roundNumber(double number) {
return (Math.round(number * 10)) / 10.0;
}
public static double finalScore(double TestScore, double GPAScore) {
return TestScore + GPAScore;
}
public static double DisplayResults(double StudentOneTestScore, double StudentOneGPAScore, double StudentTwoTestScore, double StudentTwoGPAScore) {
double StudentOneScore = finalScore(StudentOneTestScore,StudentOneGPAScore);
double StudentTwoScore = finalScore(StudentTwoTestScore,StudentTwoGPAScore);
System.out.println("First applicant overall score = " + roundNumber(StudentOneScore)); //StudentOneTestScore + StudentOneGPAScore);
System.out.println("Second applicant overall score = " + roundNumber(StudentTwoScore)); //StudentTwoTestScore + StudentTwoGPAScore);
if ( StudentOneTestScore + StudentOneGPAScore > StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The first applicant seems to be better");
} else if ( StudentOneTestScore + StudentOneGPAScore < StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The second applicant seems to be better");
} else {
System.out.println("The two applicants seem to be equal");
}
return StudentOneTestScore;
}
}
It seems you have a problem when using methods, returning types and inmutable types.
In the main section:
double testscore = 0;
double GPA = 0;
int Student = 1;
ACTSATScores(1,0,console);
double StudentOneTestScore = testscore;
GPAInfo(0,console);
double StudentOneGPAScore = GPA;
Student = 2;
ACTSATScores(2,0,console);
double StudentTwoTestScore = testscore;
You are assigning those variables the value "testscore". But you really never change that value, and the way you wrote the methods makes me believe that you are expecting testscore to change inside the methods.
Try printing the value of testscore in the main to see that it does not change its value (it should be always 0 in that main). This might be what you are looking for:
double StudentOneTestScore = ACTSATScores(1,0,console);
I am extremely new to java I am in my second week in classes or so--
I need my program to keep going or exit according to the user. It is a payroll calculation and I want the end to say "Do you want to continue (y/n)" I want Y to repeat my entire program of questions and no to end program. I am using Jgrasp and I am very very new. I am assuming it needs a loop and I am not totally sure, I just got this to run and compile correctly-- it runs correctly for me so it is a good start and I am hoping to get help on how to do this as I am seeing a ton of different ways and different programs for it. thanks.
import java.util.Scanner;
public class calculations {
public static void main(String [] args) {
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
double Regpay;
double Payperhour;
int HoursAweek;
double Pay;
double OvertimeHours;
double OvertimePay;
double Dependants;
double SocSecTax;
double FederalTax;
double StateTax;
int UnionDues;
double AllTaxes;
double FinalPay;
String playAgain;
System.out.print("Enter your pay per hour:");
Payperhour = reader.nextDouble ();
System.out.print("Enter your regular Hours a week:");
HoursAweek = reader.nextInt();
System.out.print("Enter your overtime hours:");
OvertimeHours = reader.nextDouble();
Regpay = Payperhour * HoursAweek;
OvertimePay = OvertimeHours * 1.5 * Payperhour;
Pay = OvertimePay + Regpay;
SocSecTax = Pay * .06;
FederalTax = Pay * .14;
StateTax = Pay * .05;
UnionDues = 10;
AllTaxes = SocSecTax + FederalTax + StateTax + UnionDues;
FinalPay = Pay -= AllTaxes;
System.out.println("Your pay this week will be " +FinalPay);
{
System.out.println("How many Dependants:");
Dependants = reader.nextInt();
if (Dependants >= 3) {
Dependants = Pay + 35;
System.out.println("Your Pay is:" +Dependants);
} else if(Dependants < 3) {
System.out.println("Your Pay is:" +Pay);
}
}
}
}
Here is the basic idea with your code:
import java.util.Scanner;
public class calculations{
public static void main(String [] args) {
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
double Regpay;
double Payperhour;
int HoursAweek;
double Pay;
double OvertimeHours;
double OvertimePay;
double Dependants;
double SocSecTax;
double FederalTax;
double StateTax;
int UnionDues;
double AllTaxes;
double FinalPay;
String playAgain;
int runAgain = 1;
while (runAgain == 1) {
System.out.print("Enter your pay per hour:");
Payperhour = reader.nextDouble();
System.out.print("Enter your regular Hours a week:");
HoursAweek = reader.nextInt();
System.out.print("Enter your overtime hours:");
OvertimeHours = reader.nextDouble();
Regpay = Payperhour * HoursAweek;
OvertimePay = OvertimeHours * 1.5 * Payperhour;
Pay = OvertimePay + Regpay;
SocSecTax = Pay * .06;
FederalTax = Pay * .14;
StateTax = Pay * .05;
UnionDues = 10;
AllTaxes = SocSecTax + FederalTax + StateTax + UnionDues;
FinalPay = Pay -= AllTaxes;
System.out.println("Your pay this week will be " + FinalPay);
{
System.out.println("How many Dependants:");
Dependants = reader.nextInt();
if (Dependants >= 3) {
Dependants = Pay + 35;
System.out.println("Your Pay is:" + Dependants);
} else if (Dependants < 3) {
System.out.println("Your Pay is:" + Pay);
}
}
System.out.println("Again??? Press 1 to run again and 0 to exit");
runAgain = reader.nextInt();
}
}
}
Here's a guide for you..
You can create a method for the transaction.
//Place this on your main method
do{
//call the method
transaction();
//ask if the user wants to repeat the program
System.out.print("Do you want to continue (y/n)");
input = reader.nextLine();
}while(input.equalsIgnoreCase("Y"))
public void transaction(){
//your transaction code here..
}
Here is a brief idea of how to do this:
String choice = "y";
while(true) {
//Take input
System.out.print("Do you want to continue (y/n)?");
choice = reader.nextLine();
if(choice.equalsIgnoreCase("n")) break;
//else do your work.
}
You can also sue do-while to get what you want. You may need to make some changes but then that is the entire idea. It is just a hint.
What am I missing here? The program runs, but only the first if statement runs when i type in Sin in any case. When i type cos or tan. It will just print literally just cos, or tan.
public class SinCosTanFormula {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double angle, sin, cos, tan, opp, adj, hyp;
boolean function;
System.out.println("ENTER Function Needed (ex. sin, cos, tan)");
System.out.print("> ");
function = sc.hasNext();
if (function == sc.next().equalsIgnoreCase("sin")) {
System.out.println("(Sin = opp/hyp )");
System.out.println();
System.out.print("ENTER Angle > ");
angle = sc.nextDouble();
System.out.print("ENTER Opposite Side of Angle >");
opp = sc.nextDouble();
System.out.print("ENTER Hypotenuse Side > ");
hyp = sc.nextDouble();
sin = opp / hyp;
System.out.println("Sin" + "(" + angle + ")" + " = " + sin);
} else if (function == sc.next().equalsIgnoreCase("cos")) {
System.out.println("(Cos = adj/hyp )");
System.out.println();
System.out.println("ENTER Angle > ");
angle = sc.nextDouble();
System.out.print("ENTER Adjacent Side of Angle > ");
adj = sc.nextDouble();
System.out.print("ENTER Hypotenuse Side > ");
hyp = sc.nextDouble();
cos = adj / hyp;
System.out.println("Cos" + "(" + angle + ")" + " = " + cos);
} else if (function == sc.next().equalsIgnoreCase("tan")) {
System.out.println("(Tan = opp/adj )");
System.out.println();
System.out.print("ENTER Angle > ");
angle = sc.nextDouble();
System.out.print("ENTER Opposite Side of Angle > ");
opp = sc.nextDouble();
System.out.print("ENTER Adjacent Side of Angle > ");
adj = sc.nextDouble();
tan = opp / adj;
System.out.println("Tan" + "(" + angle + ")" + " = " + tan);
} else {
System.out.println("Check inputted data");
}
}
}
You should only call sc.next() once, before all the if statements - store it somewhere and use that in the if-statements instead.
When you put sc.next() in each if check, and your input doesn't match 'sin', then it'll stop there and wait for input because the else if block that's coming up also has an sc.next() call.
Here's what your program is really doing:
if (the next input is "sin") {
} else (get another input and check if it's "cos") {
} else (get another input and check if it's "tan") {
} else {
print error message
}
sc.next().equalsIgnoreCase(...
You are pulling another word / token every time you call sc.next(). This is why it is not working
I have to allow the user to choose which conversion to do, and what degree to start at, then print the conversion starting at that degree up to the next 9 (10 conversions). And I have to write this using a callback function. Also there is a menu in the beginning. I have an "else without if" at line . Also my callback function is not calculating numbers correctly. How do I resolve this error and fix my callback function?
import java.util.Scanner;
public class FahrToCel {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
double choice = 0;
double fahrenheit = 0;
double celsius = 0;
double answer = 0;
//print the welcome message and the menu options for the user
System.out.printf("Welcome to Candace's Fahrenheit and Celsius "
+ "convertor. ");
System.out.printf("Please choose one of the following options: \n"
+ " Press 0 to exit \n Press 1 to to convert to Celsius \n"
+ " Press 2 to convert to Fahrenheit > ");
choice = input.nextInt();
//print what happens when the user hits a button
if (choice == 0){
// the user is going to exit the game
System.out.printf("Well hopefully you can play again soon! :) ");
} else {
//perform code for the operation
for ( double i = fahrenheit; i >-100; i-=10 ){
if (choice == 1) {
// it will convert from fahrenheit to celsius
System.out.printf("Please pick a number in Fahrenheit: > ");
fahrenheit = input.nextDouble();
celsius = FahrToCel();
System.out.printf("%f ", i);
}
}
for ( double i = celsius; i >-10; i-=10 ){
if (choice == 2){
// it will convert from celsius to fahrenheit
System.out.printf("Please pick a number in celsius: > ");
celsius = input.nextDouble();
fahrenheit = CelToFahr();
System.out.printf("%f ", i);
}
}
} else {
System.out.printf("I'm sorry, I did not ask you to enter that "
+ "number. ");
}
}
public static double CelToFahr(){
double celsius = 0;
double fahrenheit = 0;
celsius = (fahrenheit - 32) * (5.0/9.0);
return celsius;
}
public static double FahrToCel( ){
//perform the conversion for fahrenheit to celsius
double celsius = 0;
double fahrenheit = 0;
fahrenheit = ((9.0/5.0) + 32) * celsius;
return fahrenheit;
}
}
You are looking for a structure like this
if (choice == 0){
// ...
}
else if (choice == 1) {
for ( double i = fahrenheit; i >-100; i-=10 ){
// ...
}
}
else if (choice == 2) {
for ( double i = celsius; i >-10; i-=10 ){
// ...
}
}
else {
// ...
}
Right now you have some if statements inside of an else and your scope is getting confused. Your loops would then go inside those else if statements. Also note that you are doing the conversion many times, but printing the initial value entered each time, not the converted temperature.
Among other things, (EDIT) ONE OF your functions is not quite right. Since they involve math, I'm offering my revisions instead of hints.
I don't know if you want to pass in the value you're converting from, but doing so would make it better.
You definitely don't want to set both celsius and fahrenheit to zero in both functions.
public static double FahrToCel(double fahrenheit ){
double celsius;
celsius = (fahrenheit - 32) * (5.0/9.0);
return celsius;
}
public static double CelToFahr( double celsius){
//perform the conversion for fahrenheit to celsius
double fahrenheit;
fahrenheit = ((9.0/5.0) ) * celsius + 32;
return fahrenheit;
This would mean that inside your for loops, the calls to the functions would have to be something like:
celsius = input.nextDouble();
fahrenheit = CelToFahr(celsius);
But I'm not sure you should input the next value of celsius, if I'm reading the instructions and intent of the for loops correctly.
Maybe you want this instead of inputting:
celsius = i;
I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)