Why does it not display Exception error - java

List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
AccountList.add("7878787");
Scanner AccountInput = new Scanner(System.in);
int x = 1;
do{
try{
System.out.println("Hi whats your pin code?");
String Value = AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountList.contains(Value)){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
x = 2;
}
}
} catch (Exception e){
System.out.println("You cant do that");
}
}while (x==1);
}
}
When I run this the error "You cant do that" does not appear but it is taken invalid and asks user to re enter number untill valid, how can I get the error line to be displayed?

You need to throw an exception to be able to catch one:
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountList.contains(Value)) { //If Input = ArrayList number then display "hi"
System.out.println("Hi");
x = 2;
} else {
throw new Exception();
}
}
EDIT: As said in the comment, the for line is not necessary as the algorithm to know if the value is contained in your AccountList is handled by the contains method.

Related

Try / catch in a do-while loop to check user input (array) - wrong boolean initialization and position

I am a Java beginner and I am learning to manage Exceptions and 2D arrays.
I am doing an exercise to plot in a 2D array the result of the sales of different car models.
I have mixed the way to deal with Exception by using a try catch or by throwing a custom Exception. On a custom Exception I have an issue I am not able to solve.
In the Seller class:
In line 16, IDE tells me that the variable "correct" initializer to
false is redundant
In line 26, IDE tells me that the while condition is always false.
I wanted to declare the boolean correct inside the inner loop to check for each value if the input was correct (an integer) or not and then to change the value to true at the end of the try in case the parseInt was successful. By reading the comments from the IDE I understand that the boolean correct is never changed to true even if I select an integer but I do not understand why.
import java.util.Scanner;
public class Sellers {
public static void main(String[] args) throws NumberArrayException {
Scanner myObj = new Scanner(System.in);
int nbrOfSellers = CheckInput.control("Enter the number of sellers = ");
int nbrOfModels = CheckInput.control("Enter the number of models = ");
int[][] sales = new int[nbrOfSellers][nbrOfModels];
String[] nameOfSellers = Characters.construction("seller", nbrOfSellers);
String[] nameOfModels = Characters.construction("model", nbrOfSellers);
for(int i = 0; i < nbrOfSellers; i++) {
for(int j = 0; j < nbrOfModels; j++) {
boolean correct = false;
System.out.print("Enter the sales for the seller " + nameOfSellers[i] + " for the model " + nameOfModels[i] + " = ");
do {
try {
String input = myObj.nextLine();
sales[i][j] = Integer.parseInt(input);
correct = true;
} catch (NumberFormatException e) {
throw new NumberArrayException();
}
}while (!correct) ;
}
}
for(int i = 0; i < nbrOfSellers; i++) {
for(int j = 0; j < nbrOfModels; j++) {
System.out.print(sales[i][j] + " ");
}
System.out.println();
}
}
}
import java.util.Scanner;
public class Characters {
public static String[] construction(String character, int maxSize) {
Scanner myObj = new Scanner(System.in);
String[] myArray = new String[maxSize];
for(int i = 0; i < maxSize; i++) {
System.out.print("Enter the name of the " + character + " ");
myArray[i] = myObj.nextLine();
}
return myArray;
}
}
import java.util.Scanner;
public class CheckInput {
public static int control(String message) {
boolean correct = false;
int number = -1;
Scanner myObj = new Scanner(System.in);
do {
try {
System.out.print(message);
String input = myObj.nextLine();
number = Integer.parseInt(input);
correct = true;
} catch(NumberFormatException e) {
System.out.println("Enter a number");
}
}while(!correct);
return number;
}
}
public class NumberArrayException extends RuntimeException {
public NumberArrayException() {
super();
}
}
There are two ways that this do-while-loop can exit: correct is true or an exception is thrown.
Technically, an exception can only be thrown in the two lines above the statement correct = true. Since you are throwing the NumberArrayException inside the loop, it will either exit because of it, or correct will be set true.
When we reach while (!correct), then correct is always true since it got set. Otherwise we would have exited with an exception. Therefore, this loop never has a second iteration.
To fix it, you can just avoid throwing an exception when the provided input cannot be parsed. The loop will then let the user enter another integer.
do {
try {
String input = myObj.nextLine();
sales[i][j] = Integer.parseInt(input);
correct = true;
} catch (NumberFormatException e) {
// output error message for the user here
}
} while (!correct);
Your code is pretty good and well structured. Actually, you should compare the source of CheckInput.control to see why it does not have the mentioned warnings: you initialize the local variable correct as it should be and no exception is thrown in case of invalid input, thus letting the user to correct it. If you throw an exception from inside do-while loop as in the main method, then the false value of correct is never used.
You should resolve these warnings by reusing existing CheckInput.control when initializing the 2D sales array. Also there's a typo when creating nameOfModels -- nbrOfModels should be passed as an argument.
String[] nameOfSellers = Characters.construction("seller", nbrOfSellers);
String[] nameOfModels = Characters.construction("model", nbrOfModels);
for(int i = 0; i < nbrOfSellers; i++) {
for(int j = 0; j < nbrOfModels; j++) {
sales[i][j] = CheckInput.control("Enter the sales for the seller " + nameOfSellers[i] + " for the model " + nameOfModels[i] + " = ");
}
}
When you throw an exception it exits the function and throws the exception. So instead of throwing the exception in the catch block just print and error message. So that user can understand the error and enter input again.
do {
try {
String input = myObj.nextLine();
sales[i][j] = Integer.parseInt(input);
correct = true;
} catch (NumberFormatException e) {
System.out.println("Wrong input format. Please enter a number");
}
}while (!correct) ;

