Using Temporary Value in If Statement to Proceed to Try Catch - java

I need values inputted into the array to be from 1-100 and not any letters. I tried to set up a temporary value that will catch numbers that are not 1-100 before but can not seem to get it to work. I come to problems where the program will close if letters are inputted. Any help would be appreciated.
public class FocusGroup {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double tempValue = scan.nextDouble();
if (tempValue > 100 || tempValue < 0) {
scan.nextDouble();
System.out.println("Invalid");
} else {
while (true) {
try {
double sumFocus = 0;
double[] arrayFocus = new double[2];
for (int i = 0; i < 2; i++) {
arrayFocus[i] = scan.nextDouble();
}
for (double num : arrayFocus) {
sumFocus = sumFocus + num;
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input");
scan.nextLine();
}
}
}
}
}

In your catch statements, you use scan.nextLine(), but you should use scan.nextDouble(), like you do in your main loop. That is, you want to accept doubles as input.
Also, your try/catch syntax seems to be wrong. You want to catch errors that can be caused by user input; therefore, you need to add the code where the user inputs something in the try block. See below:
try {
double tempValue = scan.nextDouble();
//this loop will keep spinning, until tempValue is valid
while (tempValue > 100d || tempValue < 0d) {
System.out.println("Invalid. Try again. Range is 0 - 100");
tempValue = scan.nextDouble();
}
//this loop will spin forever (There is nothing to terminate it)
while (true) {
double sumFocus = 0;
double[] arrayFocus = new double[2];
for (int i = 0; i < 2; i++) {
arrayFocus[i] = scan.nextDouble();
}
for (double num : arrayFocus) {
sumFocus = sumFocus + num;
}
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input");
scan.nextDouble(); //this doesn't do anything. The value is not assigned to any variable
}
With the above code, when the user enters an invalid characters, e.g: an alphabet letter, then the program will stop. Why? Because the catch is outside the endless loop, which makes your program counter move outside the loop and when the code in the catch statement is executed, your program will also terminate as it reached the end.
What you can do, is something like this:
static double validValueWithRange(Double min, Double max){
Scanner s = new Scanner(System.in);
System.out.println("Enter a valid value for a 'double': ");
double value;
try {
value = s.nextDouble();
if(value > max || value < min){
System.out.println("Invalid. Try again. Range is 0 - 100");
return validValueWithRange(min, max);
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input. Try again.");
return validValueWithRange(min, max);
}
return value;
}
static double validValue(){
Scanner s = new Scanner(System.in);
System.out.println("Enter a valid value for a 'double': ");
double value;
try {
value = s.nextDouble();
}
catch (InputMismatchException e) {
System.out.println("Invalid input. Try again.");
return validValue();
}
return value;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
double tempValue = validValueWithRange(0d, 100d);
while (true) {
System.out.println("Now entering endless while loop");
double sumFocus = 0;
double[] arrayFocus = new double[2];
for (int i = 0; i < 2; i++) {
arrayFocus[i] = validValue();
}
for (double num : arrayFocus) {
sumFocus = sumFocus + num;
}
}
}

You just have to put the initialization of the variable in a try and catch block like this:
try {
double tempValue = scan.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Please enter a number.");
}

Related

How to validate these inputs?

I wrote a simple program.it gets two Integer number from user and return odd numbers to user.i validate them to force the user to type just Integer numbers.
when user type other data type,program gives him my custom error.that is right up to now but when this happen user has to type inputs from the beginning.it means that program takes the user to the first home.
here is my main class :
package train;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean isNumber;
do {
System.out.println("enter number1 please : ");
if (input.hasNextInt()) {
number1 = input.nextInt();
isNumber = true;
System.out.println("enter number2 please : ");
}
if (input.hasNextInt()) {
number2 = input.nextInt();
isNumber = true;
} else {
System.out.println("wrong number!");
isNumber = false;
input.next();
}
} while (!(isNumber));
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
}
and here is my calculate class which return odd numbers :
public class Calculate {
private int minNumber;
private int MaxNumber;
public void setNumbers(int min, int max) {
this.minNumber = min;
this.MaxNumber = max;
}
public void result() {
int count = 0; // number of results
ArrayList<Integer> oddNumber = new ArrayList<Integer>(); // array of odd numbers
// get odd numbers
for (int i = minNumber; i < MaxNumber; i++) {
if ((i % 2) != 0) {
oddNumber.add(i);
count++;
}
}
int i = 0;// counter for printing array
while (i < oddNumber.size()) {
if(i != oddNumber.size()){
System.out.print(oddNumber.get(i) + ",");
}else{
System.out.println(oddNumber.get(i));
}
i++;
}
// print result numbers
System.out.println("\nResult number : " + count);
// print number range
System.out.println("You wanted us to search between " + minNumber
+ " and " + MaxNumber);
}
}
Create a method verifyAndGetNumber which will verify a number with regex \d+ which means match one or more digit. Throw Exception if it is not number. Catch the exception and print your custom message.
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean isNumber = false;
do {
try {
System.out.println("enter number1 please : ");
if (input.hasNextLine()) {
number1 = verifyAndGetNumber(input.nextLine());
}
System.out.println("enter number2 please : ");
if (input.hasNextLine()) {
number2 = verifyAndGetNumber(input.nextLine());
}
isNumber = true;
} catch (Exception e) {
System.out.println(e.getMessage());
}
} while (!isNumber);
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
private static int verifyAndGetNumber(String line) throws Exception {
if (line.matches("\\d+")) {
return Integer.parseInt(line);
}
throw new Exception("wrong number!");
}
You can count the number of Integer inputs entered by the user and that way you can solve the problem.
So you can modify the code as:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean isNumber;
int totalEnteredNumbers=0;
int currNumber=1;
do {
System.out.println("enter number"+currNumber+" please : ");
if (totalEnteredNumbers==0 && input.hasNextInt()) {
number1 = input.nextInt();
isNumber = true;
currNumber++;
System.out.println("enter number"+currNumber+" please : ");
totalEnteredNumbers++;
}
if (totalEnteredNumbers==1 && input.hasNextInt()) {
number2 = input.nextInt();
isNumber = true;
} else {
System.out.println("wrong number!");
isNumber = false;
input.next();
}
} while (!(isNumber));
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
}
Anyways here you can also remove the boolean variable isNumber from termination condition by replacing it with while(totalEnteredNumbers<2);.
However this can also be solved with the following code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean numberTaken=false;
while(!numberTaken)
{
System.out.print("Enter number1 : ");
String ip=input.next();
try
{
number1=Integer.parseInt(ip); //If it is not valid number, It will throw an Exception
numberTaken=true;
}
catch(Exception e)
{
System.out.println("Wrong Number!");
}
}
numberTaken=false; //For second input
while(!numberTaken)
{
System.out.print("Enter number2 : ");
String ip=input.next();
try
{
number2=Integer.parseInt(ip); //If it is not valid number, It will throw an Exception
numberTaken=true;
}
catch(Exception e)
{
System.out.println("Wrong Number!");
}
}
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
}

