Java Character Input With Loop? - java

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

Related

Edit ExceptionSample so it can catch exceptions wherein text is entered as String input instead of integer data type input

How to catch an exception if the the input is string instead of integer?
It's confusing me since they used Try, Catch, Finally which looks new to me. Please enlighten me thanks.
import java.util.*;
public class ExceptionSample {
public static void main (String[]args){
Scanner s = new Scanner(System.in);
int dividend, divisor, quotient;
System.out.print("Enter dividend: ");
dividend = s.nextInt();
System.out.print("Enter divisor: ");
divisor = s.nextInt();
try {
quotient = dividend/divisor;
System.out.println(dividend + " / " + divisor + " = " + quotient);
}
catch (ArithmeticException ex) {
System.out.println("Divisor cannot be 0.");
System.out.println("Try again.");
}
finally {
System.out.println("Thank you.");
}
}
}
It would go something like this:
Scanner s = new Scanner(System.in);
int dividend, divisor, quotient;
while (true) {
System.out.print("Enter dividend: ");
try {
dividend = s.nextInt();
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid Dividend Entry! Try again...\n");
s.nextLine(); // consume the Enter Key Hit.
continue;
}
break;
}
while (true) {
System.out.print("Enter divisor: ");
try {
divisor = s.nextInt();
if (divisor == 0) {
throw new java.util.InputMismatchException();
}
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid Divisor Entry! Try again...\n");
s.nextLine(); // consume the Enter Key Hit.
continue;
}
break;
}
try {
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " = " + quotient);
}
catch (ArithmeticException ex) {
System.out.println("Divisor cannot be 0.");
System.out.println("Try again.");
}
finally {
System.out.println("Thank you.");
s.close();
}
When the Scanner#nextInt() method is used and one or more alpha characters are supplied a InputMismatchException is thrown. We trap this exception and use it to our advantage for validating the numerical input.

Cant get my integers to add to get correct output

so I am trying to do my homework, this being the question:
Write a program that prompts the user to read two integers and displays their sum. If anything but an integer is passed as input, your program should catch the InputMismatchException that is thrown and prompt the user to input another number by printing "Please enter an integer."
Below is the sample run and what I am supposed to test.
SAMPLE RUN #1: java InputMismatch
Enter an integer: 2.5↵
Please enter an integer↵
Enter an integer: 4.6↵
Please enter an integer↵
Enter an integer: hello!↵
Please enter an integer↵
Enter an integer:7↵
Enter an integer:5.6↵
Please enter an integer↵
Enter an integer:9.4↵
Please enter an integer ↵
Enter an integer:10↵
17↵
When I am testing my code and putting in the integers, it works as it is supposed to, however, I am stuck on getting the integers to add together when both inputs are entered correctly. What am I doing wrong?
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
try adding another condition to your while and putting the numbers in an array.
int[] numbers = new int[2];
and change this in your while loop:
int count = 0;
while (!isValid && count <2) {
try {
System.out.print("Enter an integer: ");
numbers[count] = input.nextInt();
count++;
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
Hope that helped.
Check with this approach:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
numArray[count] = number;
count++;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
int num1 = numArray[0];
int num2 = numArray[1];
System.out.println((num1 + num2));
}
You need to stitch together the logic. As you are taking 2 numbers 2 flags will ensure you got correct input for both variables. Also both flags ensure you are taking input correctly for num1 or num2 when an exception occurs.
If you need to input n arbitrary integers, then you may want to use dynamic collections and add numbers to collection.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean num1Valid = false;
boolean num2Valid = false;
while (num1Valid==false || num2Valid==false) {
try {
if(num1Valid == false) {
System.out.print("Enter an integer for num1: ");
num1 = input.nextInt();
System.out.println("The number entered for num1 is " + num1);
num1Valid = true;
}
if(num2Valid == false) {
System.out.print("Enter an integer for num2: ");
num2 = input.nextInt();
System.out.println("The number entered for num2 is " + num2);
num2Valid = true;
}
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
input.close()
System.out.println((num1 + num2));
}
You need capture the exception, in this case you can using e.getMessage()
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1=0, number=0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
number = input.nextInt();
if(number > 0) {
System.out.println("The number entered is " + number);
}
num1 += number;
System.out.println("are would you like continue the program? Y or
N ");
String condition = input.next();
if(condition.equalsIgnoreCase("Y")) {
isValid = false;
} else {
isValid = true;
}
}
catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
System.out.println("You cannot type words");
isValid = true;
}
}
System.out.println("Result = " + num1);
input.close();
}
}
in another case do you can use the method matches using expression language
saw example below:
if(valor.matches("[0-9]*"))
You can add the two numbers inside the try block
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
num1 = input.nextInt();
System.out.print("Enter an integer: ");
num2 = input.nextInt();
System.out.println("The numbers you entered are " + num1 + ","+num2);
int sum = num1+num2;
System.out.println("The sum Of the numbers you entered is: "+ sum);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer:");
int number = input.nextInt();
numArray[count] = number;
count++;
} catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
input.nextLine();
}
}
System.out.println(numArray[0] + numArray[1]);
}
}

