Keep getting syntax error, insert while expression to complete do statement. It maybe something simple like curly brackets etc.
{
int num = 0;
//flag
boolean inputOk = false;
Scanner s = new Scanner (System.in);
do {
try {
System.out.println("Enter a number....");
num =s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}
} while (inputOk != true);
s.close();
System.out.println("Thank you");
}
In your code you are missing ending curly brackets "}" for do. For Scanner it's better to use try with resource. here is working code
int num = 0;
//flag
boolean inputOk = false;
try (Scanner s = new Scanner(System.in)) {
do {
try {
System.out.println("Enter a number....");
num = s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}
}
while (inputOk != true);
}
System.out.println("Thank you");
You are missing ending curly brackets "{" of Do I have corrected it in below code
int num = 0;
//flag
boolean inputOk = false;
Scanner s = new Scanner (System.in);
do {
try {
System.out.println("Enter a number....");
num =s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}} while (inputOk != true);
{
s.close();
System.out.println("Thank you");
}
Related
I'm a novice java programmer and need to adjust this code so it catches two strings instead of variables.
Here is the original code we are supposed to use:
import java.util.Scanner;
import java.util.InputMismatchException;
public class Part4 {
public static void main(String[] args) {
int userNum = 0;
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
String dump = null;
while (!inputOK) {
System.out.print("Enter a number: ");
try {
userNum = screen.nextInt();
dump = screen.nextLine();
inputOK = true;
} catch (InputMismatchException e) {
dump = screen.nextLine();
System.out.println("\"" + dump + "\" is not a legal integer, " +
"please try again!");
} // end try-catch block
} // end input loop
screen.close();
userNum = userNum + 20;
System.out.println("Your number plus 20 is " + userNum);
}
}
and here is my failed attempt:
import java.util.Scanner;
import java.util.InputMismatchException;
public class testClass {
public static void main(String[] args) {
String letter = new String();
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
String dump = null;
while (!inputOK) {
System.out.print("Enter ('y' or 'n': )");
try {
letter = screen.nextLine();
dump = screen.nextLine();
inputOK = true;
} catch (InputMismatchException e) {
dump = screen.nextLine();
System.out.println("\"" + dump + "\" is not a legal letter, " +
"please try again!");
}
}
screen.close();
System.out.println("That is a valid letter");
}
}
If anyone could help that would be much appreciated.
Thanks :)
First off InputMismatchException will only be thrown
to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
Since anything but y and n are still String's this won't be thrown. Instead you can throw a new InputMismatchException if it is not y or n:
String letter = new String();
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
while (!inputOK) {
System.out.println("Enter ('y' or 'n': )");
try {
letter = screen.nextLine();
if(!letter.equals("y") && !letter.equals("n")) {
throw new InputMismatchException();
}
inputOK = true;
} catch (InputMismatchException e) {
System.out.println("\"" + letter + "\" is not a legal letter, " +
"please try again!");
}
}
System.out.println("That is a valid letter");
Also it is not good practice to close System.in. The general rule is if you did not open a resource, you should not close it
I was having some problem when try to try catch the IndexOutOfBoundsException for a List in Java. So I declared my list with 2 elements as:
List<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
Then I tried to do a try catch:
do {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + (i + 1) + ")" + list.get(i));
}
System.out.println(" ");
try{
option = sc.nextInt();
} catch (IndexOutOfBoundsException e){
System.out.println("Invalid option");
sc.next();
continue;
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
sc.next();
continue;
}
sc.nextLine();
if (option == 1) {
System.out.print("Enter name: ");
// scanner takes in input
} else if (option == 2) {
System.out.print("Enter desc: ");
// scanner takes in input
}
type = list.get((option - 1));
} while (option <= 0 || option >= 3);
However, when I entered anything larger than 2 for option, it threw me IndexOutOfBounds exception but I thought I did a try catch for it already?
Thanks in advance.
do {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + (i + 1) + ")" + list.get(i));
}
System.out.println(" ");
try {
option = sc.nextInt();
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
sc.next();
continue;
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
sc.next();
continue;
}
sc.nextLine();
if (option == 1) {
System.out.print("Enter name: ");
// scanner takes in input
} else if (option == 2) {
System.out.print("Enter desc: ");
// scanner takes in input
}
try {
type = list.get((option - 1));
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
option=3;
}
} while (option <= 0 || option >= 3);
I have added new try-catch at type = list.get((option - 1));
To force user re-input option, I will set option to 3 at the catch cause
You are not going to catch the exception if you don't use an invalid value to call the list.
ArrayList<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
Scanner sc = new Scanner(System.in);
int option;
try {
option = sc.nextInt();
System.out.println(list.get(option));
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
}
sc.close();
You also can do it like this, it will loop till you enter a valid value and after a valid value is entered ask for name or whatever(not implemented)
ArrayList<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
Scanner sc = new Scanner(System.in);
int option = 0;
while(!(option == 1 || option==2) ) {
try {
option = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
}
}
System.out.println(list.get(option-1));
sc.close();
I was able to implement the function of the try - catch for the variable choice and it works great. I have a problem with variable stopnie. I want to check if this is numerical value. I tried to throw it in the try catch, unfortunately without success
class Task {
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
System.out.println("Pick 1 to convert Fahrenheit to Celsius");
System.out.println("Pick 2 to convert Ceslius to Fahrenheit");
int choice = 0;
double stopnie = 0.0;
double convert = 0.0;
DecimalFormat df = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.US));
boolean loop = true;
while (loop)
{
try
{
choice = user_input.nextInt();
loop = false;
}
catch (Exception e)
{
System.out.println("Bad value");
System.out.println("Try again");
user_input.next();
}
}
if(choice == 1)
{
System.out.println("Let me know Celsius value");
stopnie = user_input.nextDouble();
convert = stopnie/1.8-35;
System.out.println(stopnie + " C " + " = " + df.format(convert) + " F");
}
else if (choice == 2)
{
System.out.println("Let me know Fahrenheit value");
stopnie = user_input.nextDouble();
convert = stopnie*1.8+35;
System.out.println(stopnie + " F " + " = " + convert + " C");
}
else
{
System.out.println("Bad value");
}
}
}
so, I added try catch to if(choice == 1): with while loop
if(choice == 1)
{
while (loop)
{
try {
System.out.println("Let me know Celsius value");
stopnie = user_input.nextDouble();
convert = stopnie/1.8-35;
System.out.println(stopnie + " C " + " = " + df.format(convert) + " F");
} catch (Exception e) {
System.out.println("Bad value");
System.out.println("Try again");
user_input.next();
}
}
}
Now, when I start program and Pick 1 nothing happens. I want to pick 1, go to function if(chooice ==1) and if there will be any error print Bad value, try again and add input to put value again
try this code:
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
try {
int f=user_input.nextInt();
System.out.println("It's an Integer");
} catch (InputMismatchException e) {
System.out.println("It's not Integer");
// Should print the exception
//e.printStackTrace();
}
}
so what I am trying to do is have the user input a valid coordinate in a matrix, that is an INT which is greater than -1,
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
while (((coordinates[1]<0)||(coordinates[1]>C)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
the problem is that it loops endlessly after entering a not valid input
int R is the size of the row
int C is the size of the collumn
Your problem is that you're not handling the error you're catching.
If you'll provide wrong format of number for the nextInt() method, then the InputMismatchException will be thrown. Then because the catch does nothing, the loop will continue (start from begining) and the scanner will read the same incorrect value, and so on...
So instead of this:
catch (InputMismatchException e) {
}
Try this:
catch (InputMismatchException e) {
System.out.println("Wrong number entered.");
scanner.nextLine();
}
This way you'll force scanner to move past the last incorrect input.
EDIT:
You're loop is also broken because you do break after reading the input. In that case if you'll put the negative number you'll break as well and won't check the loop condition. Remove the break statement and it will work as expected:
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
EDIT2:
public static void main(final String args[])
{
int maxRowsNumber = 10;
int maxColsNumber = 10;
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>maxRowsNumber)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
while (((coordinates[1]<0)||(coordinates[1]>maxColsNumber)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
System.out.println("Inserted RowsNumber: " + coordinates[0]);
System.out.println("Inserted RowsNumber: " + coordinates[1]);
}
Output:
Please enter a valid row number: 11
Please enter a valid row number: 22
Please enter a valid row number: 10
Please enter a valid col number: 11
Please enter a valid col number: 2
Inserted RowsNumber: 10
Inserted RowsNumber: 2
If by "not valid input" you mean "not any kind of integer", then your scanner will fail each time it tries to read another integer, so you'll hit your catch, and do nothing to stop the loop. Maybe you intended to set check to false in such circumstances? Or maybe you meant to put the break in each catch?
Using a break when a valid integer is read isn't right, because it might be a negative integer, which your loop guard says you don't want.
This is basically the same as what your doing, I just tried to improve it a little bit by removing hardcoded values, made variables more descriptive, and included input validations.
final int ROW = 0;
final int COL = 1;
int coordinates[] = new int[2];
coordinates[ROW] = -1;
coordinates[COL] = -1;
boolean isInputValid = true;
Scanner scanner = new Scanner(System.in);
do {
try {
System.out.print("Please enter a valid row number:\t");
coordinates[ROW] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false; //if the input is not int
}
} while (!isInputValid && (coordinates[ROW] < 0) //do this until the input is an int
|| (coordinates[ROW] > R)); //and it's also not less than 0 or greater than R
//same logic applies here
do {
try {
System.out.print("Please enter a valid col number:\t");
coordinates[COL] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false;
}
} while (!isInputValid && (coordinates[COL] < 0)
|| (coordinates[COL] > C));
Hope this helps.
I want to handle NumberFormatException in more specific way.
This exception occurs, when it tries assign anything but an integer, when the following is entered:
string
character
empty input
double number
Depending on what was entered I want to display a proper message, like
you've entered string, please enter an integer
or
value can't be null, please enter an integer value
The code below catches NumberFormatException in general way.
I wonder is there a way to include more catch clauses.
import java.util.Scanner;
public class TestException {
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
try {
input = Integer.parseInt(scan.next());
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
System.out.println("You've entered non-integer number");
System.out.println("This caused " + e);
}
}
}
First take the input from the user and after that try to convert it to integer.
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
String inputString = scan.next();
try {
input = Integer.parseInt();
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
if(inputString.equals("") || inputString == null) {
System.out.println("empty input");
} else if(inputString.length == 1) {
System.out.println("char input");
} else {
System.out.println("string input");
}
}
}
You've to use if-else construct to specify your scenerios within catch block.
See the code below:
String inString = null;
try
{
iString = scan.next().trim();
input = Integer.parseInt(inString);
System.out.println("You've entered number: " + input);
}
catch (NumberFormatException e)
{
if(inString.equals("")
{
System.out.println("You've entered empty string.");
}
else if(inString.length() == 1)
{
System.out.println("You've entered a single char");
}
else
{
System.out.println("You've entered non-intereger number");
}
System.out.println("This caused " + e);
}
You could do some more tests on the input if parsing the input as an integer value caused an exception, something like this:
String scanned = null
try {
scanned = scan.next();
input = Integer.parseInt(scanned);
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
if (scanned == null || scanned.isEmpty()) {
System.out.println("You didn't enter any value");
} else if (scanned.length() == 1)
System.out.println("You entered a single char which is not a number");
}
// and more tests, you can even try to parse as Double
}
String aString = null;
aString = scan.next().trim();
System.out.println("You've entered number: " + aString);
if("".equals(aString.trim())){
System.out.println("You have entered an Empty String");
}else if(!isNumber(aString) && aString.length()==1){
System.out.println("You have entered a Character");
}else if(!isNumber(aString) && aString.length()>1){
System.out.println("You have entered a String");
}else if(isNumber(aString)){
int input = Integer.parseInt(aString.replaceAll(",",""));
System.out.println("You have entered a correct Number"+input);
}
private boolean isNumber(String s){
return s.matches("[0-9]+(,[0-9]+)*,?");
}
public static int isInt(){
boolean ok=false;
int b=1;
do{
String next = sc.next();
int a=b;
try{
a = Integer.parseInt(next);
}catch(Exception e){
System.out.println("Invalid Option...");
continue;
}
if(a==1){b=a;ok=true;}
else if(a==2){b=a;ok=true;}
else if(a==3){b=a;ok=true;}
}while(!ok);
return b;
}