how to check the else statement in if else condition - java

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!

Related

do while loop prompting user for some input

I'm new to do while loops.
I've attempted to create a do-while loop that checks if the users input is an integer or the character x. If it is neither it prompts the user to try again.
The loop instead prompts the user twice:
Intended output:
Enter answer:
500
//program is succesful
Actual output:
Enter answer:
500
//prompts user for more input
Code:
do {
System.out.println("Enter answer: ");
input = scan.next();
if(input.trim().equals("x"))
{
terminate = false;
break;
}
while (!scan.hasNextInt()) {
input = scan.next();
System.out.println(input + " is not a interger!!");
}
operationResult = scan.nextInt();
valid = false;
} while (valid);
You could always use a try...catch but I think this will be better -
do{
if(scan.hasNextInt()){
operationResult = scan.nextInt();
break;
}else if(scan.next().trim().equals("x")){
break;
}else{
System.out.println("Enter an Integer!!");
}
}while(true);
It checks whether its an integer first, so there's no need of a try...catch
You can use as given below:
It will not check for integer value, however it will check for numeric value entered, may this will help
public class SomeClass {
public static void main(String args[]) {
try (Scanner scan = new Scanner(System.in)) {
do {
String str = scan.next();
if (isNumeric(str)) {
System.out.println("Program Ends");
break;
} else if (str.equalsIgnoreCase("x")) {
System.out.println("Program Ends");
break;
} else {
System.out.println("Enter Again");
}
} while (true);
}
}
public static boolean isNumeric(String str) {
return !str.matches(".*[^0-9].*");
}
}

Looping for odd and even number in java

how do i repeatedly ask the user to enter an input until the user enters a negative number. If the user enters a negative number or 0, the program will end?
import java.util.Scanner;
public class OddEvenInt {
public static void main(String args[]) {
Scanner s = new Scanner(System. in );
int x;
do {
System.out.println("Enter an integer to check if it is odd or even ");
x = s.nextInt();
if (x % 2 == 0)
System.out.println("You entered an even number.");
else
System.out.println("You entered an odd number.");
} while (x % 2 == 0);
}
}
You gotta change the while clause :
while (x>0)
use < and >
public static void main(String[] arguments) {
Scanner s = new Scanner(System.in);
int x = 0;
do {
System.out.println("Enter an integer to check if it is odd or even ");
try {
x = Integer.parseInt(s.nextLine());
if (x > 0) {
System.out.println("You entered an even number.");
} else if (x == 0) {
System.out.println("You entered 0, thats not negativ or positiv.");
} else {
System.out.println("You entered an odd number.");
}
} catch (Exception e) {
//e.printStackTrace();
System.out.println("U call this an Integer? :P");
}
} while (x > 0);
return;
}
last edit: check if your input is numberic, if you want to check the error you can remove // from the catch-block

How do i make the program keep looping until the user has entered an integer

i am trying to modify my program so that even when the user has entered a string instead of the program crashing it should keep looping and asking for the user to enter the exam grade which needs to be an integer, only when the user has entered an integer should the program terminate. I am referring to the code in the do-while block
import java.util.InputMismatchException;
import java.util.Scanner;
public class CatchingException {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int score;
String choice;
try {
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
do {
if(score <40) {
System.out.println("You FAILED");
}else if(score >=40 && score <50){
System.out.println("Your grade: PASS MARK");
}else if(score >=50 && score <60) {
System.out.println("Your grade: 2:2");
}else if (score >=60 && score <70) {
System.out.println("Your grade: 2:1");
}else {
System.out.println("Your grade: 1:1");
}
System.out.println("Do you want to enter another grade: ");
choice = scan.next();
if(choice.equalsIgnoreCase("yes")) {
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
System.err.println("Incorrect Input");
}
}while();
}catch(InputMismatchException e) {
System.err.println("Incorrect Input ");
}
System.out.println("program terminated");
scan.close();
}
}
Use a boolean variable to keep track of whether or not to keep looping. For example:
boolean loop = true;
do {
// set loop to false when you want to end
} while(loop);
so you could do:
int score = null;
boolean isInt = false;
do {
System.out.println("Enter your percentage mark:");
try {
score = scan.nextInt();
isInt = true;
} catch (InputMismatchException e) {
//Not An Integer
isInt = false;
}
} while(false)
//Do you if statements here if it gets out of the while loop which means the user entered an int
Instead of assuming the number inputed is an int, you can input it as a String and loop until that string represents an int:
int intScore;
String score;
boolean gotInt = false;
while (!gotInt) {
score = scan.next();
try {
intScore = Integer.valueOf(score);
gotInt = true;
} catch (NumberFormatException e) {
// output some warning
}
}
Did you consider using JOptionPane to get an input from the user? It is able to display a little window with a text field and a OK and Cancel button which would fit your needs perfectly.
Here is the documentation for JOptionPane#showInputDialog:
static String showInputDialog(Component parentComponent, Object message, String title, int messageType)
Shows a dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType.

How to make the code run reversly? from Roman number to decimal number

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

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