How to use try catch to replace invalid data of user input array instead of restarting code in Java?

Whenever invalid input is entered, such as a letter, the code starts from the beginning. How do I get it so that it keeps rebuilding the code from where invalid input was entered. I want it to kick out the invalid input, and prompt the user to re-enter a valid input, and keep building it.
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
int z = 1;
do {
try {
Scanner scanner = new Scanner(System.in);
double[] myArr1 = new double[10]; //Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x=0; x<myArr1.length; x++) {
myArr1[x] = scanner.nextDouble(); //Gets user input
} //end of for
double sum1 = 0;
for(double x=0; x<myArr1.length; x++) {
sum1 += myArr1[(int) x]; //Defines sum1
} //end of for
double[] myArr2 = new double[10]; //Creates array
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int y=0; y<myArr2.length; y++) {
myArr2[y] = scanner.nextDouble(); //Gets user input
} //end of for
double sum2 = 0;
for (double y=0; y<myArr2.length; y++) {
sum2 += myArr2[(int) y];
} //end of for
System.out.println("Sum of first 10 elements is: " + sum1); //Prints sum of first 10 elements
System.out.println("Sum of second 10 elements is: " + sum2); //Prints sum of last 10 elements
}/*end of try*/catch (Exception e) { //Catches errors in user input
System.out.println("Invalid input. Try again: ");
System.out.println("");
} //end of catch
}//end of do
while(z==1);
return;
}
}
You can craft a helper method for input. It will continually prompt with the messages provided until a correct type is entered. This tends to come in handy when inputs need to be taken from different locations within the program.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double v = nextDouble(input, "Please enter a value: ", "Improper type, try again: ");
System.out.println(v);
}
public static double nextDouble(Scanner input, String prompt, String error) {
System.out.print(prompt);
// loop forever
for(;;) {
try {
double v = input.nextDouble();
return v;
} catch (InputMismatchException ie) {
input.nextLine(); // clear input buffer
System.out.print(error);
}
}
}
Here is an example from your code.
Scanner scanner = new Scanner(System.in);
String prompt = "Please enter a number: ";
String error = "Invalid input, try again";
double[] myArr1 = new double[10]; // Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x = 0; x < myArr1.length; x++) {
myArr1[x] = nextDouble(scanner, prompt, error);
} // end of for
double sum1 = 0;
for (double x = 0; x < myArr1.length; x++) {
sum1 += myArr1[(int) x]; // Defines sum1
} // end of for
Get rid of your existing try/catch blocks. And I don't know why you have a do/while since you aren't looping more than once.
or you can using while loop and a boolean value to get a number
Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d ;//= scanner.nextDouble();
while(bool){
try{
scanner = new Scanner(System.in);
d = scanner.nextDouble();
bool = false;
}catch(InputMismatchException e){
System.err.println("invalid input");
}
}
I've figured it out. I had to create a boolean, but also decrement the index of the array of where the bad input was being placed (i = i-1). I also made it just one array and set the first 10 values to x and the last 10 to y to make it a little bit simpler.
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
double[] array = new double[20]; //creates array
boolean on = true; //sets value "on"
while (on) { //starts while loop
System.out.println("Enter 20 numbers: ");
System.out.println("");
for (int i = 0; i < array.length; i++) { //creates user input prompt
Scanner input = new Scanner(System.in); //gets user input
try {
array[i] = input.nextDouble(); //assigns user input to array[i]
}/*end of try*/ catch (Exception e) { //catches invalid input
System.err.println("Invalid Input. Try again: ");
i = i - 1; //decrements index of re-entered number
} //end of catch
} //end of for
double x = 0;
for (int z = 0; z < 10; z++) {
x += array[z];
} //end of for
System.out.println("Sum of first 10 numbers = " + x); //adds first 10 numbers in array and assigns them to x
System.out.println("");
double y = 0;
for (int z = 10; z < 20; z++) {
y += array[z];
} //end of for
System.out.println("Sum of last 10 numbers = " + y); //adds last 10 numbers in array and assigns them to y
on = false; //breaks while loop
} //end of while
}
}

