Trouble correctly handling exceptions - java

I'm a beginner Java programmer writing a program that calculates the average of a set of positive integers. First, it queries the user for the amount of integers to be entered. Then, it collects the integers from the user and outputs the calculated average. I'm having trouble handling the exceptions. When the user tries to enter a negative number to be averaged, the exception is correctly displayed, but it doesn't correctly continue the for-loop to collect the appropriate amount of numbers. For example, below is an example output:
Please enter the number of integers to be averaged: 5
Enter a number: 1
Enter a number: 2
Enter a number: -3
NegativeIntegerException: N must be a positive integer.
Enter a number: 3
Enter a number: 4
The average is: 0.0
It correctly threw the exception, but didn't continue to fill the 5 integers. Only the other 4 that were valid.
Below is the code:
import java.util.*;
class NegativeIntegerException extends Exception {
public NegativeIntegerException()
{
super("N must be a positive integer.");
}
}
public class intAverage {
public static void main(String[] args)
{
int N = 0; //number of integers to be averaged
int[] numbers = null; //array to hold integers
int sum = 0;
int newInt;
double average;
Scanner keyboard = new Scanner(System.in);
int x = 1; //for do-while loop #1
int z = 1; //for do-while loop #2
do {
try {
System.out.print("Please enter the number of integers to be averaged: ");
N = keyboard.nextInt();
numbers = new int[N]; //setting size of array
x = 2;
}
catch (Exception e) {
System.out.println("N must be a positive integer");
}
} while (x == 1);
do {
for(int i = 0; i < N; i++) //collecting the integers
{
System.out.print("Enter a number: ");
newInt = keyboard.nextInt();
if (newInt < 0) {
try {
throw new NegativeIntegerException();
}
catch(NegativeIntegerException e) {
System.out.println(e);
}
}
newInt = numbers[i];
}
z = 2;
} while (z == 1);
for(int y = 0; y < N; y++) //calculate average
{
sum = sum + numbers[y];
}
average = sum / N;
System.out.println("The average is: " + average);
}
}

When you print out the exception, subtract 1 from i, and continue. This will basically restart the iteration.
do {
for(int i = 0; i < N; i++) //collecting the integers
{
System.out.print("Enter a number: ");
newInt = keyboard.nextInt();
if (newInt < 0) {
try {
throw new NegativeIntegerException();
}
catch(NegativeIntegerException e) {
System.out.println(e);
// Ignore this input
i--;
continue;
}
}
numbers[i] = newInt;
}
z = 2;
} while (z == 1);
Note that you don't need to throw an exception for this to work - you could just as easily say:
do {
for(int i = 0; i < N; i++) //collecting the integers
{
System.out.print("Enter a number: ");
newInt = keyboard.nextInt();
if (newInt < 0) {
System.out.println("NegativeIntegerException: N must be a positive integer");
// Ignore this input
i--;
continue;
}
numbers[i] = newInt;
}
z = 2;
} while (z == 1);
This is more readable, too.

Related

How to make while loop check if there are 16 digits in a string

