How do I use InputMismatchExeption to catch strings? (Java) - java

I'm a novice java programmer and need to adjust this code so it catches two strings instead of variables.
Here is the original code we are supposed to use:
import java.util.Scanner;
import java.util.InputMismatchException;
public class Part4 {
public static void main(String[] args) {
int userNum = 0;
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
String dump = null;
while (!inputOK) {
System.out.print("Enter a number: ");
try {
userNum = screen.nextInt();
dump = screen.nextLine();
inputOK = true;
} catch (InputMismatchException e) {
dump = screen.nextLine();
System.out.println("\"" + dump + "\" is not a legal integer, " +
"please try again!");
} // end try-catch block
} // end input loop
screen.close();
userNum = userNum + 20;
System.out.println("Your number plus 20 is " + userNum);
}
}
and here is my failed attempt:
import java.util.Scanner;
import java.util.InputMismatchException;
public class testClass {
public static void main(String[] args) {
String letter = new String();
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
String dump = null;
while (!inputOK) {
System.out.print("Enter ('y' or 'n': )");
try {
letter = screen.nextLine();
dump = screen.nextLine();
inputOK = true;
} catch (InputMismatchException e) {
dump = screen.nextLine();
System.out.println("\"" + dump + "\" is not a legal letter, " +
"please try again!");
}
}
screen.close();
System.out.println("That is a valid letter");
}
}
If anyone could help that would be much appreciated.
Thanks :)

First off InputMismatchException will only be thrown
to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
Since anything but y and n are still String's this won't be thrown. Instead you can throw a new InputMismatchException if it is not y or n:
String letter = new String();
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
while (!inputOK) {
System.out.println("Enter ('y' or 'n': )");
try {
letter = screen.nextLine();
if(!letter.equals("y") && !letter.equals("n")) {
throw new InputMismatchException();
}
inputOK = true;
} catch (InputMismatchException e) {
System.out.println("\"" + letter + "\" is not a legal letter, " +
"please try again!");
}
}
System.out.println("That is a valid letter");
Also it is not good practice to close System.in. The general rule is if you did not open a resource, you should not close it

Related

NoSuchElementException not working when calling method

