While loop wont stop looping with exception - java

probably missing something really silly, but my while loop will not stop printing the error message.
Could someone have a quick look and point me in the right direction?
package week5;
import java.util.*;
public class Week5 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
inputInt();
}
public static int inputInt(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter number:");
int num;
boolean carryOn = true;
while (carryOn = true) {
{
try {
num = myKeyboard.nextInt();
carryOn = false;
}
catch (Exception e) {
System.out.println ("Integers only");
}
}
}
return 0;
}

This line is the problem
while (carryOn = true) {
Instead of using the comparison operator ==, you are using the assignment operator =. So essentially, you're setting carryOn to true every iteration, then automatically running the body of the loop since the condition essentially becomes
while (true) {
Just change that problem line to
while (carryOn == true) {

Apart from the infinite loop and the fact you always return 0; no matter what the user types, the code is far more complex than it needs to be.
// only create one scanner
private static final Scanner myKeyboard = new Scanner(System.in);
public static void main(String[] args) {
int num = inputInt();
// do something with num
}
public static int inputInt() {
System.out.println("Enter number:");
while (true) {
if (myKeyboard.hasNextInt()) {
int num = myKeyboard.nextInt();
myKeyboard.nextLine(); // discard the rest of the line.
return num;
}
System.out.println ("Integers only, please try again");
}
}

In your case:
while(carryOn==true)
or
while(carryOn)
will solve your problem

Related

if else statement along with try catchblock throwing an error

//Program to Check the given Number is an odd or even number
import java.util.Scanner;
public class EvenOddNo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check \"Even or Odd\" number");
int k = sc.nextInt();
String j =getNo(k);
System.out.println(j);
sc.close();
}
static public String getNo(int n) // Throwing an error *This method must return a result of type String*
{
try {
if(n%2==0) {
return n+" is an Even number";
}
else
return n+" is an Odd Number";
}catch(ArithmeticException ae) {
ae.printStackTrace();
}
}
}
What happens if your try block throws an ArithmeticException? So you are missing a return statement. You have to add one, preferable as a default one after the try-catch.

How to resolve InputMismatchException?

package exercises;
import java.util.*;
public class Try_and_catch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=1;
do
{
System.out.println("Enter first number");
int n1 = input.nextInt();
System.out.println("Enter second number");
int n2 = input.nextInt();
int sum= n1/n2;
System.out.println(sum);
} while(x==1);
}
}
The code above requires input only integers, my question is how to handle the error whenever the user input a character?
Use a try block:
boolean again = true;
int n1;
while (again) {
try {
System.out.println("Enter first number");
input.nextInt();
again=false;
}
catch(InputMismatchException ime)
{
// do nothing!
}
}
What happens here is pretty simple: if we get an exception, then "again" is not set to true and we go back around in the loop. If we get out of the try block without an exception, then again is toggled and we go merrily on our way.

How can I check if an input is a integer or String, etc.. in JAVA?

I am wondering how I can check if a user's input is a certain primitive type (I mean integer, String, etc... I think it's called primitive type?). I want a user to input something, then I check if it's a String or not, and do a certain action accordingly. (JAVA)
I have seen some codes like this:
if (input == (String)input) { (RANDOM STUFF HERE) }
or something like
if input.equals((String) input)
And they don't work. I want to know how I can Check for only a String? (EDITED OUT)
I was wondering if there was a function that can do that? Thanks for the answers
EDIT: With the help of everyone I have created my fixed code that does what I want it to:
package files;
import java.util.*;
public class CheckforSomething {
static Scanner inputofUser = new Scanner(System.in);
static Object userInput;
static Object classofInput;
public static void main(String[] args){
try{
System.out.print("Enter an integer, only an integer: ");
userInput = inputofUser.nextInt();
classofInput = userInput.getClass();
System.out.println(classofInput);
} catch(InputMismatchException e) {
System.out.println("Not an integer, crashing down");
}
}
}
No need for answers anymore, thanks!
Use instanceof to check type and typecast according to your type:
public class A {
public static void main(String[]s){
show(5);
show("hello");
}
public static void show(Object obj){
if(obj instanceof Integer){
System.out.println((Integer)obj);
}else if(obj instanceof String){
System.out.println((String)obj);
}
}
}
You may try this with Regex:
String input = "34";
if(input.matches("^\\d+(\\.\\d+)?")) {
//okay
} else {
// not okay !
}
Here,
^\\d+ says that input starts with a digit 0-9,
()? may/or may not occur
\\. allows one period in input
Scanner input = new Scanner (System.in);
if (input.hasNextInt()) System.out.println("This input is of type Integer.");
else if (input.hasNextFloat()) System.out.println("This input is of type Float.");
else if (input.hasNextLine()) System.out.println("This input is of type string.");
else if (input.hasNextDouble()) System.out.println("This input is of type Double.");
else if (input.hasNextBoolean()) System.out.println("This input is of type Boolean.");
else if (input.hasNextLong())
System.out.println("This input is of type Long.");
Hate to bring this up after 6 years but I found another possible solution.
Currently attending a coding bootcamp and had to solve a similar problem. We introduce booleans and change their values depending on the result of the try/catch blocks. We then check the booleans using simple if statements. You can omit the prints and input your code instead. Here's what it looks like:
import java.io.IOException;
import java.util.Scanner;
public class DataTypeFinder {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
String input = "";
while (true) { //so we can check multiple inputs (optional)
input = scan.nextLine();
if ("END".equals(input)) { //a way to exit the loop
break;
}
boolean isInt = true; //introduce boolean to check if input is of type Integer
try { // surround with try/catch
int integer = Integer.parseInt(input); //boolean is still true if it works
} catch (NumberFormatException e) {
isInt = false; //changed to false if it doesn't
}
boolean isDouble = true; //same story
try {
double dbl = Double.parseDouble(input);
} catch (NumberFormatException e) {
isDouble = false;
}
if (isInt) {
System.out.printf("%s is integer type%n", input);
} else if (isDouble) {
System.out.printf("%s is floating point type%n", input);
} else if (input.length() == 1) { //this could be useless depending on your case
System.out.printf("%s is character type%n", input);
} else if ("true".equals(input.toLowerCase()) || "false".equals(input.toLowerCase())) {
System.out.printf("%s is boolean type%n", input);
} else {
System.out.printf("%s is string type%n", input);
}
}
}
}
class Main{
public static void main(String args[]){
String str;
Scanner sc=new Scanner(System.in);
int n,
boolean flag=false;
while(!flag){
try{
str=sc.nextLine();
n=Integer.parseInt(str);
flag=true;
}
catch(NumberFormatException e){
System.out.println("enter an no");
str=sc.nextLine();
}
}
}
}
Is this ok?
class Test
{
public static void main(String args[])
{
java.util.Scanner in = new java.util.Scanner(System.in);
String x = in.nextLine();
System.out.println("\n The type of the variable is : "+x.getClass());
}
}
Output:
subham#subham-SVE15125CNB:~/Desktop$ javac Test.java
subham#subham-SVE15125CNB:~/Desktop$ java Test
hello
The type of the variable is : java.lang.String
But Zechariax wanted an answer with out using try catch
You can achieve this using NumberForamtter and ParsePosition.
Check out this solution
import java.text.NumberFormat;
import java.text.ParsePosition;
public class TypeChecker {
public static void main(String[] args) {
String temp = "a"; // "1"
NumberFormat numberFormatter = NumberFormat.getInstance();
ParsePosition parsePosition = new ParsePosition(0);
numberFormatter.parse(temp, parsePosition);
if(temp.length() == parsePosition.getIndex()) {
System.out.println("It is a number");
} else {
System.out.println("It is a not number");
}
}
}
Try instanceof function with Integer instead of int.. each primitive also have a class

