Only accept positive integers using while loop or any other - java

My program currently rejects any inputs other than an integer, but I'm trying to take it one step further and have it accept only positive integers. How would i accomplish this. I tried creating another boolean and calling it numisGreat and another do-while loop for this part, but I'm cant seem to get it.
import java.util.Scanner;
public class TandE {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int firstN = 0;
int secondN = 0;
boolean isNumber = false;
boolean numisGreat = false;
System.out.print("Enter a positive integer: ");
do {
if (input.hasNextInt()) {
firstN = input.nextInt();
isNumber = true;
} else {
System.out.print("Please enter a positive integer: ");
isNumber = false;
input.next();
}
} while (!(isNumber));
System.out.print("Enter another positive integer: ");
do {
if (input.hasNextInt()) {
secondN = input.nextInt();
isNumber = true;
} else {
System.out.print("Please enter a positive integer: ");
isNumber = false;
input.next();
}
} while (!(isNumber));
System.out.println("The GCD of " + firstN + " and " + secondN + " is " + gCd(firstN, secondN));
}
public static int gCd(int firstN, int secondN) {
if (secondN == 0) {
return firstN;
} else
return gCd(secondN, firstN % secondN);
}
}

Just add a condition that tests if the input number is positive :
boolean isPosNumber = false;
do {
if (input.hasNextInt()) {
firstN = input.nextInt();
if (firstN > 0) {
isPosNumber = true;
} else {
System.out.println("You entered a non-positive number, try again: ");
}
} else {
System.out.print("Please enter a positive integer: ");
isPosNumber = false;
input.next();
}
} while (!isPosNumber);

Related

Cant get my integers to add to get correct output

so I am trying to do my homework, this being the question:
Write a program that prompts the user to read two integers and displays their sum. If anything but an integer is passed as input, your program should catch the InputMismatchException that is thrown and prompt the user to input another number by printing "Please enter an integer."
Below is the sample run and what I am supposed to test.
SAMPLE RUN #1: java InputMismatch
Enter an integer: 2.5↵
Please enter an integer↵
Enter an integer: 4.6↵
Please enter an integer↵
Enter an integer: hello!↵
Please enter an integer↵
Enter an integer:7↵
Enter an integer:5.6↵
Please enter an integer↵
Enter an integer:9.4↵
Please enter an integer ↵
Enter an integer:10↵
17↵
When I am testing my code and putting in the integers, it works as it is supposed to, however, I am stuck on getting the integers to add together when both inputs are entered correctly. What am I doing wrong?
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
try adding another condition to your while and putting the numbers in an array.
int[] numbers = new int[2];
and change this in your while loop:
int count = 0;
while (!isValid && count <2) {
try {
System.out.print("Enter an integer: ");
numbers[count] = input.nextInt();
count++;
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
Hope that helped.
Check with this approach:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
numArray[count] = number;
count++;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
int num1 = numArray[0];
int num2 = numArray[1];
System.out.println((num1 + num2));
}
You need to stitch together the logic. As you are taking 2 numbers 2 flags will ensure you got correct input for both variables. Also both flags ensure you are taking input correctly for num1 or num2 when an exception occurs.
If you need to input n arbitrary integers, then you may want to use dynamic collections and add numbers to collection.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean num1Valid = false;
boolean num2Valid = false;
while (num1Valid==false || num2Valid==false) {
try {
if(num1Valid == false) {
System.out.print("Enter an integer for num1: ");
num1 = input.nextInt();
System.out.println("The number entered for num1 is " + num1);
num1Valid = true;
}
if(num2Valid == false) {
System.out.print("Enter an integer for num2: ");
num2 = input.nextInt();
System.out.println("The number entered for num2 is " + num2);
num2Valid = true;
}
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
input.close()
System.out.println((num1 + num2));
}
You need capture the exception, in this case you can using e.getMessage()
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1=0, number=0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
number = input.nextInt();
if(number > 0) {
System.out.println("The number entered is " + number);
}
num1 += number;
System.out.println("are would you like continue the program? Y or
N ");
String condition = input.next();
if(condition.equalsIgnoreCase("Y")) {
isValid = false;
} else {
isValid = true;
}
}
catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
System.out.println("You cannot type words");
isValid = true;
}
}
System.out.println("Result = " + num1);
input.close();
}
}
in another case do you can use the method matches using expression language
saw example below:
if(valor.matches("[0-9]*"))
You can add the two numbers inside the try block
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
num1 = input.nextInt();
System.out.print("Enter an integer: ");
num2 = input.nextInt();
System.out.println("The numbers you entered are " + num1 + ","+num2);
int sum = num1+num2;
System.out.println("The sum Of the numbers you entered is: "+ sum);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer:");
int number = input.nextInt();
numArray[count] = number;
count++;
} catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
input.nextLine();
}
}
System.out.println(numArray[0] + numArray[1]);
}
}