How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!
import java.util.Scanner;
public class LuhnAlgorithm {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine();
int i = 0;
char chk = nums.charAt(15);
while(!nums .equals("") ) {
if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
}
int sum = 0;
for( i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if ( i % 2 == 0 ) {
num = num * 2;
if ( num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if ( sum2 == chk2) {
System.out.println("Number is valid.");
}
else {
System.out.println("Number is not valid. ");
}
System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
nums = input.nextLine();
}
System.out.println("Goodbye!");
input.close();
}
}
You can include your code that you only want done if the length ==16 in an if statement.
Meaning, instead of:
if (nums.length != 16) {
//code if there is an error
}
//code if there is no error
you can do:
if (nums.length == 16) {
//code if there is no error
} else {
//code if there is an error
}
(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine().trim();
if (nums.length() == 0) {
break; //exits while loop
}
if (nums.length() != 16) { //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
continue; //goes back to the beginning right away
}
//still here, process the number
char chk = nums.charAt(15);
int sum = 0;
for (int i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if (i % 2 == 0) {
num = num * 2;
if (num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if (sum2 == chk2) {
System.out.println("Number is valid.");
} else {
System.out.println("Number is not valid. ");
}
}
System.out.println("Goodbye!");
input.close();
}
}

asking a user to reenter data in a 2d array - java

Good afternoon,
I'm writing a program that asks a user to enter two numbers into a 2d array. The 1st number needs to be between 1 and 20 and the second number needs to be between 1 and 5.
I've written the part to take the input from the user
import java.util.Scanner;
public class store {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[][] maxtrix = new double[4][2];
for (int i = 0; i < maxtrix.length; i++) {
System.out.print("Enter the amount of apples (1-20) and oranges (1-5) for bag " + (i+1) + ": ");
for (int j = 0; j < maxtrix[i].length; j++) {
maxtrix[i][j] = input.nextDouble();
}
}
The question I have is what would be the best way to ask the user to reenter the data if they are outside the given ranges. I have used a do while before to ask a user to reenter if they input is outside the range but can't seem to figure it out within a 2d array.
Thanks for any tips or hints in advance.
Try this... I intentionally kept 2 nested loops as you did. You can also enter apples and oranges separately to simplify this.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[][] maxtrix = new double[4][2];
boolean areApplesEntered = false, areOrangesEntered = false;
for (int i = 0; i < maxtrix.length; i++) {
areApplesEntered = false;
areOrangesEntered = false;
for (int j = 0; j < maxtrix[i].length; j++) {
double apples, oranges;
if (areApplesEntered == false) {
do {
System.out.println("Enter the # of apples between 1 and 20 for the bag ["+(i+1) +"] -->");
apples = input.nextDouble();
} while (apples < 1 || apples > 20);
maxtrix[i][j] = apples;
areApplesEntered = true;
} else {
do {
System.out.println("Enter the # of oranges between 1 and 5 for the bag ["+(i+1)+"] -->");
oranges = input.nextDouble();
} while (oranges < 1 || oranges > 5);
maxtrix[i][j] = oranges;
areOrangesEntered = true;
}
}
}
}
You might want to set up some while loops to check for your conditions:
System.out.println("Please enter the number of apples (from 1 to 20): ");
while (input.hasNextDouble()) {
double temp = input.nextDouble();
if (temp < 1 || temp > 20) {
System.out.println("\nThe number of apples must be a number in [1..20]. \nPlease enter a valid amount: ");
continue;
}
else {
matrix[0][0] = temp;
break;
}
}
System.out.println("Please enter the number of oranges (from 1 to 5): ");
while (input.hasNextDouble()) {
double temp = input.nextDouble();
if (temp < 1 || temp > 5) {
System.out.println("\nThe number of oranges must be a number in [1..5]. \nPlease enter a valid amount: ");
continue;
}
else {
matrix[0][1] = temp;
break;
}
}
I am assuming by your post that you are just entering two numbers total..

How to separate integers using arrays?

I am a noob at programming so I might have trouble with some key terms.
I'm trying to write a program where a user types in a minimum number and a maximum number and it generates a random number. After that I want to know how many even numbers and odd numbers are in the random generated number. I was able to successfully complete the first part but I am having trouble detecting how many even and odd numbers are in the random generated number.
SAMPLE OUTPUT:
Ex:
Random generated number is: 478,099
# of even digits: 2
# of odd digits: 3
I tried creating local variables that did not work, I want to use a switch case statement but I am having trouble. For now I used a for loop but I want to use a switch case.
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
}
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
I can't look at the whole number separately.
**EDIT 1**
import java.util.Scanner;
import java.text.DecimalFormat;
public class MyClass
{
public static void main(String args[])
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
int even = 0; int odd = 0;
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
System.out.println("Even:" + even);
System.out.println("Odd: " + odd);
}
}
}
I have gotten it to detect the even numbers and the odd numbers now I am curious to know if there is a way to do it without having the the two variables (odd, even).
You are not dividing the value l by 10. Which is why it is going into a infinite loop.
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
if((l % 10)%2==0) // this line is changed
{
even++;
}
l = l/10; // this line is changed
}
}
}
Also, if you are checking for even, you have to do ...%2 == 0. Find your errors fixed in the code above.
EDIT: you can also calculate the odd numbers in the same loop, like this:
if((l % 10)%2==0) // this line is changed
{
even++;
}
else
{
odd++;
}
EDIT3: The code was supposed to go inside the method, not replace the method.
I do not see any use case for a switch case here, but it can be accommodated like this:
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
Hope this helps. Good luck.

Find the median of n values given by the user without using arrays or any function that uses arrays or any other collection