I am Facing issues in Scanner Class in java

If I enter the wrong input(example , if I enter String instead of Integer) loop is not ending, it wont get input next time. Here(below) i attach the entire program. can you please help this?. Thanks in advance!!!
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* If we enter the wrong input(example , if we enter sting instead of integer) it goes unending loop
*
* #author Nithish
*
*/
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
e.printStackTrace();
}
}
}
}
On an InputMismatchException you are doing i--, so the loop condition is modified to prevent the loop from ending without the needed input. If you read the API documentation for Scanner.nextInt() you should notice the following:
If the translation is successful, the scanner advances past the input that matched.
This means that if the input cannot be translated to int, the scanner does not advance. So on the next invocation of nextInt() it will re-read the exact same, non-int, input and fail again. You will need to read past that non-integer token before attempting to get an int again.
Again, don't mess with the loop index inside of the loop as this can cause problems down the road. Instead use a while loop which is much cleaner and much easier to debug 3 months from now:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean done = false;
int result = 0;
while (!done) {
try {
System.out.print("Enter the value: ");
String temp = scanner.nextLine();
result = Integer.parseInt(temp);
done = true;
} catch (NumberFormatException e) {
System.out.println("Please only enter integer data");
}
}
scanner.close();
}
}
what about the below?
Scanner sc = new Scanner(System.in);
while (!sc.hasNext()) {
System.out.println("Enter the value");
if (src.hasNextInt()) {
i = src.nextInt();
System.out.println("Thank you! (" + i+ ")");
}
else
{
System.out.println("Please only int");
}
}
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
//e.printStackTrace();
scanner.nextLine(); //you can add this here.
//scanner.next(); you can also use this
}
}

Looping Forever

I'm trying to loop an exception, but for some reason its not giving me the option to re write my scanner file:
I don't know how to use BufferedReader so that's why I'm using this. Any clues?
Here's my standard class with my method
package arrayExceptionsWithInput;
import java.util.*;
public class GetThoseNumbersBaby {
int firstInt;
int secondInt;
boolean error;
Scanner yourNumbers = new Scanner(System.in);
public void findNumbers()
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
}
}
And here's my main class with the exception being implemeted with a loop:
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
GetThoseNumbersBaby zack = new GetThoseNumbersBaby();
{
do {
try
{
zack.findNumbers();
}
catch(InputMismatchException Q)
{
System.out.println(" one of your integers was incorrect, please try again");
Q.printStackTrace();
error = true;
}
} while (error == true);
}
error = false;
}
}
If anyone has any ideas on how to loop this differently I'm all ears.
Set error false before the action. That way you have the correct exit condition if the user gets it right.
error = false;
zack.findNumbers();
i decided too get rid of the method class
and just put the method into the try exception area.
used a .nextLine after scanner and it seems fixed.
this looks ok?
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
int firstInt;
int secondInt;
Scanner yourNumbers = new Scanner(System.in);
{
do{
try
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
yourNumbers.nextLine();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
yourNumbers.nextLine();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
yourNumbers.nextLine();
}
catch(InputMismatchException Q)
{
Q.printStackTrace();
System.out.println(" one of your integers was incorrect, please try again");
error = true;
yourNumbers.nextLine();
}
}while (error == true);
}error = false;
}
}
You loop while 'error' variable has value 'true'. However, it becomes 'true' only when the is thrown (i.e. when 'catch' block is executed). Control flow doesn't reach it.

Categories