import java.util.*;
public class Main {
static void factorFinder() {
Scanner sc = new Scanner(System.in);
boolean valid = false;
int number = 0;
while(! valid ){
System.out.println("Enter the number you want to find the factor of(Numbers only)");
try {
number = sc.nextInt();
valid = true;
} catch (InputMismatchException e) {
System.out.println("Not a number.");
sc.next();
}
}
sc.close();
System.out.print("Factors of " + number + " are: ");
for (int i = 1; i <= number; ++i) {
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
public static void main(String[] args) {
Scanner choiceScanner = new Scanner(System.in);
System.out.println("Do you want to use the factor finder? (y/n)");
String answer = choiceScanner.nextLine();
choiceScanner.close();
if(answer.equals("y")){
factorFinder();
}else{
System.exit(0);
}
}
}
Here is the terminal output(Ran through replit)
 sh -c javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')
 java -classpath .:target/dependency/* Main
Do you want to use the factor finder? (y/n)
y
Enter the number you want to find the factor of(Numbers only)
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.factorFinder(Main.java:13)
at Main.main(Main.java:38)
exit status 1

I am making a calculator that finds the factor of a given number. The calculator part is done and is working. However, the part where it asks to use the calculator isn't working. It gave a NoSuchElementException error. Can someone maybe help me on this?
Once you close a Scanner, you cannot read form another one.
So, you have two possible solution (as I can see):
1 (Recomended). Use only one Scanner. You can make it class member or pass it to the method as a parameter.
import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
static void factorFinder() {
boolean valid = false;
int number = 0;
while(! valid ){
System.out.println("Enter the number you want to find the factor of(Numbers only)");
try {
number = sc.nextInt();
valid = true;
} catch (InputMismatchException e) {
System.out.println("Not a number.");
sc.next();
}
}
System.out.print("Factors of " + number + " are: ");
for (int i = 1; i <= number; ++i) {
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
public static void main(String[] args) {
System.out.println("Do you want to use the factor finder? (y/n)");
String answer = choiceScanner.nextLine();
if(answer.equals("y")){
factorFinder();
}else{
sc.close();
System.exit(0);
}
sc.close();
}
}
Close the choiceScanner only after you call your factorFinder() method.
public class Main2 {
static Scanner sc = new Scanner(System.in);
static void factorFinder() {
boolean valid = false;
int number = 0;
while(! valid ){
System.out.println("Enter the number you want to find the factor of(Numbers only)");
try {
number = sc.nextInt();
valid = true;
} catch (InputMismatchException e) {
System.out.println("Not a number.");
sc.next();
}
}
System.out.print("Factors of " + number + " are: ");
for (int i = 1; i <= number; ++i) {
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
public static void main(String[] args) {
Scanner choiceScanner = new Scanner(System.in);
System.out.println("Do you want to use the factor finder? (y/n)");
String answer = choiceScanner.nextLine();
if(answer.equals("y")){
factorFinder();
}else{
sc.close();
System.exit(0);
}
sc.close();
}
}

Simple calculator - "Resource leak: op is never closed" does it harm to not close Scanner?

my questions are the following:
- why does eclipse want me to close the Scanners? Does it any harm to not close them? Do I profit if I close them?
- Is there beginner mistake in my code? What would an java expert solve different?
I have left out subtraction(), multiplication(), division() and modulo() from my code because they work almost the same like addition().
import java.util.InputMismatchException;
import java.util.Scanner;
class Calculator {
/**
* #param args
*/
static boolean invalid = true;
static void addition() throws InputMismatchException {
do {
try {
Scanner a = new Scanner(System.in);
Scanner b = new Scanner(System.in);
System.out.print("Enter a number: ");
double a1 = a.nextDouble();
System.out.print("Enter a number to add it to " + a1 + ": ");
double a2 = b.nextDouble();
System.out.println(a1 + " + " + a2 + " = " + (a1 + a2));
invalid = false;
} catch (InputMismatchException e) {
System.out.println("Oops! Please enter only numbers!");
invalid = true;
}
} while (invalid == true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int o;
boolean turnOff = false;
do {
System.out.print("Choose from one of the operation options.\n"
+ "Type 1 for addition\n" + " 2 for substraction\n"
+ " 3 for multiplication\n" + " 4 for division\n"
+ " 5 for modulo\n");
Scanner op = new Scanner(System.in);
o = op.nextInt();
switch (o) {
case 1:
addition();
break;
case 2:
subtraction();
break;
case 3:
multiplication();
break;
case 4:
division();
case 5:
modulo();
}
do {
System.out.print("Do you want to do more calculations? (n = no, y = yes) ");
Scanner c = new Scanner(System.in);
char input = c.next().charAt(0);
if (input == 'y') {
turnOff = false;
invalid = false;
} else if (input == 'n') {
turnOff = true;
invalid = false;
} else {
System.out.println("y or n is the only valid input. Try again.");
invalid = true;
}
} while (invalid == true);
} while (turnOff == false);
}
}
Normally not closing an AutoCloseable (e.g. a FileInputStream) is a mistake that would result in a resource leak, hence the warning.
But you're right to ask the question here. Say if you were to follow Eclipse's suggestion and close Scanner a, that would actually close the System.in that it's wrapping.
Stylewise I would be tempted to use a single Scanner instance all the way through, probably as an instance variable in the Calculator class. Firstly this would side step the Eclipse warning, but will also be (slightly) more efficient.

Whats wrong with my code? Do while and Try Catch

Keep getting syntax error, insert while expression to complete do statement. It maybe something simple like curly brackets etc.
{
int num = 0;
//flag
boolean inputOk = false;
Scanner s = new Scanner (System.in);
do {
try {
System.out.println("Enter a number....");
num =s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}
} while (inputOk != true);
s.close();
System.out.println("Thank you");
}
In your code you are missing ending curly brackets "}" for do. For Scanner it's better to use try with resource. here is working code
int num = 0;
//flag
boolean inputOk = false;
try (Scanner s = new Scanner(System.in)) {
do {
try {
System.out.println("Enter a number....");
num = s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}
}
while (inputOk != true);
}
System.out.println("Thank you");
You are missing ending curly brackets "{" of Do I have corrected it in below code
int num = 0;
//flag
boolean inputOk = false;
Scanner s = new Scanner (System.in);
do {
try {
System.out.println("Enter a number....");
num =s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}} while (inputOk != true);
{
s.close();
System.out.println("Thank you");
}

Input to exit java program when blank line entered

I have written a RPN Calculator in Java, but I am struggling to get my code to exit when the user enters a blank line instead of an equation. The program needs to loop until this blank line is entered.
Below is my source code.
$`import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
import java.io.FileNotFoundException;
public class Calculator {
private static Scanner input;
public static int invalidlines = 0;
public static int validlines = 0;
public static ArrayList<String> validList = new ArrayList<String>();
public void FileNotFoundException(){
System.out.println("Please enter a valid expression!");
}
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
}
catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
}
else
{
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
}
else
{
return false;
}
}
}
public static void main(String[] args) throws IOException {
input = new Scanner(System.in);
String keyboardInput = new String();
String currentLine = new String();
Scanner kbScan = new Scanner(System.in);
System.out.println("Please press the letter F for file input or K for keyboard input");
String inputString = new String(input.nextLine());
int answer = 0;
while (true){
if (inputString.equals("K") || inputString.equals("k")) {
System.out.println("Please enter an equation");
keyboardInput = kbScan.nextLine();
}
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
if (inputString.equals("") || inputString.equals(""));
{
System.exit(0);
}
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch(equation[2]) { // This case switch checks the third position of the string to decide which operator is being used. It then works out the answer and breaks to the next instruction
case("+"):
answer = num1 + num2;
break;
case("-"):
answer = num1 - num2;
break;
case("/"):
answer = num1 / num2;
break;
case("*"):
answer = num1 * num2;
break;
}
System.out.println("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
System.out.println("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
}
else{
System.out.println("The equation you entered is invalid");
}
if (inputString.equals("f") || inputString.equals("F")) {
try{
//Open the file
System.out.println("Enter File Name: ");
FileInputStream fstream = new FileInputStream(input.nextLine()); // make a input stream
BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); // pass input stream to a buffered reader for manipulation
String strLine; // create string vars
//loop to read the file line by line
while ((strLine = br.readLine()) != null) { // Whilst the buffered readers read line method is not null, read and validate it.
currentLine = strLine;
if(isValidLine(currentLine))
{
validList.add(currentLine);
validlines++;
String[] filearray = new String[3];
filearray = currentLine.split(" ");
int val1 = Integer.parseInt(filearray[0]);
int val2 = Integer.parseInt(filearray[1]);
System.out.println("Your expression is: " + filearray[0] + " " + filearray[1] + " " + filearray[2]);
switch(filearray[2]) {
case("+"):
answer = val1 + val2;
break;
case("-"):
answer = val1 - val2;
break;
case("/"):
answer = val1 / val2;
break;
case("*"):
answer = val1 * val2;
break;
}
System.out.println("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Please Enter a valid file name");
}
}
}
}
}
Just use following code to check the variable in which you are taking the user input,whether it's empty or not?
I am assuming you are taking in a variable called inputString,then the code should be-
if(inputString.isEmpty())
{
System.exit(0);
}
maybe you should use break instead of System.exit(0).
Also, I would check for empty input as soon as I read the input.

how to handle NumberFormatException in more specific way?

I want to handle NumberFormatException in more specific way.
This exception occurs, when it tries assign anything but an integer, when the following is entered:
string
character
empty input
double number
Depending on what was entered I want to display a proper message, like
you've entered string, please enter an integer
or
value can't be null, please enter an integer value
The code below catches NumberFormatException in general way.
I wonder is there a way to include more catch clauses.
import java.util.Scanner;
public class TestException {
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
try {
input = Integer.parseInt(scan.next());
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
System.out.println("You've entered non-integer number");
System.out.println("This caused " + e);
}
}
}
First take the input from the user and after that try to convert it to integer.
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
String inputString = scan.next();
try {
input = Integer.parseInt();
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
if(inputString.equals("") || inputString == null) {
System.out.println("empty input");
} else if(inputString.length == 1) {
System.out.println("char input");
} else {
System.out.println("string input");
}
}
}
You've to use if-else construct to specify your scenerios within catch block.
See the code below:
String inString = null;
try
{
iString = scan.next().trim();
input = Integer.parseInt(inString);
System.out.println("You've entered number: " + input);
}
catch (NumberFormatException e)
{
if(inString.equals("")
{
System.out.println("You've entered empty string.");
}
else if(inString.length() == 1)
{
System.out.println("You've entered a single char");
}
else
{
System.out.println("You've entered non-intereger number");
}
System.out.println("This caused " + e);
}
You could do some more tests on the input if parsing the input as an integer value caused an exception, something like this:
String scanned = null
try {
scanned = scan.next();
input = Integer.parseInt(scanned);
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
if (scanned == null || scanned.isEmpty()) {
System.out.println("You didn't enter any value");
} else if (scanned.length() == 1)
System.out.println("You entered a single char which is not a number");
}
// and more tests, you can even try to parse as Double
}
String aString = null;
aString = scan.next().trim();
System.out.println("You've entered number: " + aString);
if("".equals(aString.trim())){
System.out.println("You have entered an Empty String");
}else if(!isNumber(aString) && aString.length()==1){
System.out.println("You have entered a Character");
}else if(!isNumber(aString) && aString.length()>1){
System.out.println("You have entered a String");
}else if(isNumber(aString)){
int input = Integer.parseInt(aString.replaceAll(",",""));
System.out.println("You have entered a correct Number"+input);
}
private boolean isNumber(String s){
return s.matches("[0-9]+(,[0-9]+)*,?");
}
public static int isInt(){
boolean ok=false;
int b=1;
do{
String next = sc.next();
int a=b;
try{
a = Integer.parseInt(next);
}catch(Exception e){
System.out.println("Invalid Option...");
continue;
}
if(a==1){b=a;ok=true;}
else if(a==2){b=a;ok=true;}
else if(a==3){b=a;ok=true;}
}while(!ok);
return b;
}

Categories

Resources