Ok all, I'm stuck again with this code.
I need to put in an Exception that won't allow the user to input 0 (because you can't divide later by 0) and the user cannot enter alpha characters. I am trying to display the message, disregard the wrong input, and loop to allow the user to try again until they put in the acceptable number.
Here is what I have:
package exceptionhandler;
/**
*
* #author Sarah
*/
import java.util.Scanner;
public class ExceptionHandler {
/**
* #param args
* the command line arguments10 10
*/
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Please enter ten values:");
System.out.println();
// Input the data into array from the user.
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
try
{
for (int i = 1; i < digit.length; i++) {
System.out.print("Value " + i + ": ");
digit[i] = (double)in.nextInt();
sum += (int)digit[i];
}
catch (NumberFormatException e)
{
System.out.println("You Can Only Enter Numbers!");
}
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
I have tried declaring the throw exception and then tried a try..catch. But it is not recognizing catch and try talking to one another... so I know I am doing something wrong, but I can't see where it should go.
Is the Exception in the right place? Should I have done something else? Is my exception written wrong? How can I then move on to prevent the input of zero as well- rethrow?
Help?
It supposed to be InputMismatchException not NumberFormatException to catch an exception upon entering characters and you need to check for 0 if the user input 0 and deduct 1 the current index of the for-loop to let the user try again.
sample:
for (int i = 1; i < digit.length; i++) {
try {
System.out.print("Value " + i + ": ");
digit[i] = (double) in.nextInt();
sum += (int) digit[i];
if(digit[i] == 0.0)
{
System.out.println("You cant enter 0: try again");
--i;
}
} catch (InputMismatchException e) {
System.out.println("You Can Only Enter Numbers!");
--i;
in.nextLine(); //to consume the character
}
}
result:
Please enter ten values:
Value 1: 0
You cant enter 0: try again
Value 1: asd
You Can Only Enter Numbers!
Value 1:
Related
So to clarify, when the program asks the user for number 1: if the user were to input a letter, I need the program to tell the user that there was an input mismatch, then ask the user for number 1 again. This needs to be achieved using only one single for loop, and there can be no negative numbers that affect the sum or the average. Here's what I have so far:
import java.util.*;
import java.text.*;
class fivePositiveNumbers{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
for(int i = 1; i <= 5; i++){
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
sum = sum + userNumber;
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
}
Use a while or a for loop that will increment the loop count ONLY IF a valid input is provided. Your solution increments the loop counter automatically regardless of the validity of the input.
int i = 1;
while (i <= 5) {
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
sum = sum + userNumber; // this belongs after the negative check
i++; // increment the count after all validations are successfully completed
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
}
If you choose to use a for loop, remove the counter increment out of the loop declaration
for (int i = 1; i <= 5;) {
// your logic and exception handling here
i++; // as in the while, increment only after all validations are successfully completed
}
Another point... I don't think it is necessary to throw an exception if the number is negative. I think it is better to simply execute a continue to avoid incrementing the loop counter. This is the result of this:
This program will give the sum and average of 5 positive integers,
Enter number 1:
-5
The integer must be positive.
Enter number 1:
-2
The integer must be positive.
Enter number 1:
-3
The integer must be positive.
Enter number 1:
-4
The integer must be positive.
Enter number 1:
-5
The integer must be positive.
Enter number 1:
1
Enter number 2:
2
Enter number 3:
3
Enter number 4:
5
Enter number 5:
4
The sum is 15 and the average of your 5 numbers is 3.
As you can see, I entered several negative numbers and the program continued to run without incrementing the loop counter. The complete solution with continue:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
for(int i = 1; i <= 5; ){
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
System.err.println("The integer must be positive.");
continue;
}
sum = sum + userNumber;
i++;
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
class fivePositiveNumbers{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
int ctr = 0;
for(;;){
System.out.println("Enter number " + (ctr+1) + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
sum = sum + userNumber;
ctr++;
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
if (ctr == 5) break;
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
}
I have a condition where if the user inputs a negative number or a number which is more than 100, or a string, an error message should be printed "That wasn't a valid percentage, I need a number between 0-100. Try again." and ask the user to reenter a valid number. and if the user decided to just enter, all the input should be calculated and printed the average amount.
public static void main(String[ ] args) {
int count = 0; //count to stop loop
double[ ] aGrade = new double[SIZE];
String input = new String("");
Scanner scan = new Scanner(System.in);
double total = 0;
int gTotal = aGrade.length;
boolean exit = false;
while ((count < SIZE) && (!exit)) {
System.out.print("Enter number " + (count + 1) + ": " + "\n");
try {
input = scan.nextLine();
if (Double.parseDouble(input) > 0 && Double.parseDouble(input) < 100) {
aGrade[count] = Double.parseDouble(input); //put into the array
count++; //only increment count if success
} else
System.out.println("That wasn't a valid percentage,"
+ " I need a number between 0-100. Try again.");
} catch (NumberFormatException nfe) {
exit = true; //exit loop
}
}
System.out.println("number of grades entered: " + count + "\n");
for (int i = 0; i < count; i++) {
// print entered grade
System.out.println("grade " + (i + 1) + ": " + aGrade[i]);
}
for (int i = 0; i < count; i++) {
total += aGrade[i];
}
// calculate and print the average
System.out.println("\n" + "Average grade: " + total /count);
But when I run my code, if I input letters, it won't allow the user to reinput value but prints whatever is calculated. I think it is in my if-else statement, but I am not sure how
When we try to convert String to Double it will throw java.lang.NumberFormatException. So whenever you enter String or char at that time instead of else it will go to catch block. As per your code else block only executed when user enter negative number or grater then 100 number.
I updated your code. Please review it.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
int count = 0; // count to stop loop
double[] aGrade = new double[3];
String input = new String("");
Scanner scan = new Scanner(System.in);
double total = 0;
int gTotal = aGrade.length;
boolean exit = false;
while ((count < 3) && (!exit)) {
System.out.print("Enter number " + (count + 1) + ": " + "\n");
try {
input = scan.nextLine();
if (Double.parseDouble(input) > 0 && Double.parseDouble(input) < 100) {
aGrade[count] = Double.parseDouble(input); // put into the array
count++; // only increment count if success
} else
System.out
.println("That wasn't a valid percentage," + " I need a number between 0-100. Try again.");
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
exit = true; // exit loop
}
}
if (!exit) {
System.out.println("number of grades entered: " + count + "\n");
for (int i = 0; i < count; i++) {
// print entered grade
System.out.println("grade " + (i + 1) + ": " + aGrade[i]);
}
for (int i = 0; i < count; i++) {
total += aGrade[i];
}
// calculate and print the average
System.out.println("\n" + "Average grade: " + total / count);
}else {
System.out
.println("That wasn't a valid percentage," + " I need a number between 0-100. Try again.");
}
}
}
If you type letter as an input, you will never end up in your else part of the if statement since code inside if throws an exception and you are then inside catch part. Also, you wrote inside catch part, when NumberFormatException happens(when you enter letter instead of number), set exit to true and that is the reason why program don't let you type again after you input letter. Fix those things and it will work. Also, take a look at how to debug your program, learn that skill, it will help you to solve this kind of problems in the future.
Try something like this:
boolean ok = false;
try {
input = scan.nextLine();
if ("".equals(input)) {
ok = true;
exit = true;
} else if (Double.parseDouble(input) >= 0 && Double.parseDouble(input) <= 100) {
aGrade[count] = Double.parseDouble(input); //put into the array
count++; //only increment count if success
ok = true;
}
} catch (NumberFormatException nfe) {
// nothing
}
if (!ok) {
System.out.println("That wasn't a valid percentage,"
+ " I need a number between 0-100. Try again.");
}
I'm fairly new to Java and the problem I am having is that this code compiles, but does not run after the hexadecimal conversion; it instead just ends after the method hexCharToDecimal. I can't reuse method main and I'm not sure how to call the method intreverse and actually have it run. Is there a way to get back into main or do I have to call intreverse somewhere?
import java.util.Scanner;
public class Homework4 {
public static void main(String[]args) {
// Sum and average of a set of intergers entered by the user
// First we will declare some variables
int userInput = 1;
int positives = 0;
int negatives = 0;
int sum = 0;
int numCount = 0;
Scanner input = new Scanner(System.in);
// Will start a while loop that will stop when user enters 20 integers
while ((numCount <= 20)) {
System.out.println("Please enter a nonzero integer or enter 0 to finish ");
userInput = input.nextInt();
if (userInput == 0) {
break;
} else if (userInput > 0) {
positives += 1;
numCount += 1;
sum = sum + userInput;
} else if (userInput < 0) {
negatives += 1;
numCount += 1;
sum = sum + userInput;
} else
System.out.println("Error, please enter an integer");
continue;
}
double average = (sum / numCount);
System.out.println("The sum of the entered integers is " + sum);
System.out.println("The average of the enetered integers is " + average);
System.out.println("There are " + positives + " positive integers and " + negatives + " negative integers");
// Convert Hexadecimal number to decimal
// Ask the user to input a string of 5 digits or less in hex
System.out.println("Please enter a hexadecimal number of up to 5 characters");
String hex = input.next();
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
}
// Now we will create the method to convert to decimal
public static int hexToDecimal(String hex) {
int decimal = 0;
for (int i = 0; i < hex.length(); i++) {
char hexcharacter = hex.charAt(i);
decimal = decimal * 16 + hexCharToDecimal(hexcharacter);
}
return decimal;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') // check to see if there is any letters in the string
return 10 + ch - 'A';
else
return ch - '0';
}
// Print entered integer in reverse
public static void intreverse(String[]args) {
// Ask user for an integer to be reversed
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer to be reversed");
int number = input.nextInt();
reverse(number); // Method to be called
}
// Will now state our method
public static void reverse(int number) {
// use a while loop to get each digit
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
}
}
}
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
Will always run once because it is not enclosed in any sort of loop. If you want it to run again when the second case is called then enclose it in a while(true) loop and have a break statement in the first case where you want it to stop execution.
I am very new to Java and as part of my college course I have to write a program that carries out some basic functions. Part of this program is that it needs to calculate the factorial of a number that the user inputs. If the user inputs a negative number then it must prompt for a positive number. I have got it to do this.
But if the user enters a fraction such as 2.2 then the program should present the user with an error and prompt for valid data. I believe some sort or try-catch should be implemented but so far I have had no success in getting this to work, after spending many hours on it. Any ideas how to get the program to catch the InputMismatchException error and prompt user for input again?
The relevant block of code from the program is below...
public static void factorialNumber() {
int factorial = 1;
boolean valid;
int number = 0;
do {
System.out.println("Please enter a number: ");
number = sc.nextInt();
valid = number > 0;
if (!valid) {
System.out.println("ERROR Please enter a positive number");
}
} while (!valid);
if (number < 0) {
System.out.println("***Error***: Please enter a positive number ... ");
factorialNumber();
}
if (number > 0) {
System.out.print("The factorial is: " + number + " ");
}
for (int i = 1; i <= number; i++) {
factorial *= i;
if ((number - i) > 0) {
System.out.print("x " + (number - i) + " ");
}
}
System.out.println("= " + factorial);
}
You can use Double class to parse the user input and then get only correct values. Like this:
public static void factorialNumber() {
int factorial = 1;
boolean valid;
int number = 0;
String userInput;
do {
System.out.println("Please enter a number: ");
userInput = sc.nextLine();
valid = validateUserInput(userInput);
} while (!valid);
number = Double.valueOf(userInput).intValue();
System.out.print("The factorial is: " + number + " ");
for (int i = 1; i <= number; i++) {
factorial *= i;
if ((number - i) > 0) {
System.out.print("x " + (number - i) + " ");
}
}
System.out.println("= " + factorial);
}
private static boolean validateUserInput(String userInput) {
if (userInput == null) {
System.out.println("You should enter a number!");
return false;
}
Double userInputNumber;
try {
userInputNumber = Double.valueOf(userInput);
} catch (Exception e) {
System.out.println("Please enter a valid number value.");
return false;
}
if (userInputNumber <= 0) {
System.out.println("ERROR Please enter a positive number");
return false;
} else if (userInputNumber - userInputNumber.intValue() > 0) {
System.out.println("ERROR You entered a fractional number!");
return false;
}
return true;
}
The idea is to create an average for money made in a week by day and my average must be calculated in a method that is called in the main method. That is the easy part, but the part I'm stuck on is if a number less than zero is entered it should give me an error message and re-prompt the user for a better value. I'm not looking for a handout here just for someone to tell me what I've been doing wrong if it is simple and easy or a pointer in the right direction.
import java.util.*;
public class weeklyAveragesClient2
{
public static void main(String [] args)//output averages in format
{
averageCash();
}
public static double averageCash()//use array and loop to calculate weekly average
{
double [] cashMoney;
cashMoney = new double[7];
Scanner scan = new Scanner(System.in);
int j = 0;
String s = "ERROR";
while (j < 7)
{
double num = cashMoney[j];
if (num == 0)
{
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
}
else if(num > 0)
{
System.out.print("Please enter an amount for day " + (j+1) +": ");
cashMoney[j] = scan.nextDouble();
j++;
}
else
{
System.out.println("Error: negative number please enter a number > 0");
}
}
System.out.println("Calculating...");
double sum = 0;
for (int i = 0; i < cashMoney.length; i++)
{
sum = sum + cashMoney[i];
}
double average = sum / (double)cashMoney.length;
System.out.println("Average: " + average);
return average;
}//end averageCash
}//end class
I've added some comments that will hopefully provide food for thought.
// This will *always* be zero at first because you haven't called scan.nextDouble() yet
// and zero is the default value. So when you run the program, it will output "Error
// please enter a number > 0" before doing anything else
if (num == 0) {
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
} else if (num > 0) {
System.out.print("Please enter an amount for day " + (j + 1) + ": ");
cashMoney[j] = scan.nextDouble();
j++;
} else {
// If we get into this state, the user will never be invited to enter
// another number, since the last entered number was negative, so
// num == 0 is false, and
// num > 0 is false, so
// we'll end up back here. In fact, you'll enter an infinite loop and
// this message will be printed over and over again.
System.out.println("Error: negative number please enter a number > 0");
// cashMoney[j] = scan.nextDouble(); // <-- try prompting the user again
}
Please also consider indenting your code correctly. It will greatly increase readability. If you're using an IDE like Eclipse, you can select Source > Format.