can't perform array validation (out of bounds) - java - java

I'm not too sure on what's happening here.
Code is supposed to validate an input against an array of fixed ID numbers. But everytime I purposefully enter the wrong number, it would say that "array is out of bounds".
Not too sure on what is causing the problem, maybe someone can point out my mistake?
import java.util.Scanner;
public class isValid
{
static int accNum[] = {11111, 22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999, 10101, 20202, 30303, 40404, 50505, 60606, 70707, 80808, 90909};
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int conti = -99;
int search = 0;
do
{
System.out.print("Enter 5-digit account number you want to validate: ");
search = keyboard.nextInt();
sequentialSearch(accNum, search);
System.out.println("");
System.out.print("Enter -9 to exit program, or any other number to validate another ID: ");
conti = keyboard.nextInt();
} while (conti != -9);
}
public static void sequentialSearch(int[] array,int value)
{
int index = 0;
int element = -1;
boolean found = false;
while (!found && index < array.length)
{
if (array[index] == value)
{
found = true;
element = index;
break; //prevent index addition if value found
}
index++;
}
if (array[index] == value)
{
System.out.println("Account " + value + " is valid.");
}
else
{
System.out.println("Account " + value + " is invalid.");
}
}
}
Problem given: http://imgur.com/39caZxD
Error message: http://imgur.com/GEr95Wb

I have modified the code and it should be something like this:
import java.util.Scanner;
public class isValid
{
static int accNum[] = {11111, 22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999, 10101, 20202, 30303, 40404, 50505, 60606, 70707, 80808, 90909};
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int conti = -99;
int search = 0;
do
{
System.out.print("Enter 5-digit account number you want to validate: ");
search = keyboard.nextInt();
sequentialSearch(accNum, search);
System.out.println("");
System.out.print("Enter -9 to exit program, or any other number to validate another ID: ");
conti = keyboard.nextInt();
} while (conti != -9);
}
public static void sequentialSearch(int[] array,int value)
{
int index = 0;
int element = -1;
boolean found = false;
while (!found && index < array.length)
{
if (array[index] == value)
{
found = true;
element = index;
break; //prevent index addition if value found
}
index++;
}
if (found)
{
System.out.println("Account " + value + " is valid.");
}
else
{
System.out.println("Account " + value + " is invalid.");
}
}
}
Notice the change in the if condition present after the while loop of sequentialSearch function.
Why is that? Since the index is equal to the a value that is beyond the array indexes in case the value is not present in the array.

OK, I am really sorry that my previous solution was a little bit dumb, But now what I can suggest as second way of your solution is do like this,
while (!found && index < accNum.length)
{
if (accNum[index] == value)
{
found = true;
element = index;
System.out.println("Account " + value + " is valid.");
}
else
{
System.out.println("Account " + value + " is invalid.");
break;
}
index++;
}
Description :- Your value will be matched once and prints valid message. If it didn't match the value then it will print invalid message and loop will break.

Related

not sure why while loop isn't looping

I am trying to prompt the user to enter 5 integers but it won't loop more than once. I don't know why this is happening and couldn't resolve the error by myself
Code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int counter= 0;
Boolean inputOK;
int iInput;
int data[]= new int[5];
// while (counter<5);
do {
System.out.println(" Please enter an integer");
while (!s.hasNextInt()) {
System.out.println("Invalid input");
System.out.println("Please Enter an integer value");
s.next();}
iInput=s.nextInt();
if (iInput < -10 || iInput > 10) {
System.out.println("Not a valid integer. Please enter a integer between -10 and 10");
inputOK = false;
} else {
inputOK = true;
}
System.out.println("before while loop"+ inputOK);
} while (!inputOK);
counter++;
System.out.println("counter value is"+ counter);
}
}
If you follow your code, you can see that when inputOK is true, there is no loop to get back to. It looks like you had some counter in mind, but you ended up not using it. The following code does what I think you intended with your code:
Scanner sc = new Scanner(System.in);
int[] data = new int[5];
for(int i = 0; i < data.length; i++) {
System.out.println("Please enter an integer.");
// Skip over non-integers.
while(!sc.hasNextInt()) {
System.out.println("Invalid input: " + sc.next());
}
// Read and store the integer if it is valid.
int nextInt = sc.nextInt();
if(nextInt < -10 || nextInt > 10) {
// Make the for loop repeat this iteration.
System.out.println("Not a valid integer. Please enter an integer between -10 and 10.");
i--;
continue;
}
data[i] = nextInt;
}
for(int i = 0; i < data.length; i++) {
System.out.println("data[" + i + "] = " + data[i]);
}

