NoSuchElementException not working when calling method - java

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();
}
}

Related

How to end this program when user inputs "end"?

So basically I am trying to figure out how to stop this program using Integer.valueOf(String s) or Integer.parseInt(String s) by typing "end" for the user input
import java.util.Scanner;
public class monkey1{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int sum = 0;
int lol = 1;
do {
System.out.print("Enter a number: ");
lol = s.nextInt();
sum += lol;
if (lol > 0) {
System.out.println("Sum is now: " + sum);
}
} while (lol>0);
}
}
First - you need to change lol=sc.nextInt() to String tmp = s.nextLine()
Second - do
try {
if (tmp.equals("END")) {
break; // This will exit do-while loop
}
lol = Integer.parseInt(tmp);
} catch (NumberFormatException e) {
e.printStackTrace();
// Here you can also exit loop by adding break. Or just ask user to enter new text.
}
you should learn how to use try/catch.
Here we go:
String text = "";
int lol = 1;
do {
System.out.print("Enter a number: ");
text = s.nextLine();
try {
lol = Integer.valueOf(text);
}catch (Exception e){
System.out.println("Exit");
System.exit(0);
}
Here is your code
package Phone;
import java.util.Scanner;
public class monkey1{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int sum = 0;
int hi = 1;
do {
System.out.print("Enter a number: ");
String lol = s.nextLine();
if(lol.equals("end")) {
break;
}
hi = Integer.parseInt(lol);
sum += hi;
if (hi > 0) {
System.out.println("Sum is now: " + sum);
}
} while (hi > 0);
}
What I did here is I changed lol to hi for adding and took String input so that you can input end...
I would suggest checking if s.equals("end") before converting to int so something like this:
do {
System.out.print("Enter a number: ");
String userValue = s.nextLine();
if(userValue.equals("end")
break;
lol = Integer.parseInt(userValue);
sum += lol;
if (lol > 0){
System.out.println("Sum is now: " + sum);
}
}while (lol>0);

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();
}
}

How to Subtract n numbers using for loop in java?

When I use for loop for subtraction, i don't get a correct output.
What logic should i apply in my code to get my subtraction correctly using for loop?
Please help me as i am new in JAVA.
My code is as Follow:
import java.io.*;
import java.util.*;
class Sub
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int a,n,i;
String yn;
boolean loop=true;
while(loop)
{
try
{
do
{
loop=true;
System.out.println("Enter how many numbers to Subtract?: ");
n=s.nextInt();
int sum=0;
for(i=1;i<=n;)
{
try
{
System.out.println("Enter number "+i+" : ");
a=s.nextInt();
sum=a-sum;
i++;
}
catch(Exception e)
{
System.out.println("Invalid Entry. Try again!!");
}
}
System.out.println("Answer is:"+sum);
System.out.println("Do you want to continue?(Y/N): ");
yn=s.next();
loop=yn.equals("Y")||yn.equals("y");
}while(loop);
}
catch(Exception e)
{
System.out.println("Re-enter the Limit");
}
}
}
}
You should start with sum as the first number (not zero) and subtract the rest of the numbers from it:
loop=true;
System.out.println("Enter how many numbers to Subtract?");
n=s.nextInt();
int sum=0;
for(i=1;i<=n;)
{
try
{
System.out.println("Enter number "+i+" : ");
a=s.nextInt();
sum=a-sum;
i++;
}
catch(Exception e)
{
System.out.println("Invalid Entry. Try again!!");
}
}
to:
...
loop = true;
System.out.println("Enter how many numbers to Subtract?: ");
n = s.nextInt();
System.out.println("Enter number 1 : ");
int sum = s.nextInt();
for (int i=2; i <= n; i++) {
try {
System.out.println("Enter number " + i + " : ");
a = s.nextInt();
sum -= a;
} catch (Exception e) {
System.out.println("Invalid Entry. Try again!!");
}
}
...
Further, instead of doing:
yn.equals("Y") || yn.equals("y")
you can use equalsIgnoreCase():
yn.equalsIgnoreCase("Y")
And last, you should use meaningful names for variables (it's recommended to develop good habits even if it's such a small program), so instead of:
int a, n, i; // you can define and use i inside the for-loop - no need to define it outside
String yn;
consider using more expressive names, such as:
int inputNumber, numberOfVariables;
String continueLooping;
The following version could be improved (refactored even further):
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
int numOfArguments = getNumberOfArguments(scanner);
int sum = getNextNumberFromUser(scanner, 1);
for (int i = 2; i <= numOfArguments; i++) {
sum -= getNextNumberFromUser(scanner, i);
}
System.out.println("Answer is: " + sum + "\n\nDo you want to continue?(Y/N): ");
String runAgain = scanner.next();
if (runAgain.equalsIgnoreCase("N")) {
break;
}
}
}
private static int getNextNumberFromUser(Scanner scanner, int i) {
while (true) {
try {
System.out.println("Enter number " + i + " : ");
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid Entry. Try again!!");
scanner.nextLine();
}
}
}
private static int getNumberOfArguments(Scanner scanner) {
int numberOfArguments = -1;
System.out.println("Enter how many numbers to Subtract?: ");
while (numberOfArguments == -1) {
try {
numberOfArguments = scanner.nextInt();
if (numberOfArguments <= 0) {
numberOfArguments = -1;
}
} catch (InputMismatchException e) {
System.out.println("Illegal number of arguments to subtract, please try again: ");
scanner.nextLine();
}
}
return numberOfArguments;
}

