Exception Handling for no user input in Java - java

I am trying to get my program to exception handle for if the user inputs nothing so they will get an error message of "Error, enter a dollar amount greater than 0" or "Error, Enter a 1, 2 or 3". As of now, the program does nothing if the user just hits "enter" with no input....
import java.util.Scanner;
import java.util.*;
import java.text.DecimalFormat;
public class Candleline
{
public static void main(String[] args)
{
//initiate scanner
Scanner input = new Scanner(System.in);
System.out.println("\tCandleLine - Candles Online");
System.out.println(" ");
//declare variables and call methods
double candleCost = getCandleCost();
int shippingType = getShippingType();
double shippingCost = getShippingCost(candleCost, shippingType);
output(candleCost, shippingCost);
}
public static double getCandleCost()
{
//get candle cost and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
double candleCost = 0;
while(!done)
{
System.out.print("Enter the cost of the candle order: ");
try
{
inputCost = input.next();
candleCost = Double.parseDouble(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (candleCost <=0) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
}
return candleCost;
}
public static int getShippingType()
{
//get shipping type and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
int shippingCost = 0;
while(!done)
{
System.out.println(" ");
System.out.print("Enter the type of shipping: \n\t1) Priority(Overnight) \n\t2) Express (2 business days) \n\t3) Standard (3 to 7 business days) \nEnter type number: ");
try
{
inputCost = input.next();
shippingCost = Integer.parseInt(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (shippingCost <=0 || shippingCost >= 4) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println(" ");
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
}
return shippingCost;
}
public static double getShippingCost(double candleCost, int shippingType)
{
//calculate shipping costs
double shippingCost = 0;
if (shippingType == 1)
{
shippingCost = 16.95;
}
if (shippingType == 2)
{
shippingCost = 13.95;
}
if (shippingType == 3)
{
shippingCost = 7.95;
}
if (candleCost >= 100 && shippingType == 3)
{
shippingCost = 0;
}
return shippingCost;
}
public static void output(double fCandleCost, double fShippingCost)
{
//display the candle cost, shipping cost, and total
Scanner input = new Scanner(System.in);
DecimalFormat currency = new DecimalFormat("$#,###.00");
System.out.println("");
System.out.println("The candle cost of " + currency.format(fCandleCost) + " plus the shipping cost of " + currency.format(fShippingCost) + " equals " + currency.format(fCandleCost+fShippingCost));
}
}

Replace input.next();
with input.nextLine();

You can write a method that validates the input before proceeding. It can keep asking for inputs if user enters something that is not valid. E.g. below example demonstrates how to validate an integer input:
private static int getInput(){
System.out.print("Enter amount :");
Scanner scanner = new Scanner(System.in);
int amount;
while(true){
if(scanner.hasNextInt()){
amount = scanner.nextInt();
break;
}else{
System.out.println("Invalid amount, enter again.");
scanner.next();
}
}
scanner.close();
return amount;
}

Related

NoSuchElementException error for ATM Machine app (Modified)

I am currently learning Java and I am trying to retain the information I learned by building a ATM machine app (I plan on adding more to it in the future).
My current issue is I would like to ask a user 'What would you like to do' repeatedly until a valid input is provided(current valid inputs are 'Withdraw' and 'Deposit').
I have a loop that will repeatedly ask the user 'Please select a valid choice' if the input is not valid. If the input is valid it will execute only once, ask 'What would you like to do', and then display a NoSuchElementException. Not sure how to fix this.
Here is my code:
App.java
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("What woul you like to do?");
String response = scanner.next().toLowerCase();
Transactions newTransaction = new Transactions();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
} else if (response.equals("deposit")) {
newTransaction.Deposit();
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}
Transactions.java
import java.util.Scanner;
public class Transactions {
private int currentBalance = 100;
public void Withdrawal() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to withdraw?");
int withdrawAmount = scanner.nextInt();
if (withdrawAmount > 0) {
if (currentBalance > 0) {
currentBalance -= withdrawAmount;
System.out.println("Amount withdrawn: $" + withdrawAmount);
System.out.println("Current Balance: $" + Balance());
if (currentBalance < 0) {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println("Can't remove 0 from account");
}
scanner.close();
}
public void Deposit() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to deposit?");
int depositAmount = scanner.nextInt();
if (depositAmount > 0) {
currentBalance += depositAmount;
Balance();
}
System.out.println("Amount deposited: $" + depositAmount);
System.out.println("Current Balance: $" + Balance());
scanner.close();
}
public int Balance() {
return currentBalance;
}
}
Error Message
NoSuchElementException
You can use a sentinel. A sentinel is a value entered that will end the iteration.
//incomplete code showing logic
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice");
choice = input.nextInt();
while(choice != -1){ //-1 is the sentinel, can be value you choose
//Some logic you want to do
System.out.println("Enter choice or -1 to end");
choice = input.NextInt(); //notice we input choice again here
}
Like has been said you should learn about loops. There are two types while-loop and for-loop. In this case you should youse the while-loop.
The implementation of your problem could be this.
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("What woul you like to do?");
String response;
Transactions newTransaction = new Transactions();
while (true) {
response = scanner.next().toLowerCase();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
break;
} else if (response.equals("deposit")) {
newTransaction.Deposit();
break;
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}

How do I validate user input in Java

I wrote a bmi calculator program and I want to validate user input so that the user would not enter a negative number for the height or weight input.
How do I do this? I am new to Java, so I have no idea.
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) throws Exception {
calculateBMI();
}
private static void calculateBMI() throws Exception {
System.out.print("Please enter your weight in kg: ");
Scanner s = new Scanner(System.in);
float weight = s.nextFloat();
System.out.print("Please enter your height in cm: ");
float height = s.nextFloat();
float bmi = (100*100*weight)/(height*height);
System.out.println("Your BMI is: "+bmi);
printBMICategory(bmi);
s.close();
}
private static void printBMICategory(float bmi) {
if(bmi < 24) {
System.out.println("You are underweight");
}else if (bmi < 29) {
System.out.println("You are healthy");
}else if (bmi < 34) {
System.out.println("You are overweight");
}else {
System.out.println("You are OBESE");
}
}
}
you can keep asking for value until the user input a valid number
private float readZeroOrPositiveFloat(Scanner scanner , String promptMessage)
{
float value = -1;
while(value < 0){
System.out.println(promptMessage);
value = scanner.nextFloat();
}
return value;
}
private static void calculateBMI() throws Exception {
System.out.print("Please enter your weight in kg: ");
Scanner s = new Scanner(System.in);
float weight = readZeroOrPositiveFloat(s , "Please enter your weight in kg: ");
float height = readZeroOrPositiveFloat(s , "Please enter your height in cm: ");
float bmi = (100*100*weight)/(height*height);
System.out.println("Your BMI is: "+bmi);
printBMICategory(bmi);
s.close();
}
Just to handle negative inputs and keep asking for valid input,
boolean flag = true;
while(flag){
System.out.print("Please enter your weight in kg: ");
int weight = sc.nextInt();
System.out.print("Please enter your height in cm: ");
int height = sc.nextInt();
if(weight >= 0 && height >= 0){
float bmi = (100*100*weight)/(height*height);
flag = false;
}else{
System.out.println("Invalid Input");
}
}
To handle all the unexpected inputs and keep asking for valid input,
boolean flag = true;
while(flag){
Scanner sc = new Scanner(System.in);
try{
System.out.print("Please enter your weight in kg: ");
int weight = sc.nextInt();
System.out.print("Please enter your height in cm: ");
int height = sc.nextInt();
if(weight >= 0 && height >= 0){
float bmi = (100*100*weight)/(height*height);
flag = false;
}else{
System.out.println("Invalid Input");
}
}catch(Exception e){
System.out.println("Invalid Input");
}
}
When you get input from the scanner, you could use an if statement to make sure the value is not negative. For example:
if(input value <= 0){
System.out.println("Invalid Input");
}else { *program continues* }

Is it possible to return a user-input declared double within an if statement for use in the main?

I am wishing to prompt the user again if a double outside of the accepted range (0-100) is input, until the input is valid. When the input is considered valid, I am wanting to return correct input value, yet, returned instead is the first incorrect value. How can I return the correct input, as accepted by the if statement?? Many thanks!
public class examscore {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
double sumfin = finalscore(console);
System.out.println(sumfin); // if user input is initially invalid, but then corrected, the first, incorrect, value is printed
}
public static double finalscore (Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
while(!console.hasNextDouble()) { //prompts the user, if invalid input, to input again, until a valid value is input
System.out.println("Please input a mark between 0 and 100. ");
console.next();
}
double examscore = console.nextDouble();
if (examscore >=0 && examscore<= 100) {
System.out.println();
System.out.println("Exam Score = "+examscore);
} else {
System.out.println("Error:");
finalscore (console);
}
return examscore; //an attempt to return the VALID exam score: fails
}
}
A do-while loop would be a perfect fit. Example:
Scanner console = new Scanner(System.in);
double userInput = 0;
do {
System.out.println("Please input a mark between 0 and 100. ");
try {
userInput = console.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Your input could not be interpreted as a floating-point number.");
}
} while (userInput <= 0D || userInput >= 100D);
You missed to assign result of finalscore(console) to examscore inside the else block.
if (examscore >= 0 && examscore <= 100) {
System.out.println();
System.out.println("Exam Score = " + examscore);
} else {
System.out.println("Error:");
examscore = finalscore(console);
}
You can either use a loop or a recursive call to accomplish this. I prefer a recursive call:
private static double getValidScore(Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
try {
double score = Double.parseDouble(console.nextLine());
if (score >= 0 && score <= 100) {
return score;
}
} catch (NumberFormatException nfe) {}
System.out.println("Please input a mark between 0 and 100.");
return getValidScore(console);
}

if a user inputs a letter instead of a number tell them it's not a number

I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here

How to check if user input is String, double or long in Java

I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}

Categories