How to print two different data type arrays?

Can anyone help?
Choice 2 isn't working. It is suppose to display the employee ID when the user inputs the employee Name, but when the user enters the name nothing prints. The code has no errors.
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
//methods called from main
}
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
// search employee data
public static void search(String[] emplNames, int[]emplID) {
Scanner scan= new Scanner(System.in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = scan.nextInt();//input choice
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID= scan.nextInt();
for(int ID = 0; ID < emplID.length; ID++) {
if (searchID == (emplID[ID])){
System.out.println("Name: "+ emplNames[ID]);
}
}
}
// Choice 2 to enter name to display ID
else if(num == 2) {
System.out.println("Please enter Employee Name");
String searchName= scan.next();
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
}
else
System.out.println("Employee Not Found");
}
}
I copied and pasted your code and ran it on my machine. Yes, choice 2 was not working for me either.
Before reading your code completely my gut feeling was that the cause of failure was in using the Scanner class to get the name of the employee. I have had similar issues in the past and the best move is to learn to use the InputStreamReader and BufferedStreamReader objects.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
1: I didn't do anything to your main()
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
}
2: I didn't do anything to your employeeID() function
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
3: It's in your search() method where I first created the InputStreamReader and the BufferedReader:
public static void search(String[] emplNames, int[]emplID) {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buff = new BufferedReader(in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = 0;
try {
num = Integer.parseInt(buff.readLine());
} catch (Exception e) {
e.printStackTrace();
}
4: Since choice 1 works fine, all I did was change your for loop to a for-each loop to make it easier to read.
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID = 0;
try {
searchID = buff.read();
} catch (Exception e) {
e.printStackTrace();
}
for (int i : emplID) {
if (searchID == i) {
System.out.println("Name: " + emplNames[i]);
}
}
5: Here is what I did to make your 2nd Option work. Again, get the String from user via BufferedReader object's readLine() method. Then, it was just letting your for-loop searching for a match. That's it. Afterward, I ran the program and tested it for all the names you had above, works fine.
} else if (num == 2) {
System.out.println("Please enter Employee Name");
String searchName = "";
try {
searchName = buff.readLine();
} catch(Exception e) {
e.printStackTrace();
}
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
} else {
System.out.println("Employee Not Found");
}
}
}
6: Yeah, Scanner has an issue where it either doesn't read the entire line or you need to flush the stream before getting the input. It caused a lot of problems for me in a bunch of easy programs. Then I switched to using the InputStreamReader and BufferedStreamReader combo. Just wrap them in try-catch blocks, and you're fine. Look into it, it will the behavior of your code and your life a lot easier.
7: I hope this was helpful.

Random two-digit number guessing game in Java

