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.
Related
i keep getting a ';' is expected at the checkBinary(String num) { ^ error, yet i can't find any place for a ";". I have only been studying java for a few days so the problem could be something obvious i haven't learnt yet. Please provide a detailed explanation in way i could use it to prevent the problem in later projects. Thank you in advance!
import java.io.*;
import java.util.Scanner;
public class checkbinary
{
public static void main(String[] args)
{
String num;
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
num = sc.nextLine();
if(checkBinary(num)) {
System.out.println("The number is: Binary");
} else {
System.out.println("The number is: Not Binary");
}
boolean checkBinary(String num) {
for(i=0;i<num.length();i++) {
digit = Integer.parseInt(num.substring(i,i+1));
if(digit > 1) {
return false;
}
}
return true;
}
}
You need to move your checkBinary method outside of the main method. You cannot nest methods in java without declaring an inner class.
This should work:
import java.io.*;
import java.util.Scanner;
public class checkbinary
{
public boolean checkBinary(String num) {
for(i=0;i<num.length();i++) {
digit = Integer.parseInt(num.substring(i,i+1));
if(digit > 1) {
return false;
}
}
return true;
}
public static void main(String[] args)
{
String num;
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
num = sc.nextLine();
if(checkBinary(num)) {
System.out.println("The number is: Binary");
} else {
System.out.println("The number is: Not Binary");
}
}
}
If you want to know how to go about solving this with a nested class, there are numerous other questions/examples on SO. Like this one Can methods in java be nested and what is the effect? or In java what are nested classes and what do they do?
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.
import java.util.Scanner;
public class Two {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
boolean userReady=false;
do{
System.out.println("y/n")
String userinput = input.nextLine();
if (userinput.equals("y")){
userReady = true;
}else if (userinput.equals("n")){
userReady = false;
}
}while (userReady = false);
System.out.println("You are ready!");
}
}
result is always "You are ready" im sure its a super simple fix that i just cant get my head around...
You are running while(userReady = false); instead of while(userReady == false);. This is not checking for condition, just assigning a value.
Because System.out.println("You are ready!"); is not under any condition or loop.
Its a separate last statement.
Just move the print in the condition where you press y.
public class Two {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
boolean userReady=false;
do{
System.out.println("y/n")
String userinput = input.nextLine();
if (userinput.equals("y")){
userReady = true;
System.out.println("You are ready!");
}else if (userinput.equals("n")){
userReady = false;
}
}while (userReady = false);
}
}
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
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
}
}