Java User input Validation - java

I am trying to figure out how to validate the input of a user. I want the user to enter a double but if the user enters a string I want the question repeated until a double is entered. Iv'e searched but I couldn't find anything. Below is my code so far any help is appreciated. I have to use a do while loop I am stuck on what to put in the while loop to make sure the input is a double and not a string.
public class FarenheitToCelsius {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double fahrenheit, celsius;
Scanner in = new Scanner(System.in);
do{
System.out.printf("Enter a fahrenheit degree: ");
fahrenheit = in.nextDouble();
}
while();
celsius = ((fahrenheit - 32)*5)/9;
System.out.println("Celsius value of Fahrenheit value " + fahrenheit + " is " + celsius);

One trick you can use here is to read the entire user input as a string, which would allow any type of input (string, double, or anything else). Then, use Double#parseDouble() to try to convert that input to a bona-fide double value. Should an exception occur, allow the loop to continue, otherwise, end the loop and continue with the rest of your program.
Scanner in = new Scanner(System.in);
boolean isValid;
do {
System.out.printf("Enter a fahrenheit degree: ");
isValid = false;
String input = in.nextLine();
try {
fahrenheit = Double.parseDouble(input);
isValid = true;
}
catch (Exception e) {
// do something
}
} while(!isValid);
celsius = ((fahrenheit - 32) * 5) / 9;

Related

How to create a helper method that takes 2 double inputs into a class global array?

I'm new to java and I have a question about an assignment I have. I've written a bunch of methods that are different formulas, like the duration of a storm. The assignment asks me to write two helper methods to get input from the user. One of them is called get_S_Input() and I was able to implement it correctly I think. But the one I'm stuck on is this other helper method called get_2_Invals(). It wants me to prompt the user with my parameter, and read in 2 double values. It wants me to record the values in a class global array of doubles and then exit the method, but I don't know how to do this. I want to put it in the else statement in the method below. Here is my code so far...
import java.lang.Math;
import java.util.Scanner;
public class FunFormulas {
public void sd(){
double durationOfStorm = Math.sqrt(((Math.pow(get_S_Input("Enter the diameter of storm in miles:"), 3) / 216)));
if (durationOfStorm > 0)
System.out.println("The storm will last: " + durationOfStorm);
}
public void sl(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of seconds since the lightning strike:");
double secondsSinceLightning = Double.valueOf(scanner.nextLine());
double distanceFromLightning = (1100 * secondsSinceLightning);
System.out.println(distanceFromLightning);
}
public void si(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the edge of cube in inches:");
double edgeOfCubeInInches = Double.valueOf(scanner.nextLine());
if (edgeOfCubeInInches < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double weightOfCube = (0.33 * (Math.pow(edgeOfCubeInInches, 3)));
System.out.println(weightOfCube);
}
public void dt(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the time in hours:");
double timeInHours = Double.valueOf(scanner.nextLine());
if (timeInHours < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
System.out.println("Enter the rate of speed in mph:");
double rateOfSpeed = Double.valueOf(scanner.nextLine());
if (rateOfSpeed < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double distanceTravelled = (rateOfSpeed * timeInHours);
System.out.println(distanceTravelled);
}
public void sa(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your weight in pounds:");
double weight = Double.valueOf(scanner.nextLine());
weight = weight * 0.4536;
System.out.println("Enter your height in inches:");
double height = Double.valueOf(scanner.nextLine());
height = height * 2.54;
double BSA = ((Math.sqrt(weight * height)) / 60);
System.out.println(BSA);
}
public double get_S_Input(String promptStr){
//Scanner helper method
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double value = Double.valueOf(scanner.nextLine());
if (value < 0 ){
System.out.println("ERROR: please enter a non-negative number!!!");
}
return value;
}
public void get_2_Invals(String promptStr){
/*Prompt the user with the promptStr passed in as a parameter
ii. Read in the first double precision value entered by the user with the Scanner
iii. Read in the second double precision value entered by the user with the Scanner
iv. Check to make sure the values entered by the user are non-negative
a. If either number entered by the user is negative, the method should print out an
error message, and return to step i. above.
b. If the number is non-negative (that is greater than or equal to zero) the method
should record the numbers obtained from the user in a class-global array of
doubles and exit.*/
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double firstValue = scanner.nextInt();
double secondValue = scanner.nextInt();
if (firstValue < 0 || secondValue < 0)
System.out.println("ERROR: please enter non-negative number!");
else
}
public static void main(String [] args){
FunFormulas fun = new FunFormulas();
fun.sd();
}
}

How to combine two simple programs into one

How can I combine two small programs I created?
They are conversions of Farenheit to Celsius and vice versus. When I join the two together, I clearly have double/repeating variables. Not quite sure how/what to change.
The goal is to combine the two programs so it will ask the user to choose one, (F or C) and then direct the user to input an integer to convert. Not sure if I need to create these as two objects of my class? Or how to direct a choice, maybe using Switch?
Below is one conversion used, the formula is the same just inverse.
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a degree in Fahrenheit: ");
double fahrenheit = input.nextDouble();
double celsius =(5.0 / 9) * (fahrenheit - 32);
System.out.println("Fahrenheit " + fahrenheit + " is " + celsius + " in Celsius") ;
}
}
I think you are right that we can simplify the code using a single switch statement - or even an if statement in this case.
Try maybe this:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String convertFrom = userInput.nextLine();
double C, F, convertedDegrees;
if (convertFrom.equals("F")) {
// Convert Fahrenheit to Celsius
} else if (convertFrom.equals("C")) {
// Convert Celsius to Fahrenheit
convertedDegrees = userInput.nextDouble();
F = (convertedDegrees * 1.8) + 32;
System.out.println(F);
} else {
System.out.println("Invalid input. Please type 'C' or 'F' to indicate whether you wish to convert Celsius or Fahrenheit degrees.");
}
}

Using method to call for a y/n answer

I have this code. The askToContinue() method is being called to ask the user if they would like to continue but my problem is it just ignores the choice and starts the program again no matter what I enter. What am I missing in the code that is causing it to ignore my choice?
public class FutureValueApp {
public static void main(String[] args) {
System.out.println("Welcome to the Future Value Calculator\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
System.out.println();
// calculate the future value
double monthlyInterestRate = interestRate / 12 / 100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// print the results
System.out.println("FORMATTED RESULTS");
printFormattedResults(monthlyInvestment,
interestRate, years, futureValue);
System.out.println();
askToContinue(sc);
}
}
private static void printFormattedResults(double monthlyInvestment,
double interestRate, int years, double futureValue){
// get the currency and percent formatters
NumberFormat c = NumberFormat.getCurrencyInstance();
NumberFormat p = NumberFormat.getPercentInstance();
p.setMinimumFractionDigits(1);
// format the result as a single string
String results
= "Monthly investment: " + c.format(monthlyInvestment) + "\n"
+ "Yearly interest rate: " + p.format(interestRate / 100) + "\n"
+ "Number of years: " + years + "\n"
+ "Future value: " + c.format(futureValue) + "\n";
System.out.println(results);
}
public static String askToContinue(Scanner sc){
// see if the user wants to conti1nue
System.out.print("Continue? (y/n): ");
String choice = sc.next();
System.out.println();
return choice;
}
You're on the right track. Change this
askToContinue(sc);
to
choice = askToContinue(sc);
Because you need to assign the value returned from askToContinue to the local reference named choice.
You are not assigning the result of askToContinue to the choice variable which is checked in the loop.
Possibly the confusion is the choice variable inside the askToContinue method. Note, this is a different variable and does not affect the choice variable checked in the while statement.
When you define a variable inside a method, it is not recognized by the code outside of your method, even if it has the same name. So, in your code for example, you have,
public static String askToContinue(Scanner sc){
// see if the user wants to conti1nue
System.out.print("Continue? (y/n): ");
String choice = sc.next(); // this choice variable exists only for the
// askToContinue method
// Once you assign it over here and return it
// with the code below, you should use the returned
// value to update the variable choice, which is
// defined outside your askToContinue method
System.out.println();
return choice;
}
So, as the other answers have pointed out, if you do,
choice = askToContinue(sc);
then the code will run fine since the choice variable defined in the main method will get updated according to the value you input
Based on
John Camerin's answer,to skip double assigning in your code, you can make your choice variable as global static variable by define it in your class :
public class FutureValueApp {
public static String choice;
}
Or send it as second parameter in your method :
askToContinue(sc,choice);

Trying to combine multiple programs together

I am trying to take 3 different programs I have created and put them under a single class. My professor has stated I must do this and I have no clue on how to. I am not looking for a hand out here, just some how I can do this quickly and efficiently. I am also trying to figure out how to call from the same scanner for each program or if I should just make multiple ones.
import java.util.Scanner;
public class AssignmentOneFahrenheit {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello, I can convert Fahrenheit to Celsius!");
System.out.println("Please enter the degrees Fahrenheit you want converted.");
double degreesF;
double degreesC;
Scanner keyboard = new Scanner(System.in);
degreesF = keyboard.nextDouble(); //Allows user to input decimal number
keyboard.close();
System.out.println("The temperature in Degrees Celsius is: ");
degreesC = 5*(degreesF - 32)/9;
System.out.printf("%.2f", degreesC);
}
import java.util.Scanner;
public class AssignmentOneHate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a line containing 'hate'.");
String text = keyboard.nextLine();
System.out.println("I have changed that line to read: ");
System.out.println(text.replaceFirst("hate", "love"));
keyboard.close();
}
import java.util.Scanner;
public class AssignmentOneVerticalDisplay {
public static void main(String[] args) {
// TODO Auto-generated method stub
int userInput;
System.out.println("Please enter a 4 digit integer.");
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
System.out.println(userInput / 1000);
userInput = userInput % 1000;
System.out.println(userInput / 100);
userInput = userInput % 100;
System.out.println(userInput / 10);
System.out.println(userInput % 10);
keyboard.close();
}
}
I basically just copied and pasted 2 programs I created. If anybody can help guide me in the correct direction here that would be great.
You can use the Double.parseDouble(String string); function together with a try-Catch to check if it was a number or a string in the input.
(...)
String text = keyboard.nextLine();
try {
//We try and assume that it is a number
Double number = Double.parseDouble(text);
/**
* Do stuff with the number like in the 1st program
*/
}
catch (NumberFormatException e)
{
//The input turned out not to be a number.
/**
* Do stuff here with the string like the 2nd program
*/
}
Am not really certain what your trying to accomplish, but if it's really necessary you combine all three classes together try using Java Inner Classes
I think that your professor is looking for a more object oriented solution. You can create a class that contains the three programs as separated methods like this
import java.util.scanner;
public class AssignmentScanner {
public double convertToCelsius() {
Scanner keyboard = new Scanner(System.in);
double degreesF = keyboard.nextDouble();
keyboard.close();
return 5*(degreesF - 32)/9;
}
public String replaceHate() {
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
String replacedText = text.replaceFirst("hate", "love");
keyboard.close();
return replacedText;
}
public int oneVerticalDisplay() {
Scanner keyboard = new Scanner(System.in);
int userInput = keyboard.nextInt();
System.out.println(userInput / 1000);
userInput = userInput % 1000;
System.out.println(userInput / 100);
userInput = userInput % 100;
System.out.println(userInput / 10);
System.out.println(userInput % 10);
keyboard.close();
}
}
You still need to create a main program that use this object like this:
public class AssignmentMain {
public static void main(String[] args) {
AssignmentScanner assignmentScanner = new AssignmentScanner();
System.out.println("Hello, I can convert Fahrenheit to Celsius!");
System.out.println("Please enter the degrees Fahrenheit you want converted.");
double degreesC = assignmentScanner.convertToCelsius();
System.out.println("The temperature in Degrees Celsius is: ");
System.out.printf("%.2f", degreesC);
System.out.println("Please enter a line containing 'hate'.");
String replacedText = assignmentScanner.replaceHate();
System.out.println("I have changed that line to read: ");
System.out.println(replacedText);
System.out.println("Please enter a 4 digit integer.");
assigmentScanner.oneVerticalDisplay();
}
}
This way your main program only knows about the AssignmentScanner and its three methods. This make the main program easier to read and maintain. There is still room for improvement but i think it's OK for a first approach.

Am I doing something wrong with my try-catch block?

So we have to make a mortgage calculation project where we have to ask the user to calculate again and now we have to make it so it prints out a error message every time the user enters a string value for any of the inputs. I thought I did it right but something strange happens every time I run it and I can't figure out why and I know it's something wrong with the Try-Catch blocks.
Here are my outputs: http://imgur.com/cbvwM5v
As you can see the third time i run the program I enter a "two" as the second input and it still did the calculations. Then, the third time I tried it, I entered a negative number then a "two" and everything worked the way I wanted it to. Then, the last time I ran it I put a positive number for the first input and it still did the calculations, anything you guys see that might be doing this? Also, I think I may have used the wrong exception, I'm not uite sure what it means, I just guessed. am I supposed to user NumberFormatException and there is also a line under nfe saying that the value is not being used.
Here's my code:
package MortgageCalculation2c;
import java.text.NumberFormat;
import java.util.Scanner;
/**
*
* #author Akira
*/
public class MortgageCalculation2c {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double loanAmount = 0;
double interestRate = 0;
double numberYears = 0;
double months;
double monthlyPayment;
double numerator;
double denominator;
double formula;
boolean userInput = true;
String answer = ("y");
while (userInput) {
try {
loanAmount = 0;
interestRate = 0;
numberYears = 0;
//prompt user for the loan amount
System.out.print("Enter the loan amount: ");
loanAmount = Double.parseDouble(in.nextLine());
//prompt the user for the interest rate
System.out.print("Enter the rate: ");
interestRate = Double.parseDouble(in.nextLine());
//prompt the user for thenumber of years
System.out.print("Enter the number of years: ");
numberYears = Double.parseDouble(in.nextLine());
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
}
//if the user enters a negative number print out a error message, if not, continue calculations
if ((loanAmount <= 0) || (interestRate <= 0) || (numberYears <= 0)) {
System.out.println("ALL NUMERICAL VALUES MUST BE POSITIVE!");
} else {
//convert the interest rate
interestRate = interestRate / 100 / 12;
//the number of years must be converted to months
months = numberYears * 12;
//numerator of the monthly payment formula
numerator = (Math.pow(1 + interestRate, months));
//denominator of the monthly payment formula
denominator = ((numerator)-1);
//the formula equals the numerator divided by the denominator
formula = ( numerator / denominator );
//monthly payment calculation
monthlyPayment = (interestRate * loanAmount * formula);
//sytem output
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
System.out.println("The monthly payment is: " + defaultFormat.format(monthlyPayment));
}
//prompt the user if they would like to calculate the program again.
System.out.println("Would you like to calculate again (y/n) : ");
//if the user enters "y" the program will run again and if the user enters anything else it ends
answer = in.nextLine();
answer = answer.toLowerCase();
if ( answer.equals("y")){
userInput = true; //tests the program if it needs to run again
}else{
break; //ends the program
}
}
}
}
Is there anything that you guys can see that might be the problem?
It seems you need continue in your catch block, so the program flow goes back to the loop.
...
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
continue; // <---------- here
}
...
If this is not a specific exercise in try-catch construct, it be would be better to use Scanner's method hasNextDouble() for validatiing and nextDouble for reading and converting the numbers.
It will look something like this:
//prompt user for the loan amount
loanAmount = enterPositiveDouble("Enter the loan amount: ")
//prompt the user for the interest rate
interestRate = enterPositiveDouble("Enter the rate: ");
//prompt the user for the number of years
numberYears = enterPositiveDouble("Enter the number of years: ");
and you will have a special static method enterPositiveDouble like following:
static void enterPositiveDouble(String prompt) {
Scanner in = new Scanner(System.in);
boolean ok = true;
double result = -1;
do {
System.out.print(prompt);
ok = (in.HasNextDouble() && (result = in.NextDouble()) > 0)
if ! ok
System.out.println("You must enter positive numerical data!");
} while (!ok);
}
The above is not an optimal code but just the illustration of a possible solution.

Categories