Only manual algorithms on variables are allowed. Collections like list, arrays etc. aren't to be used. (I Used .length() function in the program but it can be manually done by putting a space after every input and counting the number of chars till a space is found)
The problem that using arrays would solve is to store any number of values that the user inputs. This can be solved by storing the values in a string. Since we'd have to know how many characters to pick from the string to form a number, I've also stored the lengths of the numbers in a separate string(Length would generally be of only 1 digit so we'd know for sure that the length of nth number would be at the nth char in the lengthstorage string.)
The algorithm:
Take a number from the string and subtract it from every other number in the string.
If the result is positive, add 1 to the int 'pos'; if negative, to 'neg'; if zero, to 'copy'.
If odd number of numbers are inputed, then the number for which pos + copy >= n/2 and neg + copy >= n/2 is the median.
If even number of numbers are inputed, then we'd have 2 middle numbers fmedian and smedian whose average would be the median. (Refer the code for algorithm).
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input,inputstorage,lengthstorage,inputlength;
int nonrep=0;
System.out.println("Enter the number of values");
int n = sc.nextInt();
int fmedian=0,smedian=0;
System.out.println("Enter a value");
input= sc.next(); //String
inputlength = "" + (char)(input.length()+48);
inputstorage = input;
lengthstorage = inputlength;
for (int i=1; i<n; i++)
{
System.out.println("Enter a value");
input = sc.next();
inputstorage = inputstorage + input;
lengthstorage = lengthstorage + (char)(input.length()+48);
}
int mainnumpos = 0;
for(int j=0;j<n;j++)
{
int copy=0;
int mainnumlength = lengthstorage.charAt(j) - 48;
int neg=0,pos=0;
int mainnum = 0; int factor = 1;int mainnumsign = 0;
for (int m =mainnumlength-1; m >= 0; m--)
{
if(inputstorage.charAt(mainnumpos+m)=='-')
{
mainnumsign = 1;
}
else
{
mainnum += (inputstorage.charAt(mainnumpos+m) - '0') * factor;
factor *= 10;
}
}
mainnumpos = mainnumpos + mainnumlength;
if(mainnumsign==1)
{
mainnum = -mainnum;
}
int position = 0;
for (int q=0;q<n;q++)
{ int fnumsign = 0;
int fnumlength = lengthstorage.charAt(q) - 48;
int fnum = 0;
factor = 1;
for (int l =fnumlength-1; l >= 0; l--)
{
if(inputstorage.charAt(position+l)=='-')
{
fnumsign = 1;
}
else{
fnum += (inputstorage.charAt(position+l) - '0') * factor;
factor *= 10;
}
}
if(fnumsign==1)
{
fnum = -fnum;
}
if((mainnum-fnum)>0)
{
pos++;
}
else if((mainnum-fnum)<0)
{
neg++;
}
else{
copy++;
}
position = position + fnumlength;
}
if((n%2)!=0){
if((double)(pos+copy)>=((double)n)/2.0 && (double)(neg+copy)>=((double)n)/2.0)
{
if(nonrep==0)
{
System.out.println("The median is: "+ mainnum);
nonrep++;
}
}
}
else
{
if ((double)(pos+copy)==(double)n/2.0)
{
fmedian=mainnum;
}
else if((double)(neg+copy)==(double)n/2.0)
{
smedian = mainnum;
}
else if((double)(pos+copy)>=(double)n/2.0 && (double)(neg+copy)>=(double)n/2.0 )
{
fmedian = mainnum;
smedian = mainnum;
}
if(j==n-1){
double evenmedian = ((double)(smedian + fmedian))/2.0;
System.out.println("The median is: "+evenmedian);
}
}
}
}
}

How do I add an evaluated scan object into an array?

I want to scan 20 integers from the user. Once the user enters a negative value, the scan stops.
After that, how can I add the positive values that the user entered into an array?
System.out.println("\nEnter up to 20 non-negative numbers:");
for(i = 0; i <= list20.length; i++) {
System.out.print("Number " + (i+1) + ": ");
input = scan.nextInt();
if(input > 0) {
input = input.list20[i] // How to add positive integer here??
}
else
break;
}
// first, zero out the array using whatever method you want
for(i = 0; i < list20.length; i++)
{
list20[i] = 0;
}
// then request the values
System.out.println("\nEnter up to 20 non-negative numbers:");
for(i = 0; i < list20.length; i++)
{
System.out.print("Number "+ (i+1) + ": ");
input = scan.nextInt();
if(input>=0)
{
list20[i] = input;
}
else
{
break;
}
}
// then total the non-negative values
int total = 0;
if(i >= 20) {
for(int value : list20)
{
if(value > 0) {
total += value;
}
}
}

Categories