How to validate these inputs?

I wrote a simple program.it gets two Integer number from user and return odd numbers to user.i validate them to force the user to type just Integer numbers.
when user type other data type,program gives him my custom error.that is right up to now but when this happen user has to type inputs from the beginning.it means that program takes the user to the first home.
here is my main class :
package train;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean isNumber;
do {
System.out.println("enter number1 please : ");
if (input.hasNextInt()) {
number1 = input.nextInt();
isNumber = true;
System.out.println("enter number2 please : ");
}
if (input.hasNextInt()) {
number2 = input.nextInt();
isNumber = true;
} else {
System.out.println("wrong number!");
isNumber = false;
input.next();
}
} while (!(isNumber));
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
}
and here is my calculate class which return odd numbers :
public class Calculate {
private int minNumber;
private int MaxNumber;
public void setNumbers(int min, int max) {
this.minNumber = min;
this.MaxNumber = max;
}
public void result() {
int count = 0; // number of results
ArrayList<Integer> oddNumber = new ArrayList<Integer>(); // array of odd numbers
// get odd numbers
for (int i = minNumber; i < MaxNumber; i++) {
if ((i % 2) != 0) {
oddNumber.add(i);
count++;
}
}
int i = 0;// counter for printing array
while (i < oddNumber.size()) {
if(i != oddNumber.size()){
System.out.print(oddNumber.get(i) + ",");
}else{
System.out.println(oddNumber.get(i));
}
i++;
}
// print result numbers
System.out.println("\nResult number : " + count);
// print number range
System.out.println("You wanted us to search between " + minNumber
+ " and " + MaxNumber);
}
}
Create a method verifyAndGetNumber which will verify a number with regex \d+ which means match one or more digit. Throw Exception if it is not number. Catch the exception and print your custom message.
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean isNumber = false;
do {
try {
System.out.println("enter number1 please : ");
if (input.hasNextLine()) {
number1 = verifyAndGetNumber(input.nextLine());
}
System.out.println("enter number2 please : ");
if (input.hasNextLine()) {
number2 = verifyAndGetNumber(input.nextLine());
}
isNumber = true;
} catch (Exception e) {
System.out.println(e.getMessage());
}
} while (!isNumber);
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
private static int verifyAndGetNumber(String line) throws Exception {
if (line.matches("\\d+")) {
return Integer.parseInt(line);
}
throw new Exception("wrong number!");
}
You can count the number of Integer inputs entered by the user and that way you can solve the problem.
So you can modify the code as:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean isNumber;
int totalEnteredNumbers=0;
int currNumber=1;
do {
System.out.println("enter number"+currNumber+" please : ");
if (totalEnteredNumbers==0 && input.hasNextInt()) {
number1 = input.nextInt();
isNumber = true;
currNumber++;
System.out.println("enter number"+currNumber+" please : ");
totalEnteredNumbers++;
}
if (totalEnteredNumbers==1 && input.hasNextInt()) {
number2 = input.nextInt();
isNumber = true;
} else {
System.out.println("wrong number!");
isNumber = false;
input.next();
}
} while (!(isNumber));
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
}
Anyways here you can also remove the boolean variable isNumber from termination condition by replacing it with while(totalEnteredNumbers<2);.
However this can also be solved with the following code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean numberTaken=false;
while(!numberTaken)
{
System.out.print("Enter number1 : ");
String ip=input.next();
try
{
number1=Integer.parseInt(ip); //If it is not valid number, It will throw an Exception
numberTaken=true;
}
catch(Exception e)
{
System.out.println("Wrong Number!");
}
}
numberTaken=false; //For second input
while(!numberTaken)
{
System.out.print("Enter number2 : ");
String ip=input.next();
try
{
number2=Integer.parseInt(ip); //If it is not valid number, It will throw an Exception
numberTaken=true;
}
catch(Exception e)
{
System.out.println("Wrong Number!");
}
}
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
}