checking if an input of an integer is a string with try catch

I want the try-catch to loop until i input a proper integer, but all i am having is an infinite loop when i enter a string :
public class Main00 {
static Scanner scan = new Scanner(System.in);
static int c = 1;
public static void main(String[] args) {
int num = 0;
while (c == 1) {
try {
System.out.println("enter a number");
num = scan.nextInt();
c = 2;
} catch (Exception e) {
System.out.println("enter a Number please : ");
}
}
Replace the loop with following:
while (c == 1) {
try {
System.out.println("enter a number");
num = Integer.parseInt(scan.nextLine());
c=2;
} catch (Exception e) {
System.out.println("enter a Number please : ");
}
}
try something like
try {
System.out.println("enter a number");
num = scan.nextInt();
c = 2;
} catch (Exception e) {
c = -1;
System.out.println("best of luck next time :)");
}
Try this
public class Main00 {
static Scanner scan = new Scanner(System.in);
static int c = 1;
public static void main(String[] args) {
int num = 0;
while (c == 1) {
try {
System.out.println("enter a number");
String value = scan.nextLine();
num = Integer.parseInt(value);
c=2;
break;
} catch (Exception e) {
continue;
}
}
With minimum use of variables and neater, you really don't require c variable.
int num = 0;
Scanner scan = new Scanner(System.in);
while (true) {
try {
System.out.println("Enter a number");
num = Integer.parseInt(scan.next());
break;
} catch (Exception e) {
continue;
}
}
This is my solution without using an exception to validate the input and some other optimisations:
public static void main(String[] args) {
int num;
while (true) {
System.out.println("enter a valid number");
if(scan.hasNextInt()){
num = scan.nextInt();
break;
}else{
scan.next();
}
}
System.out.println("input: " + num);
}
You just check if next value is an integer, and if it's an integer you put it directly in your num value. This has the benifit of not using the exception and not needing to parse the String to an integer. I also changed the while loop, now you don't need that c variable... It was just confusing ;-)

Java Character Input With Loop?

Guys I want to write a program which find Nominator and Denominator with Exception Handling and calculate their result. I also added a Simple Interface which is Would you like to continue press 'y'. or 'n'. Character is in Lower Case.
I Want that Interface Occur only on two things.When Program Catch the Wrong Input. And When Result Is Calculated.
Problem is when user press 'n' it does not quit.Or When user enter any characters like 'aadswe' Interface does not again appear. I'm Stuck at this Problem.
public class Main {
public static void main(String[] args) {
int numeator;
int denominator;
double result;
Scanner s = new Scanner(System.in);
char m = 'y';
do {
try {
System.out.print("Enter Numenator:");
numeator = s.nextInt();
System.out.print("Enter Denominator:");
denominator = s.nextInt();
result = numeator / denominator;
System.out.println("Answer: " + result);
} catch (InputMismatchException e) {
System.out.println("error=> must enter integer values");
} catch (ArithmeticException e) {
System.out.println("error=> falseairthmtic");
}
System.out.println("Would you continue prees 'y' or quit press 'n'");
m = s.next().charAt(0);
}
while (m == 'y');
}
}
Use following code-
public static void main(String[] args) {
int numeator;
int denominator;
double result;
Scanner s = new Scanner(System.in);
char m = 'y';
do {
try {
System.out.print("Enter Numenator:");
numeator = s.nextInt();
System.out.print("Enter Denominator:");
denominator = s.nextInt();
result = numeator / denominator;
System.out.println("Answer: " + result);
} catch (InputMismatchException e) {
System.out.println("error=> must enter integer values");
} catch (ArithmeticException e) {
System.out.println("error=> falseairthmtic");
}
System.out.println("Would you continue prees 'y' or quit press 'n'");
m = s.next().charAt(0);
while(m!='y'&& m!='n'){
System.out.println("you can press only 'y'or'n' "+ m+ " is not allowed!!") ;
m = s.next().charAt(0);
}
}
while (m == 'y');
System.out.println("Has been quit");
}

How to Subtract n numbers using for loop in java?

When I use for loop for subtraction, i don't get a correct output.
What logic should i apply in my code to get my subtraction correctly using for loop?
Please help me as i am new in JAVA.
My code is as Follow:
import java.io.*;
import java.util.*;
class Sub
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int a,n,i;
String yn;
boolean loop=true;
while(loop)
{
try
{
do
{
loop=true;
System.out.println("Enter how many numbers to Subtract?: ");
n=s.nextInt();
int sum=0;
for(i=1;i<=n;)
{
try
{
System.out.println("Enter number "+i+" : ");
a=s.nextInt();
sum=a-sum;
i++;
}
catch(Exception e)
{
System.out.println("Invalid Entry. Try again!!");
}
}
System.out.println("Answer is:"+sum);
System.out.println("Do you want to continue?(Y/N): ");
yn=s.next();
loop=yn.equals("Y")||yn.equals("y");
}while(loop);
}
catch(Exception e)
{
System.out.println("Re-enter the Limit");
}
}
}
}
You should start with sum as the first number (not zero) and subtract the rest of the numbers from it:
loop=true;
System.out.println("Enter how many numbers to Subtract?");
n=s.nextInt();
int sum=0;
for(i=1;i<=n;)
{
try
{
System.out.println("Enter number "+i+" : ");
a=s.nextInt();
sum=a-sum;
i++;
}
catch(Exception e)
{
System.out.println("Invalid Entry. Try again!!");
}
}
to:
...
loop = true;
System.out.println("Enter how many numbers to Subtract?: ");
n = s.nextInt();
System.out.println("Enter number 1 : ");
int sum = s.nextInt();
for (int i=2; i <= n; i++) {
try {
System.out.println("Enter number " + i + " : ");
a = s.nextInt();
sum -= a;
} catch (Exception e) {
System.out.println("Invalid Entry. Try again!!");
}
}
...
Further, instead of doing:
yn.equals("Y") || yn.equals("y")
you can use equalsIgnoreCase():
yn.equalsIgnoreCase("Y")
And last, you should use meaningful names for variables (it's recommended to develop good habits even if it's such a small program), so instead of:
int a, n, i; // you can define and use i inside the for-loop - no need to define it outside
String yn;
consider using more expressive names, such as:
int inputNumber, numberOfVariables;
String continueLooping;
The following version could be improved (refactored even further):
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
int numOfArguments = getNumberOfArguments(scanner);
int sum = getNextNumberFromUser(scanner, 1);
for (int i = 2; i <= numOfArguments; i++) {
sum -= getNextNumberFromUser(scanner, i);
}
System.out.println("Answer is: " + sum + "\n\nDo you want to continue?(Y/N): ");
String runAgain = scanner.next();
if (runAgain.equalsIgnoreCase("N")) {
break;
}
}
}
private static int getNextNumberFromUser(Scanner scanner, int i) {
while (true) {
try {
System.out.println("Enter number " + i + " : ");
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid Entry. Try again!!");
scanner.nextLine();
}
}
}
private static int getNumberOfArguments(Scanner scanner) {
int numberOfArguments = -1;
System.out.println("Enter how many numbers to Subtract?: ");
while (numberOfArguments == -1) {
try {
numberOfArguments = scanner.nextInt();
if (numberOfArguments <= 0) {
numberOfArguments = -1;
}
} catch (InputMismatchException e) {
System.out.println("Illegal number of arguments to subtract, please try again: ");
scanner.nextLine();
}
}
return numberOfArguments;
}

Entering string instead of integer (Java)

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

Categories

Resources