Quadratic Equation (handle exceptions) for illegal inputs

I am trying to create a program that asks users for input values for variables in the quadratic equation. I want the code to deal with bad input with the use of exception handling. Bad input would be: non-numeric values where numeric values are excepted. Where i am running into a problem is when a bad value is entered instead of terminating the program i want the code to re request an input. So, in cases where Non-numeric, A=0 or B and C both = 0.
The code below has some errors but I was wondering if someone could help me crack this one! Thanks alot
import java.util.InputMismatchException;
import java.util.Scanner;
//Program that does quadratic equations with exceptions
public class Quadratic{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double a ;
do{
try{
System.out.print("Enter a value for 'a': ");
a =sc.nextDouble();
}
catch (InputMismatchException ex)
{
System.out.println("not a valid character..");
System.out.println("please try again:");
sc.nextDouble(); //prompt user again
}
}while (a==0);
System.out.println("value can not be equal to 0. Please enter another value:\n");
a= sc.nextDouble();
}
}
Your code currently doesn't show you're getting any input for variables B or C but error handling of them should be similar to what can do with input here for 'a':
import java.util.InputMismatchException;
import java.util.Scanner;
//Program that does quadratic equations with exceptions
public class Quadratic{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double a = 0.0 ;
boolean valid_a = false;
while(!valid_a){
try{
System.out.print("Enter a value for 'a': ");
a = sc.nextDouble();
if (a==0){
System.out.println("value can not be equal to 0. Please enter another value:");
}
else{
valid_a = true;
}
}
catch (InputMismatchException ex){
System.out.println(ex);
sc.next();
System.out.println("not a valid character..");
System.out.println("please try again:");
}
}
}
}
Hope this helps!
import java.util.InputMismatchException;
import java.util.Scanner;
//Program that does quadratic equations with exceptions
public class Quadratic{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double a, b, c;
boolean valid_a = false;
a = 0.0;
while(!valid_a){
try{
System.out.print("Please enter value for 'a': ");
a = sc.nextDouble();
if (a == 0){
System.out.println("VALUE CANNOT BE 0, PLEASE TRY AGAIN.");
}
else{
valid_a = true;
}
}
catch (InputMismatchException e){
System.out.println(e);
sc.next();
System.out.println("INVALID INPUT PLEASE TRY AGAIN");
}
}
boolean valid_b = false;
b = 0.0;
while(!valid_b){
System.out.println("Please enter value for 'b': ");
try{
b = sc.nextDouble();
sc.nextLine();
valid_b = true;
}
catch(InputMismatchException e){
System.out.println(e);
valid_b = false;
System.out.println("INVALID INPUT PLEASE TRY AGAIN");
sc.nextLine();
}
}
boolean valid_c = false;
c = 0.0;
while(!valid_c){
System.out.println("Please enter value for 'c': ");
try{
c = sc.nextDouble();
sc.nextLine();
valid_c = true;
}
catch(InputMismatchException e){
System.out.println(e);
valid_c = false;
System.out.println("INVALID INPUT PLEASE TRY AGAIN");
sc.next();
}
}
while(b == 0 && c == 0){
System.out.println("B AND C CANNOT BE BOTH 0. PLEASE RE-ENTER VALID VALUES.");
System.out.println("Value B: ");
b = sc.nextDouble();
System.out.println("Value C: ");
c = sc.nextDouble();
}
System.out.println("Value a:" +a);
System.out.println("Value b:" +b);
System.out.println("Value c:" +c);
double determinate = Math.pow(b,2)- (4 * a * c);
if (determinate >= 0){
double qf1 = ((-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c)))) / (2 * a);
double qf2 = ((-b - Math.sqrt(Math.pow(b, 2) -(4 * a * c))))/ (2 * a);
// qf stands for Quadratic Formula
System.out.printf("Anwser One: %s \n", qf1);
System.out.printf("Anwser Two: %s \n", qf2);
}
else{
System.out.println("DETERMINATE IS NEGATIVE, THEREFORE THERE ARE NO REAL ROOTS.");
}
System.out.println("PROGRAM IS COMPLETE");
return;
}
}``

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