First do-while loop not functioning properly

There seems to be something with my code. My code detects non-integers and keep asking the user to input a positive #, but when you insert a negative #, it just ask the user to input a positive just once. What is wrong? Something with my do-while loop for sure.
I'm just focusing on the firstN, then I could do the secondN.
import java.util.Scanner;
public class scratch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int firstN = 0;
int secondN = 0;
boolean isNumber = false;
boolean isNumPos = false;
System.out.print("Enter a positive integer: ");
do {
if (input.hasNextInt()) {
firstN = input.nextInt();
isNumber = true;
}
if (firstN > 0) {
isNumPos = true;
isNumber = true;
break;
} else {
isNumPos = false;
isNumber = false;
System.out.print("Please enter a positive integer: ");
input.next();
continue;
}
} while (!(isNumber) || !(isNumPos));
System.out.print("Enter another positive integer: ");
do {
if (input.hasNextInt()) {
secondN = input.nextInt();
isNumber = true;
}
if (secondN > 0) {
isNumPos = true;
isNumber = true;
} else {
isNumPos = false;
isNumber = false;
System.out.print("Please enter a positive integer: ");
input.next();
}
} while (!(isNumber) || !(isNumPos));
System.out.println("The GCD of " + firstN + " and " + secondN + " is " + gCd(firstN, secondN));
}
public static int gCd(int firstN, int secondN) {
if (secondN == 0) {
return firstN;
} else
return gCd(secondN, firstN % secondN);
}
}
You read the input twice in such case:
firstN = input.nextInt();
...
input.next ();
Add some indication variable or reorganize the code so when you read via first read, avoid the second one.
Try this piece of code
while (true){
System.out.println("Please enter Positive number");
boolean hasNextInt = scanner.hasNextInt();
if(hasNextInt){
int firstNum = scanner.nextInt();
if(firstNum>0){
break;
}else{
continue;
}
}else{
scanner.next();
continue;
}
}

Entering string instead of integer (Java)

I am an absolute beginner, no experience in any programming language.
I wrote a program as an exercise for converting Arabic numbers to Roman numbers. It works. However I want to add a part for dealing with problem if a string is entered instead of integer. And don't know how to do this. I tried to use try/catch, but I don't know how to use it correctly. Now the program asks me twice to enter a number. What to do?
Here is he main method:
public static void main(String[] args) {
int numArabic;
boolean validEntry;
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
} catch (InputMismatchException e) {
System.out.println("Entered value is not an integer!");
}
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
if ((numArabic < 1) || (numArabic > 3999)) {
System.out.println();
System.out.print("Wrong number. ");
System.out.print("Enter an integer number between 1 and 3999!");
System.out.println();
}
else {
String numRoman1 = toRomanOne(numArabic % 10);
String numRoman2 = toRomanTwo(((numArabic / 10) % 10));
String numRoman3 = toRomanThree(((numArabic / 100) % 10));
String numRoman4 = toRomanFour(numArabic / 1000);
System.out.print("The number " + numArabic + " is equal to: ");
System.out.print(numRoman4+numRoman3+numRoman2+numRoman1 + ".");
}
}
Your control mechanism is true but only works once. You have to put it inside a loop so that it can allow user to enter an integer at last.
boolean validEntry;
do {
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
}
catch (InputMismatchException e) {
validEntry = false;
System.out.println("Entered value is not an integer!");
}
}
while(!validEntry);
You can use Scanner#hasNextInt() method to check that.
This method returns true if the next token in this scanner's input can be interpreted as an int value.
if (scan.hasNextInt()) {
// Do the process with Integer.
} else {
// Do the process if it is not an Integer.
}
Note that, this will cover all the Inputs which are not Integer, not only String.
public static void main(String[] args) {
int numArabic;
boolean validEntry = false;
while (validEntry = false){
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
}
catch (InputMismatchException e) {
System.out.println("Entered value is not an integer!");
validEntry = false;
}
}
if ((numArabic < 1) || (numArabic > 3999)) {
System.out.println();
System.out.print("Wrong number. ");
System.out.print("Enter an integer number between 1 and 3999!");
System.out.println();
}
else {
String numRoman1 = toRomanOne(numArabic % 10);
String numRoman2 = toRomanTwo(((numArabic / 10) % 10));
String numRoman3 = toRomanThree(((numArabic / 100) % 10));
String numRoman4 = toRomanFour(numArabic / 1000);
System.out.print("The number " + numArabic + " is equal to: ");
System.out.print(numRoman4+numRoman3+numRoman2+numRoman1 + ".");
}
}
Try This :
boolean b=true;
while(b)
{
try
{
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
}
catch (InputMismatchException e)
{
System.out.println("Entered value is not an integer!");
}
if(validEntry)
{
if ((numArabic < 1) || (numArabic > 3999))
{
System.out.println();
System.out.print("Wrong number. ");
System.out.print("Enter an integer number between 1 and 3999!");
System.out.println();
}
else
{
String numRoman1 = toRomanOne(numArabic % 10);
String numRoman2 = toRomanTwo(((numArabic / 10) % 10));
String numRoman3 = toRomanThree(((numArabic / 100) % 10));
String numRoman4 = toRomanFour(numArabic / 1000);
System.out.print("The number " + numArabic + " is equal to: ");
System.out.print(numRoman4+numRoman3+numRoman2+numRoman1 + ".");
}
b=false;
}//end of if
}//end of while
Try this,
you need to initialize numArabic to some value first.
public static void main(String[] args) {
int numArabic = 0;
boolean validEntry;
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
}
catch (InputMismatchException e) {
System.out.println("Entered value is not an integer!");
}
if ((numArabic < 1) || (numArabic > 3999)) {
} else {
}
}
The Program what you entered is free from syntax errors and logical errors.But for asking only one time to enter the integer value just rewrite the code as following.We are attaching second sop function in catch block.So if the input is mismatch it will ask for again re-enter.
public static void main(String[] args) {
int numArabic;
boolean validEntry;
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
} catch (InputMismatchException e) {
System.out.println("Entered value is not an integer!");
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
}

