I'm trying to make a program that gets a number from the user and checks the number is a prime number or not. I was thinking about the error handling. When the user enters a string the program should give an error message instead of an exception. I tried many methods but couldn't be successful. Could you guys help me with that?
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
if(inputNum < 0){
System.out.println("Please enter a possitive number.");
}
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
}
If user enters a non-integer input, this line
inputNum = input.nextInt();
will throw an exception (an InputMismatchException). The way Java handles exceptions is through a try-catch block:
try {
inputNum = input.nextInt();
// ... do domething with inputNum ...
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
Note: If you want to know more about exceptions (and you must) you can read Java tutorials.
just put it in try-catch and then print your message when exception occurs mean in the catch clause..its simple thing
If you need to check the input first and if it is a number check for prime and if it is invalid prompt user for another input until he enter a valid one, try this.
String inputString;
boolean isValid = false;
while(isValid == false){
//sysout for input
inputString = input.nextLine();
if(inputString.matches("[0-9]+")){
// check for prime
isValid = true;
}else{
//printin error
}
}
}
Thank you to every one especially to Christian. Here is the latest code.
import java.util.InputMismatchException;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
}
}
Related
im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i
I remember having this exact issue in Python. This Java code is a replica of my Python code which calculates the area of a triangle. I have it catch an exception if a non-number value is entered, but the end result gets botched.
private static float baseLength() {
float baseLength = 0;
Scanner user_input = new Scanner(System.in);
try {
while (baseLength <= 0) {
System.out.print("Enter the base length of the triangle: ");
baseLength = user_input.nextFloat();
if (baseLength <=0) {
System.out.println("Error. Plase enter a number higher than 0.");
}
}
} catch (InputMismatchException badChar) {
System.err.println("You have entered a bad value. Please try again");
baseLength();
}
return baseLength;
It will recover from bad numbers, but not from a value that is not a number. I still can't figure out what the exact issue is.
You can put the while loop around the try/catch block to achieve this:
private static float baseLength() {
float baseLength = 0;
Scanner user_input = new Scanner(System.in);
while (baseLength <= 0) {
try {
System.out.print("Enter the base length of the triangle: ");
baseLength = user_input.nextFloat();
if (baseLength <= 0) {
System.out.println("Error. Plase enter a number higher than 0.");
}
} catch (InputMismatchException badChar) {
System.err.println("You have entered a bad value. Please try again");
}
}
return baseLength;
}
with tests more clear, and exception inside principal loop, and every errors with System.err
private static float baseLength() {
float baseLength = 0;
while (true)
{
try {
System.out.print("Enter the base length of the triangle: ");
Scanner user_input = new Scanner(System.in);
baseLength = user_input.nextFloat();
if (baseLength>0)
return baseLength;
if (baseLength <=0)
System.err.println("Error. Plase enter a number higher than 0.");
}
catch (InputMismatchException badChar)
{
System.err.println("You have entered a bad value. Please try again");
}
}
}
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
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.");
}
}
I have made a very simple guessing game. But I want to count the sum of attempts a user made before finding the original number. That means once the Hidden number is matched with user input, it should tell how many numbers has been entered before the user won.
This is my code:
package guessinggame;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int hiddenNum = 10;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a numebr by guessing: ");
int guessedNum = input.nextInt();
if (guessedNum == hiddenNum) {
System.out.println("Congratulation! Your number is matched");
System.exit(0);
} else if (guessedNum < hiddenNum) {
System.out.println("Not matched! Try a bigger number");
} else if (guessedNum > hiddenNum) {
System.out.println("Not matched! Try a smaller number");
}
}
}
}
ition
} else if (guessedNum < hiddenNum) {
System.out.println("Not matched! Try a bigger number");
//checking another condition
} else if (guessedNum > hiddenNum) {
System.out.println("Not matched! Try a smaller number");
}
}
}
}
try this:
public static void main(String[] args) {
//storing the hidden number in a variable
int hiddenNum = 10;
//introducing the scanner class (for user input)
Scanner input = new Scanner(System.in);
//asking user to enter a random number
int attempts = 0; // use as a counter
while (true) {
System.out.println("Enter a numebr by guessing: ");
//Storing that into a variable
int guessedNum = input.nextInt();
attempts += 1;
//Checking wheather the number is matched
if (guessedNum == hiddenNum) {
System.out.println("Congratulation! Your number is matched");
//System.out.println("You have made total of " + attempts +" attempts to find the number!");
//If matched number found, terminate the program
System.exit(0);
//checking another condition
} else if (guessedNum < hiddenNum) {
System.out.println("Not matched! Try a bigger number");
//checking another condition
} else if (guessedNum > hiddenNum) {
System.out.println("Not matched! Try a smaller number");
}
}
}
This reply is better suited on http://codereview.stackexchange.com but here it goes.
package guessinggame;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int hiddenNum = 10;
int guessedNum = 0;
Scanner input = new Scanner(System.in);
boolean running = true;
for (int i = 1; running; i++) {
System.out.println("Enter a number to guess: ");
guessedNum = input.nextInt();
if (guessedNum == hiddenNum) {
System.out.println("Congratulation! Your number is matched");
System.out.println("You have made " + i + " to find the number!");
running = false;
} else if (guessedNum < hiddenNum) {
System.out.println("Not matched! Try a bigger number");
} else {
System.out.println("Not matched! Try a smaller number");
}
}
}
}
Some changes to the code:
You should avoid having while (true) and "randomly" terminating the program. Instead I introduced boolean variable. It can either hold the value of true or false. I put it as true in the start and later set it to false if the user guesses right.
I removed the comments for now, generally you should use comments when the code doesn't explain itself. For example here it is a good reason to use it on the for loop. (A while loop is better practice here, I just wanted to show a for loop.)
For the last condition check I removed the comparison, either it is equal, bigger or smaller. If we've tested equal and bigger all that remains is smaller, hence just the else there.