I'm working on a "game" for the user to guess a random two-digit number, and this is my "robust" version so far:
import static java.lang.System.*;
import java.util.*;
public class RandomNumberGuessing {
public static Scanner scan = new Scanner(in);
public static void main(String args[]){
Random generator = new Random ();
int Low = 10;
int High = 99;
int answer = generator.nextInt (High - Low) + Low;
int answerFirstDigit = Integer.parseInt(String.valueOf(answer).substring(0,1));
int answerSecondDigit = Integer.parseInt(String.valueOf(answer).substring(1,2));
int count = 0;
out.println ("Welcome to the two digit number guessing game!");
out.println ("We have randomly chosen a two-digit number");
out.println ("And you have to guess it after 5 tries!");
out.println ("Guess the number: ");
while (!scan.hasNextInt ()) {
scan.next ();
out.println ("You have to input a valid two-digit integer!");
}
int guess = scan.nextInt ();
while (guess != answer && count < 4){
count ++;
out.println("Wrong number! You have " + (5 - count) + " tries left:");
if (Integer.parseInt(String.valueOf(guess).substring(0,1)) == answerFirstDigit){
out.println("But you got the first digit correctly!");
} else if (Integer.parseInt(String.valueOf(guess).substring(1,2)) == answerSecondDigit){
out.println("But you got the second digit correctly!");
} else if (Integer.parseInt(String.valueOf(guess).substring(1,2)) == answerSecondDigit || Integer.parseInt(String.valueOf(guess).substring(0,1)) == answerSecondDigit){
out.println("One or two digits are correct but in the wrong place!");
}
while (!scan.hasNextInt ()) {
scan.next ();
out.println ("You have to input a valid two-digit integer!");
}
guess = scan.nextInt ();
}
if (guess == answer){
out.println("Congratulations! The number was " + answer + "!");
} else{
out.println("The number was " + answer + ". Better luck next time!");
}
}
}
But I'm having a problem with forcing the user to input a two-digit number only. I tried using:
while(guess < 10 || guess > 99){
scan.next();
out.println("Invalid number!");
guess = scan.nextInt();
}
I added that after the while loop to make sure the user entered an integer, and when I enter a 3 or 4-digit number in the console (I run the code on IntelliJ IDEA), it just seems to hang with no response. It doesn't even print out "Invalid number!" and just hangs. Do I have to rewrite the code using methods or are there any other things I can add to the existing code to make sure the user enters a TWO-DIGIT INTEGER? Thanks in advance
To check that the user enters just two digit numbers, i would use two methods to verify that.
Things to check:
User must enter something, i.e do not accept null or empty
Everything user enters must be exactly two characters long
When the characters are two, they have to all be digits
In your program you can do these
1. Get input as string
2. Call validString
3. If valid, then convert to integer
4. Check that number is between range (if the user entered 01, this evaluates to true). Integer.ParseInt could catch this but good to check anyway
Complete program should be something like this
import static java.lang.System.*;
import java.util.*;
public class RandomNumberGuessing {
public static Scanner scan = new Scanner(in);
public static void main(String args[]) {
final int tries = 5; // max number of tries
Random generator = new Random();
int Low = 10;
int High = 99;
int answer = generator.nextInt(High - Low) + Low;
int firstDigit = getFirst(answer);
int secondDigit = getSecond(answer);
out.println("Welcome to the two digit number guessing game!");
out.println("We have randomly chosen a two-digit number");
out.println("And you have to guess it after " + tries + " tries!");
int guess = 0; // number guessed
int count = 0; // number of failed guesses
do {
out.println("Guess the number: ");
String guessString = scan.nextLine(); // just read everything
// entered
if (validString(guessString)) {
guess = Integer.parseInt(guessString);
if (guess >= Low && guess <= High) { // check range and only
// process valid range
count++;
if (count == tries) {
out.print("Max guess reached.\nThe values were ");
out.println(firstDigit + " and " + secondDigit);
break;
}
out.println("You guessed " + guess);
// get the first and second digits
int first = getFirst(guess);
int second = getSecond(guess);
// compare them and process
if (guess == answer) {
out.println("Congratulations. You made the right guess after "
+ count + " tries");
} else if (first == firstDigit) {
out.println("Guessed the first number rightly");
} else if (second == secondDigit) {
out.println("Guessed the second number rightly");
} else {
out.print("No matching guess. You have ");
out.println((tries - count) + " guesses left");
}
} else {
out.println("Out of range!");
}
} else {
out.println("Bad Value.");
}
} while (guess != answer && count < tries);
}
// Validate an input Checks for length [2 characters] and that everything is
// a digit
private static boolean validString(final String guess) {
if (guess != null && !guess.isEmpty()) { // if not null and not empty
if (guess.length() == 2 && isAllDigits(guess)) { // length and digit
return true;
} else {
return false;
}
} else {
return false;
}
}
// Verify that all characters in a string are numbers
private static boolean isAllDigits(final String input) {
for (char c : input.toCharArray()) {
if (!Character.isDigit(c))
return false;
}
return true;
}
// get the first digit
private static int getFirst(final int value) {
return Integer.parseInt(String.valueOf(value).substring(0, 1));
}
// Get the second digit
private static int getSecond(final int value) {
return Integer.parseInt(String.valueOf(value).substring(0, 1));
}
}

How to prevent string from printing repeatedly in while loop?