Java data validation with while loops

This applicaiton validates that the user is entering the correct data. I have about 95% of this done but I can not figure out the Continue? (y/n) part. If you hit anything but y or n (or if you leave the line blank) it is supposed to print an error:So this is what the application is supposed to look like in the console:
Continue? (y/n):
Error! This entry is required. Try again.
Continue? (y/n): x
Error! Entry must be 'y' or 'n'. Try again.
Continue? (y/n): n
Here is my code:
public static void main(String[] args) {
System.out.println("Welcome to the Loan Calculator");
System.out.println();
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, 1000000);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
double monthlyInterestRate = interestRate/12/100;
int months = years * 12;
double monthlyPayment = calculateMonthlyPayment(loanAmount, monthlyInterestRate, months);
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMinimumFractionDigits(1);
String results = "Loan amount: \t\t" + currency.format(loanAmount) + "\n"
+ "Yearly interest rate: \t" + percent.format(interestRate/100) + "\n"
+ "Number of years: \t" + years + "\n"
+ "Monthly payment: \t" + currency.format(monthlyPayment) + "\n";
System.out.println();
System.out.println("FORMATTED RESULTS");
System.out.println(results);
String getContinue = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
System.out.print(getContinue);
System.out.println();
}
}
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 than " + min + ".");
}
else if (d >= max) {
System.out.println("Error! Number must be less than " + max + ".");
}
else {
isValid = true;
}
}
return d;
}
public static double getDouble(Scanner sc, String prompt)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid decimal value. Try Again.");
}
sc.nextLine();
}
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 greater than " + min + ".");
}
else if (i >= max) {
System.out.println("Error! Number must be less than " + max + ".");
}
else {
isValid = true;
}
}
return i;
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if(sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine();
}
return i;
}
public static double calculateMonthlyPayment(double loanAmount, double monthlyInterestRate, double months)
{
double monthlyPayment = 0;
for (int i = 1; i <= months; i++)
{
monthlyPayment = loanAmount * monthlyInterestRate/(1 - 1/Math.pow(1 + monthlyInterestRate, months));
}
return monthlyPayment;
}
System.out.print(getContinue);
System.out.println();
public static String getContinueWithinRange(Scanner sc, String prompt, String yContinue, String nContinue)
{
String i = "";
boolean isValid = false;
while (isValid == false)
{
i = getContinue(sc, prompt);
if (!yContinue.equalsIgnoreCase("") && !nContinue.equalsIgnoreCase("")){
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}
else{
isValid = true;
}
}
return i;
}
public static String getContinue(Scanner sc, String prompt)
{
String i = "";
boolean isValid = false;
while(isValid == false)
{
System.out.print(prompt);
if (i.length() > 0)
{
i = sc.nextLine();
isValid = true;
}
else
{
System.out.println("Error! Entry is required. Try again.");
}
sc.nextLine();
}
return i;
}
}
Change the content of the while loop in getContinue() to this:
System.out.print(prompt);
i = sc.nextLine();
if (i.length() > 0)
{
isValid = true;
}
else
{
System.out.println("Error! Entry is required. Try again.");
}
This first prints the prompt, then reads the input into the variable that will be returned, then checks whether the input had length greater than zero.
In getContinueWithinRange(), the condition in the if clause needs to be replaced by
!yContinue.equalsIgnoreCase(i) && !nContinue.equalsIgnoreCase(i)
This will "y" and "n" against the input instead of against "".
Also if you would like to actually continue after reading a "y", you need to do something like this:
if (!yContinue.equalsIgnoreCase(i) && !nContinue.equalsIgnoreCase(i)){
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}
else {
isValid = true;
}
The first case catches invalid input, the second ends the loop if the user entered "n", the third tells the user the loop will continue after he entered a "y".
Finally, to make your program do what it's supposed to do, change
String getContinue = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
to
choice = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
in your main method.
I try something for you according to your first submitted code
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class Tester4 {
public static String getContinueWithinRange(Scanner sc, String prompt, String yContinue, String nContinue) {
String result = "";
boolean isValid = false;
boolean isStarted = false;
while(!isValid) {
result = getContinue(sc, prompt, isStarted);
isStarted = true;
if(yContinue.equalsIgnoreCase(result) || nContinue.equalsIgnoreCase(result)) {
isValid = true;
} else if(!yContinue.equalsIgnoreCase(result) || !nContinue.equalsIgnoreCase(result)) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
} else {
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}
}
return result;
}
public static String getContinue(Scanner sc, String prompt, boolean isStarted) {
String result = "";
boolean isValid = false;
while(!isValid) {
if(result.isEmpty() && !isStarted) {
System.out.print(prompt);
System.out.println("Error! Entry is required. Try again.");
}
result = sc.nextLine();
if(result.length() > 0) {
isValid = true;
}
}
return result;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String getContinue = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
// to call the method
System.out.print(getContinue);
System.out.println();
}
// InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg");
// BufferedImage bufferedImage=ImageIO.read(stream);
// ImageIcon icon= new ImageIcon(bufferedImage);
}
import java.util.*;
import java.text.*;
public class LoanPaymentApp {
public static void main(String[] args)
{
System.out.println("Welcome to the Loan Calculator");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0, 1000000);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
double monthlyInterestRate = interestRate/12/100;
int months = years * 12;
double monthlyPayment = calculateMonthlyPayment(loanAmount, monthlyInterestRate, months);
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMinimumFractionDigits(1);
String results = "Loan amount: \t\t" + currency.format(loanAmount) + "\n"
+ "Yearly interest rate: \t" + percent.format(interestRate/100) + "\n"
+ "Number of years: \t" + years + "\n"
+ "Monthly payment: \t" + currency.format(monthlyPayment) + "\n";
System.out.println();
System.out.println("FORMATTED RESULTS");
System.out.println(results);
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n"))
{
if (choice.equals(""))
{
System.out.println("Error! This entry is required. Try again.");
System.out.print("Continue? (y/n): ");
}
else
{
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
System.out.print("Continue? (y/n): ");
}
choice = sc.nextLine();
}
}
}
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 than " + min + ".");
}
else if (d >= max) {
System.out.println("Error! Number must be less than " + max + ".");
}
else {
isValid = true;
}
}
return d;
}
public static double getDouble(Scanner sc, String prompt)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid decimal value. Try Again.");
}
sc.nextLine();
}
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 greater than " + min + ".");
}
else if (i >= max) {
System.out.println("Error! Number must be less than " + max + ".");
}
else {
isValid = true;
}
}
return i;
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if(sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine();
}
return i;
}
public static double calculateMonthlyPayment(double loanAmount, double monthlyInterestRate, double months)
{
double monthlyPayment = 0;
for (int i = 1; i <= months; i++)
{
monthlyPayment = loanAmount * monthlyInterestRate/(1 - 1/Math.pow(1 + monthlyInterestRate, months));
}
return monthlyPayment;
}
}

Categories

Resources