This is a method for the main class of this problem.
I have an issue when the user inputs a non-numeric value for the requested information.
Example)
Enter a distance in meters: jam
Incorrect value. Please select a distance in meters greater than zero.
Enter a distance in meters: Incorrect value. Please select a distance greater than zero.
Enter a distance in meters:
This is the output that occurs when this method is called. How do i correct this?
public static double validDistance (String prompt,
double minValue) {
Scanner keyboard = new Scanner (System.in);
double value;
String errorMessage = "Incorrect value. Please select a distance in "
+ "meters greater than zero\n";
// Protects distance input from incorrect value
// (non-numeric or too low)
do {
System.out.print(prompt);
if (keyboard.hasNextDouble()) {
value = keyboard.nextDouble();
if (value <= minValue) {
System.out.println(errorMessage);
} else {
break; // Exit loop
}
} else {
System.out.println(errorMessage);
keyboard.nextLine(); // Clears buffer
}
} while (true);
return value;
}
I realize this doesn't directly answer your question.
I personally find that dealing with the Scanner buffer is incredibly annoying, so I prefer just reading line by line and doing the processing myself. For example:
public static double validDistance(String prompt, double minValue)
{
Scanner keyboard = new Scanner(System.in);
String errorMessage = "Incorrect value. Please select a distance in meters greater than zero\n";
while (true) {
System.out.print(prompt);
String line = keyboard.nextLine();
try {
double result = Double.parseDouble(line);
if (result >= minValue) {
keyboard.close(); // You should always close a Scanner when you're done!
return result;
}
} catch (NumberFormatException e) {
}
System.out.println(errorMessage);
}
}
Related
This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 4 years ago.
How do I resolve the java.util.NoSuchElementException error? I call the scanner object 3 times, and the program will accept input the first two times. But on the third try, I immediately get the java.util.NoSuchElementException error. The name of the scanner object is stdInput.
I've tried creating a new scanner object just for the instance throwing this error, but I still get the same error, just from a different line in the code.
/**
* reddit url: https://www.reddit.com/r/dailyprogrammer/comments/pjbj8/easy_challenge_2/
*/
import java.util.Scanner;
public class challenge {
public static void main(String[] args) {
int choiceNum = 0;
boolean continueRunningProgram = true;
String repeatProgram = "";
Scanner stdInput = new Scanner (System.in);
do {
System.out.println("Are you solving for force (1), mass (2), or acceleration (3)?");
choiceNum = stdInput.nextInt();
if(isValidChoiceNum(choiceNum) == false) {
do {
System.out.println("The number " + choiceNum + " is an invalid choice. Please choose again.");
choiceNum = stdInput.nextInt();
} while(isValidChoiceNum(choiceNum) == false);
}
switch(choiceNum) {
case 1:
System.out.println("The force is " + solvingForForce());
break;
case 2:
System.out.println("The mass is " + solvingForMass());
break;
case 3:
System.out.println("The acceleration is " + solvingForAcceleration());
break;
}
System.out.println("Would you like to solve another problem involving force, mass, and acceleration (Y/N)?");
repeatProgram = stdInput.next();
if(isValidChoiceChar(repeatProgram) == false) {
do {
System.out.println("The letter " + repeatProgram + " is an invalid choice. Please choose again.");
repeatProgram = stdInput.next();
} while(isValidChoiceChar(repeatProgram) == false);
}
if(repeatProgram.compareTo("Y") == 0) {
continueRunningProgram = true;
} else {
continueRunningProgram = false;
}
} while(continueRunningProgram == true);
stdInput.close();
} // end of main method
public static boolean isValidChoiceNum(int c) {
if(c < 1 || c > 3 ) {
return false;
} else {
return true;
}
}
public static boolean isValidChoiceChar(String c) {
if(c.compareTo("Y") == 0 || c.compareTo("N") == 0) {
return true;
} else {
return false;
}
}
public static double solvingForForce() {
Scanner stdInput2 = new Scanner (System.in);
System.out.println("Please enter a value for mass.");
double m = stdInput2.nextDouble();
System.out.println("Please enter a value for acceleration.");
double a = stdInput2.nextDouble();
stdInput2.close();
return m * a;
}
public static double solvingForMass() {
Scanner stdInput2 = new Scanner (System.in);
System.out.println("Please enter a value for force.");
double f = stdInput2.nextDouble();
System.out.println("Please enter a value for acceleration.");
double a = stdInput2.nextDouble();
stdInput2.close();
return f / a;
}
public static double solvingForAcceleration() {
Scanner stdInput2 = new Scanner (System.in);
System.out.println("Please enter a value for force.");
double f = stdInput2.nextDouble();
System.out.println("Please enter a value for mass.");
double m = stdInput2.nextDouble();
stdInput2.close();
return f * m;
}
} // end of class
Stop the madness of closing a Scanner linked to System.in! It will close the underlying stream (System.in), causing any other attempt to read from that Stream to throw an exception.
Yes you will get a warning, but it is safe to ignore that warning, or you can add
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
To avoid it.
Remember, if you didn't open a resource, you shouldn't close it. Let the JVM close it when it terminates the program.
This also includes creating a Scanner(System.in) inside a try with resources block:
try(Scanner in = new Scanner(System.in)){
//Code...
}
This will implicitly close the stream at the end of the block.
From the Java tutorials:
The try-with-resources statement ensures that each resource is closed at the end of the statement.
Also you have several Scanner objects reading from System.in, which is bad practice. I would pass them to your methods as a parameter:
public static double solvingForMass(Scanner in) {
System.out.println("Please enter a value for force.");
double f = in.nextDouble();
System.out.println("Please enter a value for acceleration.");
double a = in.nextDouble();
return f / a;
}
Also just a note that if you are ever doing the structure of:
if(someBool)
return true;
else
return false;
It can be simplified to just
return someBool
So your isValidChoice() method can be simplified to:
public static boolean isValidChoiceChar(String c) {
return c.compareTo("Y") == 0 || c.compareTo("N") == 0;
}
Although note you can use the equals() and equalsIgnoreCase()methods to compareString`'s
I've been given a task to make some conversions from ft and in to cm. I've gotten most of this down and the conversions do work. I also want to include the statement of A negative number... or A non-digit... when I type a string, for example, or a negative number, to display said message.
The problem I am getting is that when I do type up a string or negative number, I get the output of testProgram.NegativeNumberException when I enter -9, for example. And testProgram.NonDigitNumberException, when I enter joe, for example.
I am thinking there is something wrong in the catch but not sure exactly where it won't click.
package testProgram;
import java.util.InputMismatchException;
import java.util.Scanner;
public class conversion{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double cm = -1;
while(cm == -1){
cm = convertToCentimeters(scan);
if(cm!=-1){
System.out.println("Your result = " +cm);
}
else{
System.out.println("Please enter the values again.");
}
scan.nextLine();
}
}
public static double convertToCentimeters(Scanner scan){
double centimeters = -1;
try{
double foot = getFootValue(scan);
double inch = getInchValue(scan);
double totalInches = foot * 12 + inch;
centimeters = totalInches * 2.54;
}catch(NegativeNumberException e1){
System.out.println(e1);
}
catch(NonDigitNumberException e2){
System.out.println(e2);
}
return centimeters;
}
public static double getFootValue(Scanner scan) throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the foot value: ");
double foot = scan.nextDouble();
if(foot <= 0){
throw new NegativeNumberException ("A negative foot value has been entered.");
}
return foot;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit foot value has been entered.");
}
}
public static double getInchValue(Scanner scan)throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the inch value: ");
double inch = scan.nextDouble();
if(inch <= 0){
throw new NegativeNumberException ("A negative inch value has been entered.");
}
return inch;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit inch value has been entered.");
}
}
}
Alternatively to #Scary's suggestion, you can add a constructor to your custom exceptions as -
NegativeNumberException(String str) {
System.out.println(str);
}
This shall help you print the message when you
throw new NegativeNumberException ("A n....");
I'm pretty new at programming so sorry for bad explanations and/or badly written code...
Anyways, i'm currently working on an assignment using "method overload" and I want to be able to get a double or an int from the user.
My first code worked, so I decided to add an else to the end of the last if statement that checked for bad input and reiterated the entire code. The problem is that while the code works fine when you put numbers the first time, if you put in bad input it will start the while loop and keep re-iterating the code block regardless of any input. I know that it is just ignoring the if statements because their is no previous input of any sort(or anything stopping it?). I need some way of the code checking getting the input and then checking whether it is an integer or double before declaring the variable type...Or if there is some better method please share... if you need any more knowledge reply to this post or whatever...here
Also, its not finished, call it a draft if you
public class LoanRates {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean x = false;
while(x = true){
System.out.println("please enter a number");
x = false;
if (in.hasNextInt()){
int rate = 0;
rate = getNumbers(rate, in);
System.out.println(rate);
break;
} else if( in.hasNextDouble()){
double rate = 0;
System.out.println("please enter a number");
rate = getNumbers(rate, in);
System.out.println(rate);
break;
}else {
System.out.print("please enter a number");}
}
System.out.print("did it work?");
}
public static double getNumbers(double rate, Scanner in){
rate =in.nextDouble();
return rate;
}
public static int getNumbers(int rate, Scanner in){
rate = in.nextInt();
return rate;
}
}
You are using while(x = true) then it is always true
first you must initialize x variable to true. Otherwise it will not go inside the while loop
boolean x = true;
try while(x == true) and make sure to change the value of variable x to false when it is necessary
Try like this. But it is better to pass the double or int value rather than passing the scanner reference to the getNumbers methods
package test;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class LoanRates {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Please enter a number");
String input = in.next();
try {
int rate = Integer.parseInt(input);
// you can use the rate variable and change your method to accept the input value
System.out.println(getNumbers(rate));
break;
} catch (NumberFormatException e) {
try {
double rate = Double.parseDouble(input);
// you can use the rate variable and change your method to accept the input value
System.out.println(getNumbers(rate));
break;
} catch (NumberFormatException ex) {
System.out.println("Invalid number.");
}
}
}
System.out.print("did it work?");
}
public static double getNumbers(double rate) {
// rate calculation logic
return rate;
}
public static int getNumbers(int rate) {
// rate calculation logic
return rate;
}
}
My program is to enter 10 numbers and add them together then display the result. Then I am to divide the smaller number by the larger number and display the result. Users cannot enter characters or zero.
I am new and have been working on this for DAYS. I do not see my mistake.
Now my problem is the Variable i isn't being recognized.
I introduced an Exception (try..catch) and it wouldn't read. I tried moving things all over (I'm new, I'm guessing and seeing what does what..) I did something wrong and probably something stupidly small. I need some help and fresh eyes.
I also need to end the program when the user enters 9999. Any idea where that would go? 'Cause I'm about to break out into tears.
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
System.out.print("Please Enter Ten Numbers:");
System.out.println();
try{
for (int i = 1; i < digit.length; i++)
System.out.print("Numbers " + i + ": ");
digit[i] = (double)in.nextInt(); //Array Not recognized here
sum += (int)digit[i];//Or recognized here
// Input the data into array from the user.
if(digit[i]==0.0)//None of these are recognized either, what did I do?
{
System.out.println("You can't enter zero. Try again");
--i; //nope
in.nextLine();//dispose of wrong number
}
}catch (NumberFormatException e){
System.out.println("You Can Only Enter Numbers!");
--i; //nope, not recognizing here either
in.nextLine();//dispose of wrong input
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
//These are all good and recognized. No problem with the division part
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
}
You for loop doesn't have braces around it. Only the first line below it is part of the loop.
You need braces around the contents of your for loop.
I have tried to modified the attached code snippet. Hope this might help you.
package com.so.general;
import java.util.Scanner;
public class AddNumbers
{
private static final int SIZE_OF_ARRAY = 10;
public static void main(String[] args)
{
int counter = 0;
double sumOfTenDigits = 0.0;
double[] digit = new double[SIZE_OF_ARRAY];
int listOfElements = digit.length;
System.out.print("Please Enter Ten Numbers:"+"\n");
Scanner readInputFromUser = new Scanner(System.in);
try
{
for (counter=0; counter<listOfElements; counter++)
{
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
if(digit[counter] == 0.0)
{
System.out.println("Zero is not allowed. Please try again.");
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
}
sumOfTenDigits += digit[counter];
}
}
catch(NumberFormatException numberFormatExcep)
{
System.err.println(" You have entered other than numbers. Only numbers are allowed. Terminating the program.");
numberFormatExcep.printStackTrace();
System.exit(0);
}
System.out.println("Addition is: "+ sumOfTenDigits);
System.out.println("Would you like to divide the values? Press Y to continue, any other character to terminate the program.");
Scanner continueWithDivide = new Scanner(System.in);
String userInput = continueWithDivide.nextLine();
closeScanner(readInputFromUser);
closeScanner(continueWithDivide);
if(readInputFromUser != null)
{
readInputFromUser.close();
}
// Always use static string literals on the left hand side.
// This prevents Null pointer exception.
if("Y".equalsIgnoreCase(userInput))
{
double[] divisionResult = new double[listOfElements/2];
for(int i=0; i<listOfElements; i+=2)
{
double result = digit[i];
if (result > digit[i+1])
{
result = result/digit[i+1];
}
else
{
result = digit[i+1]/result;
}
divisionResult[i/2] = result;
System.out.println(result);
}
}
else
{
System.out.println("You have entered "+userInput+". Terminating the program.");
System.exit(0);
}
}
/**
* Closed the scanner
* #param scanner
*/
public static void closeScanner(Scanner scanner)
{
if(scanner != null)
{ try
{
scanner.close();
}
catch(IllegalStateException illegatStateExcep)
{
System.err.println("Scanner is already closed.");
illegatStateExcep.printStackTrace();
}
}
}
Please note the below points:
Always use proper indentation.
Always match { }
Even if your if or for is having only one statement, use { }.
For example:
for (int counter=1; i<digit.length; i++)
{
System.out.print("Numbers " + i + ": ");
}
Above three points will save a lot of your time if some thing goes wrong in your program.
Use proper name for the variables and method.
Always close the IO resources after the use.
For example:
if(scanner != null)
{
scanner.close();
}
I a making a program that will ask an int input from user and check whether user input is an integer or not. If no the program asks for an input tile it gets a integer.
Scanner in = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
int num;
if (in.hasNextInt()){
num =in.nextInt();
if(num % 2 == 0){
System.out.print("this is even!!");
} else{
System.out.println("this is odd!!");
}
} else {
System.out.print("pleas enter an integer only!!!");
num = in.nextInt();
if(num % 2 == 0){
System.out.print("this is even second check!!");
} else{
System.out.println("this is odd second check!!");
}
}
here is the code but i have some mistakes in there. it brings an error when input is not an int. pleas help with this, thanks in advance!
Try the below code, it will end only if its a valid Integer otherwise it will keep asking for Integer and I think you are looking for the same.
public void checkInt() {
Scanner scanner = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
try {
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.print("this is even!!");
} else {
System.out.println("this is odd!!");
}
} catch (InputMismatchException e) {
System.out.println("pleas enter an integer only!!!");
checkInt();
}
}
You must read user input as String. Then, inside a try/catch block, make a casting to integer (Integer.parseInt()), if throws a exception is because is not a number.
May be a stupid way but this can solve your problem:
String x;
x = "5";//or get it from user
int y;
try{
y = Integer.parseInt(x);
System.out.println("INTEGER");
}catch(NumberFormatException ex){
System.out.println("NOT INTEGER");
}
Edited:
The program will try to convert the string to integer. If it is integer it will succeed else it will get exception and be caught.
Another way is to check the ASCII value.
To continue till integer is encountered:
String x;
Scanner sc = new Scanner(System.in);
boolean notOk;
do{
x = sc.next();
notOk = check(x);
}while(notOk);
System.out.println("Integer found");
}
private static boolean check(String x){
int y;
try{
y = Integer.parseInt(x);
return false;
}catch(NumberFormatException ex){
return true;
}
}
import java.util.Scanner;
public class Test {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
if(sc.hasNextInt())
System.out.println("Input is of int type");
else
System.out.println("This is something else");
}
}