Java: Accept input as string or int

I am trying to make a simple even or odd program. I want it to keep running until the user enters in 'q'. But I am having trouble accepting 'q' as a String.
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
int number;
String quit;
try {
number = myScanner.nextInt();
} finally {
quit = myScanner.nextLine();
}
if (quit.equals("q")) {
break;
} else if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
}
The program works fine when I enter numbers, but when I enter 'q', the console throws an error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at EvenOrOdd.main(EvenOrOdd.java:19)
I know this may be easy for many of you, but I have just picked up a java book and am trying to finish the task. Any help would be greatly appreciated!
You can make something like this and i found that a boolean is better for a loop in this case instead of while(true) and break:
public class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out
.println("Welcome to my program that checks if a number is even or odd.");
boolean enterLoop = true;
while (enterLoop) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
String scannerinput = myScanner.nextLine();
if (scannerinput.equals("q")) {
enterLoop = false;
} else {
checkNumber(scannerinput);
}
}
}
private static void checkNumber(String scannerinput) {
try {
int number = Integer.parseInt(scannerinput);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
} catch (Exception e) {
System.out.println("No Number!");
}
}
}
Take a String from Scanner, check if is 'q' and if not, convert it to int and then check even or odd.
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
String inText = myScanner.next();
if (inText.equals("q")){
break;
}
int number = Integer.valueOf(inText);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.print("\nPlease type number in a number ['q' to quit]: ");
String input = scanner.next();
if (input.equals("q")) {
break;
} else {
int number = Integer.parseInt(input);
System.out.print(number + " is ");
System.out.print(number%2 == 0 ? "Even." : "Odd.");
}
}
}
}
That'll do it. :)
Instead of using myScanner.nextInt(), just use myScanner.next() to get a String. Then if it is not "q", use Integer.valueOf(inputString) to get the int and check it for even/odd.
while (true) {
String input = myScanner.next();
if ("q".equals(input)) {
break;
} else {
int number = Integer.valueOf(input);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
Try this approach. Check code note for more details.
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
String input=null;
int number;
boolean flag=true; // loop flag
do {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
// Take user input as String
input=myScanner.nextLine();
try
{
// convert the string value to integer value
number = Integer.parseInt(input);
if (number % 2 == 0)
{
System.out.println(number + " is Even.");
}
else
{
System.out.println(number + " is Odd.");
}
}
catch (NumberFormatException nfe)
{
// control goes here if input is not integer value
if(input.equals("q")) // exist option
flag=false;
else // invalid input
System.out.println("Invalid input, Please enter integer value or (q) to exist");
}
} while (flag);
}
}
You should update your method flow, you are actually trying to pass and intger validation for a string so first take the input as String and check whether it is your quit character q then if it is not try to parse the string to and int primitive with Integer.parseInt(input) and test if it is Odd or Even.
If the process fails assuming it is neither a q nor a number (any other character), then a message will be prompted for user telling him to use a valid number or "q" to quit:
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
int number;
String input = myScanner.next();
if (input.equals("q")) {
break;
} else {
try {
number = Integer.parseInt(input);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
} catch (NumberFormatException nfe) {
System.out.println("Enter valid number or \"q\" to quit!");
}
}
}
}
}
It is because the program is expecting a input of int-type, basically the program outputs: Please type number in a number ['q' to quit], and after that it will reach the myScanner.nextInt(); line and will be waiting for a input, and since "q" is not a integer it will throw an exception.
A quick solution would be to use myScanner.nextLine() and then convert the string into a integer unless it is equal to 'q'. Something like this:
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
String string = myScanner.nextLine();
int number = 0;
if (string.equals("q")) {
myScanner.close(); // Close the scanner.
break;
} else if ((number = toInteger(string)) == -1){ // Is the string a number, less than Integer.MAX_VALUE and greater than Integer.MIN_VALUE?
System.out.printf("%s is not a valid integer!%n",string);
} else if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
private static int toInteger(String str){
try{
return Math.abs(Integer.parseInt(str));
}catch(NumberFormatException e){
return -1;
}
}
}
By the way, always close the scanner, otherwise a resource leak may occur.

Categories

Resources