I'm currently working on some exercises given to me by my teacher. These are for the holidays so I won't be able to ask for help there.
I have this piece of code which creates a multiplication table from an integer defined by the user, ranging from a minimum and maximum also defined by the user.
Before setting any of my variables to the next integer in my Scanner, I do a check to see if the Scanner actually has an integer. This works fine but I don't want it to print out the error message a billion times.
Any tips/tricks or other special ways of getting around this?
public class MultiplicationTable
{
private int intervalMin;
private int intervalMax;
private int multiplier;
private int result;
private Scanner sc;
public MultiplicationTable()
{
multiplier = 0;
intervalMin = 0;
sc = new Scanner(System.in);
while (multiplier == 0)
{
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt())
{
multiplier = sc.nextInt();
}
else
{
System.out.println("Input is not an integer\n");
}
}
while (intervalMin == 0)
{
System.out.println("\nPlease enter the integer defining the start of the table");
if (sc.hasNextInt())
{
intervalMin = sc.nextInt();
}
else
{
System.out.println("Input is 0 or not an integer\n");
}
}
while (intervalMax == 0)
{
System.out.println("\nPlease enter the integer defining the end of the table");
if (sc.hasNextInt())
{
int i = sc.nextInt();
if (i > intervalMin)
{
intervalMax = i;
}
else
{
System.out.println("\nEnd integer must be greater than start integer");
}
}
else
{
System.out.println("Input is 0 or not an integer");
}
}
System.out.println("\nTable for integer " + multiplier + " from " + intervalMin + " to " + intervalMax + "\n");
for (int i = intervalMin; i <= intervalMax; i++)
{
result = i * multiplier;
System.out.println(i + " * " + multiplier + " = " + result);
}
}
}
You didn't consume what user entered into the scanner buffer, that's why sc.hasNextInt() keeps getting executed without waiting for the next user input.
The solution is to add sc.nextLine() after the if condition.
For example:
boolean gotInteger = false;
while (!gotInteger) {
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt()) {
multiplier = sc.nextInt();
gotInteger = true;
} else {
System.out.println("Input is not an integer\n");
}
sc.nextLine();
}
Pleas try this, just wrap all your code inside try catch:
try {
while (intervalMax == 0) {
System . out . println("\nPlease enter the integer defining the end of the table");
if (sc . hasNextInt()) {
int i = sc . nextInt();
if (i > intervalMin) {
intervalMax = i;
} else {
throw new Exception("\nEnd integer must be greater than start integer");
}
}
}
} catch (Exception e) {
System . out . println(e . getMessage());
}

Java: implement a loop with duplicate values in Array

My task is to enter names into an array. If the name has already been entered, the program must alert about that and offer to reenter the player under the same number.
This is my code:
public void enterNames() {
for (int i=0; i<nameOfPlayers.length; i++)
{
do
{
// isDuplicate is a Boolean initialized to false
System.out.println("CHECK": + isDuplicate);
System.out.println("Enter player " + (i+1) + ":");
nameOfPlayers[i] = in.next();
for (int k=0; k<nameOfPlayers.length; k++)
{
if (k!=i && nameOfPlayers[i].equals(nameOfPlayers[k]))
{
isDuplicate = true;
break;
}
}
} while (isDuplicate = false);
}
}
Interesting, even when I enter a duplicate value, it is caught and assigns true to isDuplicate, but when it returns to the beginning of the while loop, the value is false again ("CHECK: false").
Looks like an easy task, but I am caught...
Also, I did not want to use HashSet and wanted to use only Array.
Thanks a lot!
EDIT:
Thanks to others, I rewrote the code to the following:
public void enterNames() {
List<String> nameOfPlayersList = new ArrayList<String>();
int i = 0;
for (i=0; i<numberOfPlayers;)
{
while(true)
{
System.out.println("Enter player " + (i+1) + ":");
String input = in.next();
if(!nameOfPlayersList.contains(input))
{
nameOfPlayersList.add(input);
i++;
break;
}
System.out.println("Player " + input + " already exists, please retry");
}
}
}
Answer reformed, used List to add more and more elements without pre defined size.
changed while (isDuplicate == false); to while (!isDuplicate);
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<String> nameOfPlayers = new ArrayList<String>();
boolean isDuplicate = false;
int i = 0;
do {
System.out.println("Enter player " + (i + 1) + ": or Q for Quit");
String input = scanner.next();
if (!input.equalsIgnoreCase("Q")) {
if (nameOfPlayers.contains(input)) {
isDuplicate = true;
} else {
nameOfPlayers.add(input);
isDuplicate = false;
}
System.out.println("CHECK : " + isDuplicate);
} else {
break;
}
i++;
} while (!isDuplicate);
}
Enter player 1: or Q for Quit
ankur
CHECK : false
Enter player 2: or Q for Quit
singhal
CHECK : false
Enter player 3: or Q for Quit
ankur
CHECK : true
The problem you are having is because of the
} while (isDuplicate = false);
it should be (mind the double ==)
} while (isDuplicate == false);
Apart from that your code is quite inefficient. You would probably do much better with two Arrays if that is really what you want, otherwise a linked list would be best.
Your while is incorrect, this
while (isDuplicate = false);
assigns false to isDuplicate which has a side-effect of also evaluating to false. You watned something like
while (isDuplicate == false);
or the shorter
while (!isDuplicate);

Categories

Resources