I have the following homework problem:
Write an application integer on that
reads an integer and determines and
prints whether it is odd or even.
Use the Scanner class for reading input.
Store that input into an integer. Check if input is really a valid integer. Otherwise, throw an exception.
Afterwards, use the modulo operator to check if it's odd or even.
Use System.out.println to print if it's odd or even.
public static void main(String[] args) {
System.out.println("Enter number");
Scanner sc = new Scanner(System.in);
try {
int i = sc.nextInt();
if (Math.abs(i) / i == 1) {
if ((Math.abs(i) % 2) == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
} catch (Exception ex) {
System.out.println("Exception " + ex.toString());
}
}
Related
So it looks like it allows me to input all ints, and when i do a string or anything else it does give me error, but how do I go about making it so its ONLY 1 and/or 2 accept and 3,4,5....(every other number) are not excepted...
Code below
public static void main(String[] args){
System.out.println("Please enter 1 to add or 2 to multiply. "); // ask user to input 1 or 2
Scanner in = new Scanner(System.in);
try {
int add = in.nextInt(); // add for 1
int multiply = in.nextInt(); // multiply for 2
}
catch (Exception e) {
System.out.println("Operation failed. You need to enter 1 or 2.");
}
}
Exceptions here would be overkill IMO. Just using if else clauses would work equally well. Like this:
if(input == 1) {
// add
}
else if(input == 2) {
// multiply
}
else {
System.out.println("Operation failed. You need to enter 1 or 2.");
}
Also if you want the program to keep prompting you can just wrap it in a loop. Here is a small example using a boolean sentinel to keep the loop going. This is one of many ways to implement this task.
public static void main(String[] args) {
System.out.println("Please enter 1 to add or 2 to multiply. "); // ask user to input 1 or 2
Scanner in = new Scanner(System.in);
boolean inputNotValid = true;
while(inputNotValid){
int input = in.nextInt();
if(input == 1) {
inputNotValid = false;
//add
System.out.println("adding");
}
else if(input == 2) {
inputNotValid = false;
//multiply
System.out.println("multiplying");
}
else {
System.out.println("Operation failed. You need to enter 1 or 2. Try again");
}
}
}
Replace:
int add = in.nextInt(); // add for 1
int multiply = in.nextInt(); // multiply for 2
with:
int value = in.nextInt();
if(value == 1) // do add
if(value == 2) // do multiply
// else case = error
The whole program would become:
public static void main(String[] args)
{
System.out.println("Please enter 1 to add or 2 to multiply. ");
Scanner in = new Scanner(System.in);
try
{
int value = in.nextInt();
if (value == 1)
{
System.out.println("add");
// do add
}
else if (value == 2)
{
System.out.println("mult");
// do multiply
}
else
{
// error
System.out.println("Operation failed. You need to enter 1 or 2.");
}
}
catch (Exception e)
{
System.out.println("Read operation failed. This should not happen!");
}
}
The javadoc for nextInt() says:
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
You still can catch the InputMismatchException, the NoSuchElementException and the IllegalStateException, since in.nextInt() can throw them. You could also catch Exception (the only superclass of all three exceptions) instead.
Since Exception is an unchecked Exception, you can also remove the try-catch. Beware though, that an error in the Input will then exit the whole program.
There are several questions I would like to ask, please refer the comment part I have added in the code, Thanks.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
/* Task:
prompt user to read two integers and display the sum. prompt user to read the number again if the input is incorrect */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a;
int b;
while (accept_a == false) {
try {
System.out.print("Input A: ");
a = input.nextInt(); /* 1. Let's enter "abc" to trigger the exception handling part first*/
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine(); /* 2. I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it? */
}
}
while (accept_b == false) {
try {
System.out.print("Input B: ");
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) { /*3. Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception? */
System.out.println("Input is Wrong");
input.nextLine();
}
}
System.out.println("The sum is " + (a + b)); /* 4. Why a & b is not found?*/
}
}
I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it?
The use of input.nextLine(); after input.nextInt(); is to clear the remaining content from the input stream, as (at least) the new line character is still in the buffer, leaving the contents in the buffer will cause input.nextInt(); to continue throwing an Exception if it's no cleared first
Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception?
You could, but what happens if input b is wrong? Do you ask the user to re-enter input a? What happens if you have 100 inputs and they get the last one wrong?You'd actually be better off writing a method which did this for, that is, one which prompted the user for a value and returned that value
For example...
public int promptForIntValue(String prompt) {
int value = -1;
boolean accepted = false;
do {
try {
System.out.print(prompt);
value = input.nextInt();
accepted = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine();
}
} while (!accepted);
return value;
}
Why a & b is not found?
Because they've not been initialised and the compiler can not be sure that they have a valid value...
Try changing it something more like.
int a = 0;
int b = 0;
Yes, it's okay. And will consume the non-integer input.
Yes. If we extract it to a method.
Because the compiler believes they might not be initialized.
Let's simplify and extract a method,
private static int readInt(String name, Scanner input) {
while (true) {
try {
System.out.printf("Input %s: ", name);
return input.nextInt();
} catch (InputMismatchException ex) {
System.out.printf("Input %s is Wrong%n", input.nextLine());
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = readInt("A", input);
int b = readInt("B", input);
System.out.println("The sum is " + (a + b));
}
I have put comment to that question line.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a=0;
int b=0;
System.out.print("Input A: ");
while (accept_a == false) {
try {
a = input.nextInt(); // it looks for integer token otherwise exception
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next(); // Move to next other wise exception // you can use hasNextInt()
}
}
System.out.print("Input B: ");
while (accept_b == false) {
try {
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next();
}
}
System.out.println("The sum is " + (a + b)); // complier doesn't know wheather they have initialised or not because of try-catch blocks. so explicitly initialised them.
}
}
Check out this "nextLine() after nextInt()"
and initialize the variable a and b to zero
nextInt() method does not read the last newline character.
I have this method and I want to check for user input. If it is a number but greater than 9 and lees than 1 or Char / String I want to throw an Exception. With the numbers it works but when I want to check for char/Strings it goes in infinite loop.
private static Scanner in = new Scanner(System.in);
public static int getPlayerPositionInput(String message) {
System.out.println(message);
while(true) {
System.out.println("1");
try {
if(in.hasNextInt()){
int i = in.nextInt();
if(i<1 || i>9 ) throw new IOException();
return i;
} else throw new IOException();
} catch(Exception e) {
System.out.println("The number has to be greater than 0 and less than 10");
}
}
}
I was thinking about using ASCII table, would it be a good idea ?
If you enter a String then if(in.hasNextInt()){ will always be false and hence no input will be possible.
Try using hasNext and nextLine
The problem is, that after you submit the non-numeric string, hasNextInt() returns false. But scince you do not discard the wrong input, it will return false the next time it is called, too.
Try this:
while (true) {
System.out.println("1");
try {
if (in.hasNext()) {
if (in.hasNextInt()) {
int i = in.nextInt();
if (i < 1 || i > 9) {
throw new IOException();
}
return;
} else {
in.next(); // discard the input
throw new IOException();
}
}
} catch (IOException e) {
System.out.println("The number has to be greater than 0 and less than 10");
}
}
Its because you are catching the exception and going for next loop.
Exception is Super Class to IOException. Go through below documentation.
http://docs.oracle.com/javase/7/docs/api/java/io/IOException.html
Your exception catching logic needs to be refactored.
This question already has answers here:
Java input mismatch error using scanner
(3 answers)
Closed 8 years ago.
I am working on homework for my class. I have written a method to throw an error if an incorrect integer is entered and I am trying to give an error message when a string is entered instead of an int but I am not sure how. I am not allowed to use parsInt or built in string methods. I would be grateful for any help.
int playerNum = stdin.nextInt();
while (invalidInteger(playerNum) == -1 || invalidInteger(playerNum) == -2 || invalidInteger(playerNum) == -3)
{
if(invalidInteger(playerNum) == -1)
{
System.out.println("Invalid guess. Must be a positive integer.");
System.out.println("Type your guess, must be a 4-digit number consisting of distinct digits.");
count++;
}
if(invalidInteger(playerNum) == -2)
{
System.out.println("Invalid guess. Must be a four digit integer.");
System.out.println("Type your guess, must be a four digit number consisting of distinct digits.");
count++;
}
if(invalidInteger(playerNum) == -3)
{
System.out.println("Invalid guess. Must have distinct digits.");
System.out.println("Type your guess, must be a four digit number consisting of distinct digits.");
count++;
}
playerNum = stdin.nextInt();
}
Added this snippet to catch the exception. Thanks to almas shaikh.
try {
int playerNum = scanner.nextInt();
//futher code
} catch (InputMismatchException nfe) {
System.out.println("You have entered a non numeric field value");
}
Use the following code:
try {
int playerNum = scanner.nextInt();
//futher code
} catch (InputMismatchException nfe) {
System.out.println("You have entered a non numeric field value");
}
Scanner throws InputMismatchException when you enter string instead of integer. So very next time when you try to enter String it will throw the InputMismatchException exception, you could catch the exception and say you let user know that user has entered invalid input and let him retry.
Check the java doc for nextInt() -- is stdin a Scanner? If so, nextint() will throw an exception if some non-integer text is entered. You would probably want to catch that and print your own pretty error. Though, you might be going even further than the assignment expects. The phrase "throw an error if an incorrect integer is entered" might imply that only integers will be entered. It depends on the instructor/class.
import java.util.*;
public class Test
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
try
{
int i = in.nextInt();
}
catch(InputMismatchException e)
{
e.printStackTrace();
}
}
}
I hope this will server as an example. When you give an char or string. exception is raised.
Well, you can use next() to get the value as a String, then parse the value and see if a String or Integer was entered.
String str = stdin.next();
for (char c:str.toCharArray()) {
if (!Character.isDigit(c)) {
throw new IllegalArgumentException("Invalid character entered: " + c);
}
}
The program takes user input which is supposed to be an integer greater than 0. If the user doesn't do this he is notified of the mistake and is reprompted. Once the correct input is entered, the value is returned. What's the best way to do this? The following code is my try but doesn't work. It seems unnecessarily complex for such an easy task.
System.out.println("Please enter an integer greater than 0:");
Scanner scan = new Scanner(System.in);
int red = -1;
do
{
try
{
red = scan.nextInt();
}catch(InputMismatchException e)
{
System.out.println("Number must be an integer");
scan.nextLine();
if(red < 1)
System.out.println("Number must be more than zero");
else
break;
}
}while(true);
return red;
Sometimes I don't know what to put in my question because I already know the code doesn't work - so if there's something else I should tell please let me know.
The basic concept is running in the right direction, beware though, nextInt won't consume the new line, leaving it within the scanner, meaning you will end up with an infinite loop after the first unsuccessful loop.
Personally, I would simply get the input as a String using nextLine, which will consume the new line, causing the next loop to stop at the statement.
Then I would simply parse the String to an int value using Integer.parseInt
For example...
Scanner scan = new Scanner(System.in);
int red = -1;
do {
System.out.print("Please enter an integer greater than 0:");
String text = scan.nextLine();
if (text != null && !text.isEmpty()) {
try {
red = Integer.parseInt(text);
// This is optional...
if (red < 1) {
System.out.println("Number must be more than zero");
}
} catch (NumberFormatException exp) {
// This is optional...
System.out.println("Not a number, try again...");
}
}
} while (red < 1);
I use this class instead of the Scanner or BufferedReader classes to get user input:
import java.io.*;
public class Input{
private static BufferedReader input=new BufferedReader
(new InputStreamReader(System.in));
public static Double getDouble(String prompt){
Double value;
System.out.print(prompt);
try{
value=Double.parseDouble(Input.input.readLine());
}
catch (Exception error){
// error condition
value=null;
}
return value;
}
public static Integer getInteger(String prompt){
Integer value;
System.out.print(prompt);
try{
value=Integer.parseInt(Input.input.readLine());
}
catch (Exception error){
// error condition
value=null;
}
return value;
}
public static String getString(String prompt){
String string;
System.out.print(prompt);
try{
string=Input.input.readLine();
}
catch (Exception error){
// error condition
string=null;
}
return string;
}
}
Now, to answer your question u can write your code like this:
public class InputTest {
public int checkValue() {
int value;
do {
value = Input.getInteger("Enter a value greater than 0: ");
} while (value <= 0);
return value;
}
}