How to override the array?

I am writing a game where a user has to input 5 numbers ranging from 1 to 50. These numbers are being saved in the array intPlayersNumbers. If the conditions are not met the user has to enter the numbers again. Why is the array intPlayersNumbers not being overwritten? It is saving only the numbers that were entered for the 1st time.
public class Game {
int chosenNumbers = 5;
int chosenNumber;
String numbers;
int[] raffleArray = new int[chosenNumbers];
public void askForNumbers(){
Scanner in = new Scanner(System.in);
numbers = in.nextLine();
String[] playersNumbers = (numbers.split(" "));
int[] intPlayersNumbers = new int[playersNumbers.length];
for(int a =0; a<playersNumbers.length; a++ ){
intPlayersNumbers[a] = Integer.parseInt(playersNumbers[a]);
}
//checking the numbers
checkTheNumbers(intPlayersNumbers);
}
public int[] checkTheNumbers(int[] intPlayersNumbers){
//if there is 5 numbers
if(intPlayersNumbers.length==5){
//if the numbers are form 1 to 50
for(int i = 0; i<intPlayersNumbers.length; i++){
if(intPlayersNumbers[i]<50 && intPlayersNumbers[i]>0){
continue;
}else{
System.out.println("Please enter 5 nums from 1 to 50.");
askForNumbers();
}
}
}
else{
System.out.println("Please enter 5 numbers");
askForNumbers();
}
return intPlayersNumbers;
}
I think a do-while makes more sense here. Additionally, I think it makes more sense that checkTheNumbers returns a boolean as it performs a validation. The solution below will continuously ask for numbers until checkTheNumbers returns true.
public int[] askForNumbers(){
int[] intPlayersNumbers;
Scanner in = new Scanner(System.in);
do {
System.out.println("Please enter 5 nums from 1 to 50.");
numbers = in.nextLine();
String[] playersNumbers = (numbers.split(" "));
intPlayersNumbers = new int[playersNumbers.length];
for(int a =0; a<playersNumbers.length; a++ ){
intPlayersNumbers[a] = Integer.parseInt(playersNumbers[a]);
}
} while (!checkTheNumbers(intPlayersNumbers));
return intPlayersNumbers;
}
public boolean checkTheNumbers(int[] intPlayersNumbers) {
if(intPlayersNumbers.length==5) {
for(int i = 0; i < intPlayersNumbers.length; i++) {
if (intPlayersNumbers[i] > 50 || intPlayersNumbers[i] <= 0) {
System.out.println("Please enter 5 nums from 1 to 50.");
return false;
}
}
} else{
System.out.println("Please enter 5 numbers");
return false;
}
return true;
}
I think you can easily solve this using recursion. Since the context of your question is not completely clear i did one or two assumptions. If you want a slightly different solution you can use the comments as hints.
public void askForNumbers() {
Scanner in = new Scanner(System.in);
// use the sout before the system.in waits for you first input
System.out.println("Please enter 5 nums from 1 to 50.");
numbers = in.nextLine();
String[] playersNumbers = (numbers.split(" "));
int[] intPlayersNumbers = new int[playersNumbers.length];
// check if the array has lenght 5 directly after the split.
if (intPlayersNumbers.length != 5) { // if the split.length != 5 start over
askForNumbers();
}
else {
for (int a = 0; a < playersNumbers.length; a++) {
int i = Integer.parseInt(playersNumbers[a]); //beware this can cause a numberFormatException !!!
if (i > 0 && i < 51) { // if one of the number is not in range start over.
intPlayersNumbers[a] = i;
}
else {
System.out.printf("%d was not between 0 and 50", i); // print which integer was the culprit
askForNumbers();
return; //return so this method ends here;
}
}
raffleArray = intPlayersNumbers; // or return intPlayersNumbers , you will have to change the return type of the method as well
}
}
I you have any questions about this solution, just leave a comment.

How do i compare the 6 numbers inputted by the user to the 6 randomly generated numbers to see if they are the same or not

package lotto;
import java.util.Random;
import java.util.Scanner;
public class lotto {
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
int restarto = 0;
double[] inputs = new double[6];
do{
////////////////////////ask for input
System.out.println("Welcome to the lotto program. Please enter " +inputs.length + " values:");
for(int i = 0; i < inputs.length; i++)
inputs[i] = scan.nextDouble();
///////////////////////create random numbers
double [] elArry = new double[6];
Random random = new Random();
for(int i = 0; i < elArry.length; i++){
elArry[i] = random.nextInt(101);
}
//////////////////////check for similarities
How can I compare the user inputted numbers and my randomly generated numbers to see if the user has correctly guessed the numbers?
//////////////////////print results
//////////////////////restart?
System.out.println("Would you like to guess again on the same lotto numbers?");
System.out.println("1.Yes");
System.out.println("2.No");
restarto=scan.nextInt();
}while(restarto == 1);
}
}
If necessary to know only if all were guessed right:
boolean same = true;
for(int i = 0; i < elArry.length; i++) {
if (elArry[i] != inputs[i]) {
same = false;
break;
}
System.out.println(same? "You have guessed correctly!" : "You guessed wrong!");
If you are fine with making a method for that, like robotlos suggested, the code will be prettier:
private static boolean guessedRight() {
for (int i = 0; i < elArry.length; i++)
if (elArry[i] != inputs[i]) return false;
return true;
}
...
System.out.println(guessedRight()? "You have guessed correctly!" : "You guessed wrong!");
But to tell the truth, you can generate random numbers straight after the user's input, which will make your code more compact:
boolean same = true;
for(int i = 0; i < inputs.length; i++) {
inputs[i] = scan.nextInt();
if(inputs[i] != random.nextInt()) same = false;
//there is no reason to generate double if the user guesses with ints
}
//if same is false, at least one number was not guessed right
Sort the two arrays, then check to see if they equal. If they do, then they are the same:
Arrays.sort(inputs);
Arrays.sort(elArry);
return (Arrays.equals(inputs, elArry));
Since both arrays must have the same values in the same order, then yoy can check if they are technically equal
The class Arrays has the equals method that can solve that for you...
Example:
if (Arrays.equals(inputs, elArry)) {
System.out.println("You won... :)");
} else {
System.out.println("You were not even close... :(");
}
You could write a loop to check if the i'th entry of your input array is also contained in elArray, providing you are not interested in the guessing order:
int counter = 0;
for(int i = 0; i < inputs.length; i++) {
if (IntStream.of(elArray).anyMatch(x -> x == inputs[i])) {
counter += 1;
}
}
Now the counter variable contains the amount of correctly guessed numbers. You could also modify this to keep track of which numbers were correct.
Make a boolean array of 6 then make a loop comparing the input and rndNum.
boolean[] correct = new boolean[6];
for (int i = 0; i < 6; i++) {
if (inputs[i]==elArry[i]) {
correct[i] = true;
}
There are tons of ways to tackle this problem, this i guess is one of them.

Java System.out.println Prints 20 times

import java.util.*;
public class ArrayExample {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean done = false;
while (!done) {
try {
System.out.println("Please enter the size of the array:");
String input = keyboard.next();
int size = new Integer(input).intValue();
int numbers[] = new int[size];
for (int i = 0; i < 20; i++) {
numbers[i] = i;
done = true;
System.out.println("Good.");
}
} catch (NumberFormatException ex) {
System.out.println("NumberFormatException Error. Please enter a integer.");
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("ArrayIndexOutOfBoundsException Error. Please enter 20 or higher.");
} catch (NegativeArraySizeException ex) {
System.out.println("NegativeArraySizeException Error. Please do not enter a negative.");
}
}
}
}
When I run this program it does not function properly. It should throw a exception unless I enter a INTEGER 20 or higher. However, it prints "Good." if I enter a number lower then 20. So if I enter 19 it will print "Good." 19 times. If I enter 3 it will print "Good." 3 times. I only want it to print "Good." if I enter 20 or higher. If not it should continue to loop through the exceptions.
You don't need anArray and IndexOutOfBoundException
for (int i = 0; i < size; i++) // < --- use (size) instead of constant 20 value
{
System.out.println("Good.");
}
also add finally block with done = true;
}
finally
{
done = true;
}
This will prevent the infinite loop throwing an exception.
Also add validation at the beginning of the program:
int size = new Integer(input).intValue();
if (size >= 20)
{
throw new IllegalArgumentException("Number more then 19");
}
I didn't understand fully, but what I have got this program to do is if the number is less than 20, it will throw the ArrayIndexOutOfBoundsException, but if it is 20 or greater, it will print out "Good" for how many ever times the integer size was. I also changed the for loop into an enhanced for loop:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean done = false;
while (!done) {
try {
System.out.println("Please enter the size of the array:");
String input = keyboard.next();
int size = new Integer(input).intValue();
int numbers[] = new int[size];
if(numbers.length >= 20) {
for (int i : numbers) {
numbers[i] = i;
done = true;
System.out.println("Good.");
}
} else {
throw new ArrayIndexOutOfBoundsException("ArrayIndexOutOfBoundsException Error. Please enter 20 or higher.");
}
} catch (NumberFormatException ex) {
System.out.println("NumberFormatException Error. Please enter a integer.");
} catch (NegativeArraySizeException ex) {
System.out.println("NegativeArraySizeException Error. Please do not enter a negative.");
}
}
}
try the below code, you need to check if number given number is less than 20 and throw the exception, that part of code is missing
import java.util.*;
public class ArrayExample {
private static Scanner keyboard;
public static void main(String[] args) throws Exception {
keyboard = new Scanner(System.in);
boolean done = false;
while (!done) {
try {
System.out.println("Please enter the size of the array:");
String input = keyboard.next();
int size = new Integer(input).intValue();
int numbers[] = new int[size];
if(size <20){
throw new Exception("Number less than 20");
}
for (int i = 0; i < 20; i++) {
numbers[i] = i;
done = true;
System.out.println("Good.");
}
} catch (NumberFormatException ex) {
System.out.println("NumberFormatException Error. Please enter a integer.");
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("ArrayIndexOutOfBoundsException Error. Please enter 20 or higher.");
} catch (NegativeArraySizeException ex) {
System.out.println("NegativeArraySizeException Error. Please do not enter a negative.");
}
}
}
}
The easiest way to answer this is to just walk through the code and figure out exactly what is happening. For simplicity, let's say you enter three.
import java.util.*;
public class ArrayExample {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean done = false; //ok so we set done to false
while (!done) { //first time through, we are not done, so we enter the loop
try {
System.out.println("Please enter the size of the array:"); //you ask for a number
String input = keyboard.next(); //we put in '3'
int size = new Integer(input).intValue(); //convert the input to an int
int numbers[] = new int[size]; //we set the size to '3'
for (int i = 0; i < 20; i++) { //we enter the loop, i is 0 so we continue
numbers[i] = i; //we set the value of idx 0 to 0
done = true; //we set done to true so we will exit the while loop
System.out.println("Good."); //we print good
//we increment i to 1
}
//EXPANDED LOOP FOR CLARITY
for (int i = 0; i < 20; i++) { //second time, i is now 1
numbers[i] = i; //we set the value of idx 1 to 1
done = true; //we set done to true again (kind of redundant)
System.out.println("Good."); //we print good
//we increment i to 2
}
for (int i = 0; i < 20; i++) { //third time, i is now 2
numbers[i] = i; //we set the value of idx 2 to 2
done = true; //we set done to true again (still kind of redundant)
System.out.println("Good."); //we print good
we increment i to 3
}
for (int i = 0; i < 20; i++) { //fourth time, i is now 3
numbers[i] = i; //at this point we should throw an ArrayIndexOutOfBoundsException, so go to that catch statement
done = true;
System.out.println("Good.");
}
} catch (NumberFormatException ex) {
System.out.println("NumberFormatException Error. Please enter a integer.");
} catch (ArrayIndexOutOfBoundsException ex) { //so here we catch the AIOB exception
System.out.println("ArrayIndexOutOfBoundsException Error. Please enter 20 or higher."); //we print out an error, then continue
} catch (NegativeArraySizeException ex) {
System.out.println("NegativeArraySizeException Error. Please do not enter a negative.");
}
//here at the end of the block, we go back to check the while condition
//we set done to true, so the while will fail and we will exit the program
}
}
}
Given that, your output should look like this:
Good
Good
Good
ArrayIndexOutOfBoundsException Error. Please enter 20 or higher.
And that's all. The program will be done. Because you haven't posted the output, it would be difficult to debug this further.
Add the following lines after int size = new Integer(input).intValue();
if(size<20)
throw new ArrayIndexOutOfBoundsException("size is not equal to or greater than 20");
It will throw an Exception if the Size is less than 20. And no need to write those try and catch methods.
Hope this helped you...

Categories

Resources