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();
}
}
Related
I'm a total beginner and am working on a practice assignment. I need to be able to re-print the same addition problem if the user has answered incorrectly, but I'm not sure how to do that. All my attempts have lead to a new random addition problem appearing or adding another new random to the original, which is also not desired. I'm sure it's simple, but I am lost. Thanks in advance for any tips!
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do {
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b)) {
System.out.println("CORRECT!");
} else if (ans==0) {
System.out.println("Good bye!");
} else if (ans!=(a+b)) {
System.out.println("Incorrect, try again.");
}
} while (ans!=0);
}
}
Just simplify your code a little bit, don't overthink. You generate answers every time you get into the loop, generate your numbers outside so they stay consistent, also, a do-while, isn't necessary, just break your loop if the answer is correct or they placed 0. Also, you need to make sure that the user entered a number, so a try-catch should be placed while getting the input.
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
int ans;
while (true) {
System.out.printf("%d + %d = ?%n", a, b);
try {
ans = Integer.parseInt(input.next());
} catch (NumberFormatException e) {
System.out.println("Please enter a number!");
continue;
}
if (ans == 0) {
System.out.println("Goodbye!");
break;
} else if (ans == a + b) {
System.out.println("Correct!");
break;
} else {
System.out.println("Incorrect!");
}
}
Please see modification inline:
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
// here you keep asking the user over and over
//until they give the right result
do{
System.out.println("Incorrect, try again.");
//show again the equation to the user
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
}while(ans!=(a+b));
}
}
while (ans!=0);
}
}
Use this simple source code and similar to you (minor change):
try (Scanner input = new Scanner(System.in)) {
Random rand = new Random();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans, a, b;
ans = a = b = 0;
do {
a = rand.nextInt(10) + 1;
b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b + " = ");
try{
//Getting input as String and casting to Integer
ans = Integer.parseInt(input.nextLine());
if (ans == 0) {
System.out.println("Good bye!");
} else if (ans == (a + b)) {
System.out.println("CORRECT!");
} else if (ans != (a + b)) {
System.out.println("Incorrect, try again.");
}
}catch (NumberFormatException nfe){
System.out.println(nfe);
}
} while (ans != 0);
}
class generateNum{
Random rand = new Random ();
int a=rand.nextInt(10)+1;
int b=rand.nextInt(10)+1;
public void generate(){
System.out.print(a + " + " + b +" = ");
}
public int getsum(){
return a+b;
}
}
public class Test02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
generateNum gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
int com=gnum.getsum();
do
{
if (ans==com)
{
System.out.println("CORRECT!");
gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
com=gnum.getsum();
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=com)
{
System.out.println("Incorrect, try again.");
gnum.generate();
ans = input.nextInt();
}
}
while (ans!=0);
}
}
There are few changes in your condition. Update your else-if(ans!=(a+b)) block.
import java.util.Random;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
boolean flag = false;
do{
System.out.println("Incorrect, try again.(0 for skip)");
int againAns = input.nextInt();
if(againAns == (a+b)){
System.out.println("CORRECT!");
flag = true;
}else if(againAns == 0){
System.out.println("You skip the answer..");
flag = true;
}
}while(flag != true);
}
}while (ans!=0);
}
}
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");
}
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 am an absolute beginner, no experience in any programming language.
I wrote a program as an exercise for converting Arabic numbers to Roman numbers. It works. However I want to add a part for dealing with problem if a string is entered instead of integer. And don't know how to do this. I tried to use try/catch, but I don't know how to use it correctly. Now the program asks me twice to enter a number. What to do?
Here is he main method:
public static void main(String[] args) {
int numArabic;
boolean validEntry;
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
} catch (InputMismatchException e) {
System.out.println("Entered value is not an integer!");
}
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
if ((numArabic < 1) || (numArabic > 3999)) {
System.out.println();
System.out.print("Wrong number. ");
System.out.print("Enter an integer number between 1 and 3999!");
System.out.println();
}
else {
String numRoman1 = toRomanOne(numArabic % 10);
String numRoman2 = toRomanTwo(((numArabic / 10) % 10));
String numRoman3 = toRomanThree(((numArabic / 100) % 10));
String numRoman4 = toRomanFour(numArabic / 1000);
System.out.print("The number " + numArabic + " is equal to: ");
System.out.print(numRoman4+numRoman3+numRoman2+numRoman1 + ".");
}
}
Your control mechanism is true but only works once. You have to put it inside a loop so that it can allow user to enter an integer at last.
boolean validEntry;
do {
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
}
catch (InputMismatchException e) {
validEntry = false;
System.out.println("Entered value is not an integer!");
}
}
while(!validEntry);
You can use Scanner#hasNextInt() method to check that.
This method returns true if the next token in this scanner's input can be interpreted as an int value.
if (scan.hasNextInt()) {
// Do the process with Integer.
} else {
// Do the process if it is not an Integer.
}
Note that, this will cover all the Inputs which are not Integer, not only String.
public static void main(String[] args) {
int numArabic;
boolean validEntry = false;
while (validEntry = false){
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
}
catch (InputMismatchException e) {
System.out.println("Entered value is not an integer!");
validEntry = false;
}
}
if ((numArabic < 1) || (numArabic > 3999)) {
System.out.println();
System.out.print("Wrong number. ");
System.out.print("Enter an integer number between 1 and 3999!");
System.out.println();
}
else {
String numRoman1 = toRomanOne(numArabic % 10);
String numRoman2 = toRomanTwo(((numArabic / 10) % 10));
String numRoman3 = toRomanThree(((numArabic / 100) % 10));
String numRoman4 = toRomanFour(numArabic / 1000);
System.out.print("The number " + numArabic + " is equal to: ");
System.out.print(numRoman4+numRoman3+numRoman2+numRoman1 + ".");
}
}
Try This :
boolean b=true;
while(b)
{
try
{
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
}
catch (InputMismatchException e)
{
System.out.println("Entered value is not an integer!");
}
if(validEntry)
{
if ((numArabic < 1) || (numArabic > 3999))
{
System.out.println();
System.out.print("Wrong number. ");
System.out.print("Enter an integer number between 1 and 3999!");
System.out.println();
}
else
{
String numRoman1 = toRomanOne(numArabic % 10);
String numRoman2 = toRomanTwo(((numArabic / 10) % 10));
String numRoman3 = toRomanThree(((numArabic / 100) % 10));
String numRoman4 = toRomanFour(numArabic / 1000);
System.out.print("The number " + numArabic + " is equal to: ");
System.out.print(numRoman4+numRoman3+numRoman2+numRoman1 + ".");
}
b=false;
}//end of if
}//end of while
Try this,
you need to initialize numArabic to some value first.
public static void main(String[] args) {
int numArabic = 0;
boolean validEntry;
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
}
catch (InputMismatchException e) {
System.out.println("Entered value is not an integer!");
}
if ((numArabic < 1) || (numArabic > 3999)) {
} else {
}
}
The Program what you entered is free from syntax errors and logical errors.But for asking only one time to enter the integer value just rewrite the code as following.We are attaching second sop function in catch block.So if the input is mismatch it will ask for again re-enter.
public static void main(String[] args) {
int numArabic;
boolean validEntry;
try {
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
validEntry = true;
} catch (InputMismatchException e) {
System.out.println("Entered value is not an integer!");
System.out.println("Enter an integer number between 1 and 3999!");
Scanner scan = new Scanner(System.in);
numArabic = scan.nextInt();
}
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;
}