/**
* Read a positive integer and return its value
* #param the prompt to be shown to the user
*/
public static int readPositiveInteger(String prompt)
{
System.out.println (prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;
if (scan.hasNextInt() && positive == false)
{
int input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
}
I'm trying to make it so the user can't insert 0 or a negative number. However I don't think my logic is correct as I'm getting a missing return error. Can anyone help?
Thanks!
The if should be a while:
while (scan.hasNextInt() && positive == false)
{
int input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
Really, there's no need of keeping the positive boolean, since the moment it passes
if (input > 0)
it immediately returns, without any further checks on the boolean.
Your method signature is as follows:
public static int readPositiveInteger(String prompt)
However, you never return an integer. You have two choices:
Add something like return 0; to the end of your method
Change static int to static void.
The first is the better option, I think, since you want to return the integer that was read. If none is read, you can tell the program a 0 was there.
The best option, though, is to modify your if statement to use a while loop, and return something only when the user has inputted something.
As mentioned by others here, your outer if statement should be a while loop:
while (scan.hasNextInt() && positive == false)
{
...
}
Also, you've only one return statement written in an if statement. If simply converting the above mentioned if statement to a while loop doesn't help, try return 0 after your while loop.
The java compiler (and others as well) doesn't understand the semantics of code. It can only check for a correct syntax. So, in your case, it might be concerned that the return command might never be reached. A return 0 at the end of your function would solve that (despite that return 0 will never be reached).
public static int readPositiveInteger(String prompt)
{
System.out.println (prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;
int input;
if (scan.hasNextInt() && positive == false)
{
input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
return input;
}
All paths of your method should return something since you define it as
public static int readPositiveInteger(String prompt)
Looks like you are expecting your code to be in a while loop or something?
As it stands it can "run off the bottom" - and like the error says, there is no return (which is required).
You need a while loop. In pseudo code:
While true (ie loop forever)
Ask for input
If input ok return it
You have to add a return statement in the else block otherwise your code wont compile
your method expects a return statement in the else block
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
return 0;//your missing return statement
}
}
What you have to do is add return input; in the end of the method that is
public static int readPositiveInteger(String prompt) {
System.out.println(prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;
if (scan.hasNextInt() && positive == false) {
int input = scan.nextInt();
if (input > 0) {
positive = true;
{
return input;
}
} else {
System.out.println("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
else {
System.out.println("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
return 0;
}
This function will work perfectly for you
public static int readPositiveInteger(String prompt) {
System.out.println(prompt);
System.out.println("Enter an integer");
Scanner scan = new Scanner(System.in);
boolean positive = false;
int input = 0;
while (input <= 0) {
System.out.println("please enter a number greater then 0");
input = scan.nextInt();
}
return input;
}
public static int readPositiveInteger()
{
return int_type;
}
has the return type as int so you should return the integer values in function.
Related
package react;
import java.util.Scanner;
public class Intputfromuser {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter a number to compare with number 5 ");
Scanner input= new Scanner(System.in);
int a=input.nextInt();
if(a==2)
{
System.out.println("U Have Entered The same value");
}
else if(a<2)
{
System.out.println("Ur number is Smaller than 2");
}
else if(a>2)
{
System.out.println("U Have Entered the number Greater than ");
}
else {
System.out.println("U Have Enterer Invalid Input");
}
}
}
how to get only integer from the user if the user enters any thing except integer then else statement should run
Another alternative. Be sure to read the comments in code:
public static void main(String[] args) {
/* Open a keyboard input stream. There is no need to close
this stream. The JVM will do that automatically when the
application closes. */
Scanner input = new Scanner(System.in);
String val = ""; // Used to store User input:
// User Prompt with 'quit' capability and entry validation:
while (val.isEmpty()) {
System.out.print("Enter a number to compare with number 5 (q to quit): -> ");
val = input.nextLine().trim(); // Trim in case just a whitespace(s) was entered.
// Was 'q' for quit supplied?
if (val.equalsIgnoreCase("q")) {
/* Yes...then quit. Returning out of main() effectively
closes this particular application: */
System.out.println("Quiting - Bye Bye");
return;
}
// Validate Entry:
/* Is entry a string representation of a signed or unsigned Integer
value and does the supplied value fall within the relm of an int? */
if (!val.matches("-?\\d+") || (Long.parseLong(val) < Integer.MIN_VALUE) ||
(Long.parseLong(val) > Integer.MAX_VALUE)) {
// No...Inform User and allow to try again:
System.out.println("Invalid Numerical Entry! {" + val + ") Try again..."
+ System.lineSeparator());
val = ""; // Empty variable to ensure re-loop:
}
}
// If you make it to this point in code, the User input was valid!
// Now parse the String numerical value to an int:
int a = Integer.parseInt(val);
/* At this point, there are only three usable conditions:
Equal To, Less Than, and Greater Than (validity has
already been handled within the `while` loop: */
// Equal To:
if (a == 5) {
System.out.println("You have entered The same value.");
}
// Less Than:
else if (a < 5) {
System.out.println("Your number is smaller than 5.");
}
// Greater Than:
else {
System.out.println("You have entered a number greater than 5.");
}
// DONE
}
You can also create method to collect input and make it inside loop like this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("enter a number to compare with number 5: ");
int userInput = getInteger();
if (userInput == 2)
{
System.out.println("U Have Entered The same value");
}
else if (userInput < 2)
{
System.out.println("Ur number is Smaller than 2");
}
else {
System.out.println("U Have Entered the number Greater than 2");
}
}
static int getInteger() {
boolean correct = false;
Scanner input = new Scanner(System.in);
int userInput = 0;
do {
try {
userInput = input.nextInt();
correct = true;
} catch (Exception e) {
System.out.println("Incorrect input");
System.out.println("Please try again: ");
} finally {
input.nextLine();
}
}
while (!correct);
input.close();
return userInput;
}
}
Important note with scanner.nextInt() or scanner.nextDouble()
you need to call scanner.nextLine() after that to clear input. Otherwise you will end up with endless loop.
Use input.nextLine() instead and parse it to a String.
To avoid a ParseException, surround it by using a try { ... } catch() { ... } block.
In the catch block you can e.g. print a message informing the user of the wrong input.
public static void main(String[] args) {
System.out.println("enter a number to compare with number 5 ");
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
try {
int option = Integer.parseInt(userInput);
if (option == 2)
{
System.out.println("U Have Entered The same value");
}
else if (option < 2)
{
System.out.println("Ur number is Smaller than 2");
}
else if (option > 2)
{
System.out.println("U Have Entered the number Greater than 2");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input!");
}
}
Hope this sort of helped!
public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
b = scan.next().charAt(0);
if (Character.toString(b).matches("^[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I have this method that checks whether the input is a letter in the alphabet or not, but I want to make sure that the input from the user is not null and that the user only enters one letter. For example "A" or "a" is a correct char, the problem is if I enter "Abcdef" then it is still true as the first letter is still a valid char. I want to make it so that the user can only enter one char, I think I've done that by using the scanner and charAt(0) but is there a more efficient way to do it, and I'm also not sure how to make it so that the input isn't null.
I've revised your code to do what you wanted:
public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
EDIT
Without scanner (see comments):
public static boolean correctchar(char b, String input) {
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I made couple of changes :
If invalid input ask user to enter again.
Make sure to close the scanner scan.close()
Scanner scan = new Scanner(System.in);
System.out.println("Please enter only one character : ");
String input = scan.next();
while (null == input || input.isEmpty() || input.length() > 1) {
System.out.println("Invaid Input, Please enter only one character : ");
input = scan.next();
}
scan.close();
if (Character.toString(input.charAt(0)).matches("^[a-zA-Z]")) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
public static boolean correctChar() {
try (Scanner scan = new Scanner(System.in)) {
String input = null;
do {
input = scan.next();
if (input != null && input.length() == 1) {
boolean isCorrect = input.matches("[a-zA-Z]");
System.out.println(isCorrect ? "True" : "False");
return isCorrect;
} else {
System.out.println("Insert only one character");
}
} while (true);
}
}
The program checks the user input and determines if it's positive or negative.
How can I catch the error when the user provides an invalid input (non-integer) such as "444h" or "ibi".
I was thinking the final else statement would catch the exception but it does not.
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = scan.nextInt();
scan.close();
if(num > 0)
{
System.out.println(num+" is positive");
}
else if(num < 0)
{
System.out.println(num+" is negative");
}
else if(num == 0)
{
System.out.println(num+" is neither positive nor negative");
}
else
{
System.out.println(num+" must be an integer");
}
}
}
I expect the program to catch the exception and prompt input of a valid integer
Simply wrap your code in a try..catch block.
Full code:
import java.util.Scanner;
import java.util.InputMismatchException;
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
try {
int num = scan.nextInt();
if (num > 0) {
System.out.println(num + " is positive");
} else if (num < 0) {
System.out.println(num + " is negative");
} else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
} catch (InputMismatchException e) {
System.out.println("Error: Value Must be an integer");
}
scan.close();
}
}
Good luck :)
int num = 0;
try{
num =input.nextInt();
}catch(InputMismatchException ex) {
System.out.println("Enter Integer Value Only");
}
You have to write int num = scan.nextInt(); this statement inside try block if you get non-integer value from input then InputMismatchException will arise then catch block will executed.
First off, don't close the Scanner if you plan on using it again during the operation of your application. Once you close it, you will need to restart your application in order to use it again.
As already mentioned, you could utilize a try/catch on the Scanner#nextInt() method:
Scanner scan = new Scanner(System.in);
int num = 0;
boolean isValid = false;
while (!isValid) {
System.out.print("Enter any number: ");
try {
num = scan.nextInt();
isValid = true;
}
catch (InputMismatchException ex) {
System.out.println("You must supply a integer value");
isValid = false;
scan.nextLine(); // Empty buffer
}
}
if (num > 0) {
System.out.println(num + " is positive");
}
else if (num < 0) {
System.out.println(num + " is negative");
}
else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
Or you could use the Scanner#nextLine() method instead which accepts string:
Scanner scan = new Scanner(System.in);
String strgNum = "";
boolean isValid = false;
while (!isValid) {
System.out.print("Enter any Integer value: ");
strgNum = scan.nextLine();
/* See if a signed or unsigned integer value was supplied.
RegEx is used with the String#matches() method for this.
Use this RegEx: "-?\\d+(\\.\\d+)?" if you want to allow
the User to enter a signed or unsigned Integer, Long,
float, or double values. */
if (!strgNum.matches("-?\\d+")) {
System.out.println("You must supply a numerical value (no alpha characters allowed)!");
continue;
}
isValid = true; // set to true so as to exit loop
}
int num = Integer.parseInt(strgNum); // Convert string numerical value to Integer
/* Uncomment the below line if you use the other RegEx. You would have to also
comment out the above line as well. */
// double num = Double.parseDouble(strgNum); // Convert string numerical value to double
if (num > 0) {
System.out.println(num + " is positive");
}
else if (num < 0) {
System.out.println(num + " is negative");
}
else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
Use regex to check if input is a number
import java.util.regex.*;
Pattern.matches("[0-9]+", "123"); // this will return a boolean
I already wrote a code that convert from decimal number to roman number, however, i want it to do opposite way so how can i make it possible? (This is my previous code: http://pastebin.com/QFKi0xJh ) thank you! and here is my code right now.
I am just a beginner so my code is look little bit basic, please apology for that.
public static void main(String[] args) {
// Fill in the body
Scanner in= new Scanner(System.in);
String user = promptUserForNumeral(in);
while (user.length()!=0) {
int numb= convertNumeralToNumber(user);
System.out.println("The numeral "+user+ " is the decimal number "+numb);
user = promptUserForNumeral(in);
}
}
private static String promptUserForNumeral(Scanner inScanner) {
// Fill in the body
System.out.println("Enter a roman numeral (Q to quit): ");
String i = inScanner.nextLine();
while (i.length()>=0) {
if (i.length()==0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
else if ( i.length()==1 && i.charAt(0)=='q' || i.charAt(0)=='Q') {
System.out.println("Goodbye!");
System.exit(0);
}
}
return i;
}
private static int convertNumeralToNumber(String numeral) {
// Fill in the body
int n=0;
if (numeral.equalsIgnoreCase("m")) {
n-=1000;
}
else if (numeral.equalsIgnoreCase("d")) {
n=500;
}
else if (numeral.equalsIgnoreCase("c")) {
n=100;
}
else if (numeral.equalsIgnoreCase("l")) {
n=50;
}
else if (numeral.equalsIgnoreCase("x")) {
n=10;
}
else if (numeral.equalsIgnoreCase("v")) {
n=5;
}
else if (numeral.equalsIgnoreCase("i")) {
n=1;
}
return n;
}
My professor assigned to write a prime number "finder". Where the number you input will display if it's a prime or even number, then display the next prime number. He wants us to give an error message when the wrong input is keyed in. I figured the negative integer portion is simple, but I cannot figure out the character input. Or if the character is not a digit. How would i block non numeric inputs?
Also, the system is supposed to exit at three CONSECUTIVE erroneous inputs. How would I reset the counter? The way i have written the program, if the user makes two errors but the next ones are acceptable, then make another error. (thus not being consecutive.) the program closes.
This is my first programing course so I'm not to savvy in it. Any help would be greatly appreciated.
Also, i have to use scanner, and the two methods.
/**
*
* #param n
* #return
*/
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer = 2;
int counter = 1;
boolean playAgain = false;
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
int n = input.nextInt();
{
//decide is negative
while ( n < 0){
//count counter
counter++;
//give error message
System.out.println("\nInvalid Input! Stike!");
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
n = input.nextInt();
//decide is character
// if ( n != '.'){
//count counter
// counter++;
//give error message
// System.out.println("\nInvalid Input! Strike!");
// }
//decide if count three errors
if (counter == 3){
//display three errors message
System.out.println("Three Strikes! You're Out!");
//close program
System.exit(0);
}
}
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
} else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
{
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
answer = in.nextInt();
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
}
} while (playAgain != false);
}
}
import java.util.Scanner;
public class SOQ5B
{
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer;
int counter = 0;
int n;
boolean playAgain = true;
boolean isNum;
boolean isNum2;
boolean continuePermitted = true;
Scanner input = new Scanner(System.in);
String s;
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
s = input.nextLine();
isNum = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum = false;
}
}
if(isNum)
{
counter = 0;
n = Integer.parseInt(s);
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
}
else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
do
{
continuePermitted = true;
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
s = input.nextLine();
isNum2 = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum2 = false;
}
}
if(isNum2)
{
answer = Integer.parseInt(s);
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
else
{
System.out.println("Incorrect response.");
continuePermitted = false;
//if answering the yes or no question incorrectly is part of the 3 strikes
//then uncomment the following lines of code
/*
counter++;
}
if(counter >= 3)
{
System.out.println("3 strikes you out");
System.exit(0);
*/
}
}while(!continuePermitted);
}
else
{
System.out.print("\nIncorrect input. Number must be a positive integer.\n");
counter++;
}
if(counter>=3)
{
System.out.println("3 strikes and you're out!");
System.exit(0);
}
} while (playAgain != false);
}
}
In the future, I recommend you research your questions on the internet before bringing the question here. There were several other places that could've easily answered your question.
Now as for your actual question, notice how I changed your code at the line that says s = input.nextLine()? What I did there is checked to see if each digit in the string was any number between and including 0-9. Not only was I able to check if they were all numbers, but I was also able to see if they were all positive too as you would have to put a - in order for it to be negative. Along with that, you also have a boolean that only works when the input is a positive number. If not, it checks 3 times to make sure your program doesn't mess up. Furthermore, I even commented out another section that allows the 3 strikes to include if answering the yes no question counts as a strike. If there any other questions, just ask and I will edit my answer.
You are trying to take input using Scanner class with
int n = input.nextInt();
If you enter a character in place of number here you will get java.util.InputMismatchException
What you can do is something like
try {
int n = input.nextInt();
} catch (InputMismatchException e) {
//handle the error scenario where the input is a character
System.out.println("Enter Valid Input");
}