Avoiding null in an array? - java

I'm a novice coder and we are given a task in college to only use Arrays
(I asked the teacher and said no array lists or whatsoever, wants to do it the rough way)
its about making an array that you are able to insert, search, or delete a value in it. I figured out the most of it by searching and applying out solutions.
But they wanted an output so that if I delete THEN I search that value, it would display that the value is gone, but the problem is since that value is deleted Java places a null in there, so when the for loop cycles through all of the nulls it creates the dreaded NullPointerException error. I'm currently searching right now for solutions with these limitations but to no avail, plus my Java vocabulary and terminology is admittedly short at the moment :P
import static java.lang.System.out;
import java.util.Scanner;
public class JavaApplication
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
//initialize String array x20
String[] regName = new String[20];
int regCount = 0;
int func = 0;
while (func == 0) //Main Menu Looper
{
out.println("Select function by entering its number.");
out.println("[1] Insert");
out.println("[2] Search");
out.println("[3] Delete");
out.println("[4] Exit");
out.print("Choose Operation: ");
func = kb.nextInt(); //Choose Option
out.print("======================================");
out.print("\n");
switch (func)
{
case 1: //Insertion
//set Array index start
char yesNo;
do
{
//Inserting into arrays loop
out.print("Insert student last name: ");
regName[regCount] = kb.next();
regCount++;
out.print("\n");
//Viewing loop
out.println("Student List: ");
for (int ctrl = 0; ctrl < regCount; ctrl++)
{
out.println(regName[ctrl]);
}
out.print("\n");
//Question loop
out.print("You want to insert again(Y/N):");
yesNo = kb.findWithinHorizon(".", 0).charAt(0);
if (yesNo == 'y' || yesNo == 'Y')
{
yesNo = 'y';
}
} while (yesNo == 'y');
func = 0;
break;
case 2: //Searching
out.print("Enter keyword: ");
String search = kb.next();
boolean found = false;
int searchCount = 0;
for (int ctrl = 0; ctrl < regCount; ctrl++)
{
if (regName[ctrl].equalsIgnoreCase(search)) {
found = true;
out.println(search + " has " + " a match.");
}
else
{
out.println(search + " has " + " not found.");
}
}
out.print("\n");
func = 0;
break;
case 3: //Deleting
out.print("type surname you want to delete: ");
String toDelete = kb.next();
for (int ctrl = 0; ctrl < regCount; ctrl++)
{
if (regName[ctrl].equalsIgnoreCase(toDelete)) {
regName[ctrl] = null;
out.println("Record deleted.");
}
}
out.print("\n");
func = 0;
break;
} //switch
} //while
} //main
} //class

Other answers propose checking for null. But this won't fix your problem. As the rest of your code expects no gaps in your list of students.
Try shifting the names after you delete some of them:
case 3: //Deleting
out.print("type surname you want to delete: ");
String toDelete = kb.next();
int deleted = 0;
for (int ctrl = 0; ctrl < regCount; ctrl++) {
if (regName[ctrl].equalsIgnoreCase(toDelete)) {
out.println("Record deleted.");
deleted++;
}
if(deleted > 0) {
int newCtrl = ctrl + deleted;
regName[ctrl] = (newCtrl < regCount) ? regName[newCtrl] : null;
}
}
regCount -= deleted;
out.print("\n");
func = 0;
break;
This solution assumes that your application allows duplicated entries.
Also I've found that your search operation prints <Name> has not found multiple times even if there is a match. Try changing it like this:
case 2: //Searching
out.print("Enter keyword: ");
String search = kb.next();
boolean found = false;
int searchCount = 0;
for (int ctrl = 0; ctrl < regCount; ctrl++) {
if (regName[ctrl].equalsIgnoreCase(search)) {
found = true;
out.println(search + " has a match : #" + ctrl);
break;
}
}
if(!found) {
out.println(search + " has not found.");
}
out.print("\n");
func = 0;
break;
UPDATE: deleting only first occurrence
case 3: //Deleting
out.print("type surname you want to delete: ");
String toDelete = kb.next();
int deletedIndex = -1;
for (int ctrl = 0; ctrl < regCount; ctrl++) {
if(deletedIndex >= 0) {
int newCtrl = ctrl + 1;
regName[ctrl] = (newCtrl < regCount) ? regName[newCtrl] : null;
} else if (regName[ctrl].equalsIgnoreCase(toDelete)) {
deletedIndex = ctrl;
out.println("Record deleted : #" + deletedIndex);
regCount--;
}
}
out.print("\n");
func = 0;
break;

When searching, check for null before calling equalsIgnoreCase on it.
if (regName[ctrl]!=null && regName[ctrl].equalsIgnoreCase(search)) {
found = true;
out.println(search + " has " + " a match.");
}
else
{
out.println(search + " has " + " not found.");
}

Consider Null checks whenever you code using any data structure for avoiding un-checked exceptions. So you can add the check first which executes first and if true then only proceeds further.
if (regname[ctrl] != null && regName[ctrl].equalsIgnoreCase(search)) {
Hope this helps you solve your problem!

Just do null checks: if (regName[ctrl].equalsIgnoreCase(search)) { can become if (regname[ctrl] != null && regName[ctrl].equalsIgnoreCase(search)) { and so on.
This is equivalent to:
if (regname[ctrl] != null)
{
if (regName[ctrl].equalsIgnoreCase(search))
{
...
Because of the way Java evaluates expressions the second part will only be done if the first is ok - in your case only try to use the array if the value at that index is not null)
If you want to impress your teacher break the insert search and delete into different methods.

Related

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.

Searching through an array for a name with a for loop

I need help in designing a for loop that returns the name if found and if it is not found it returns the requested name as not found. I need to do this without repeating the not found loop multiple times.
I have tried various if, else if, and else statements. I have also tried a do while loop inside of the for loop and also tried to do the not found statement outside of the loop
String[] values = new String[12];
int name = 1;
// Initialize Scanner
java.util.Scanner input = new java.util.Scanner(System.in);
// Create loop for name input
for (int i = 0; i < values.length; i++)
{
System.out.print("Enter in " + " the name of friend " + name++ + ": ");
values[i] = new String(input.next());
if (values[i].equalsIgnoreCase("zzzz"))
{
break;
}
}
// Create loop for name output
System.out.println("\n" + "The names of your friends are: ");
for (int i = 0; i < values.length; i++)
{
if (values[i].equalsIgnoreCase("zzzz"))
{
break;
}
else
{
System.out.println(values[i]);
}
}
// Search for the name
boolean found = false;
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
for(int i = 0;i < values.length && !found;++i)
{
if (find.equalsIgnoreCase(values[i]))
{
System.out.println("\n" + "Your friend " + find + " was found");
found = true;
break;
}
else if (find != values[i] && (found = false))
{
System.out.println("\n" + "Your friend " + find + " was not found" );
break;
}
}
}
}
I expect the not found statement to not be reiterated multiple times through the loop until the actual name is found. If the name does not exist in the array, it should search through the whole array and return that it was not found.
See my attempt. I have cast all elements to lower case whilst we iterate through the array to ensure we don't miss a match. For example if we searched for
"tom" and in the array we had "Tom" the match would be missed.
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
boolean foundFlag = false;
String[] values = new String[12];
//Populate array
for(int i = 0, x = 1; i < values.length; i ++, x ++)
{
System.out.print("Enter name of friend " + x + ": " );
String name = input.next();
values[i] = name;
}
//Output all elements of the array
System.out.println("\n" + "The names of your friends are: ");
for(String x : values)
{
System.out.println(x);
}
//Find a friend
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
//Iterate through array and check if Friend inside.
for(int i = 0; i < values.length; i ++)
{
if(values[i].toLowerCase().equals(find.toLowerCase()))
{
foundFlag = true;
break;
}
}
//If friend in the array flag will be True, else flag will remain false.
if (foundFlag)
{
System.out.println("Friend " + find + " found");
}
else
{
System.out.println("Friend " + find + " not found");
}
}
}
just create a function to do your searching:
public boolean findName(String[] items, String name) {
if (items == null || items.length == 0 || name == null || name.trim().isEmpty()) return false;
for(int i = 0; i < items.length; i++) {
if (items[i].equalsIgnoreCase(name.trim())) {
return true;
}
}
return false;
}
Then where ever you need to find a friend:
boolean exists = findName(values, "Foo Bar");
if (exists) {
System.out.println("Friend exists");
} else {
System.out.println("Friend does not exists");
}
You can use also java 8 streams :
boolean found = Stream.of(values)
.anyMatch(value -> value.equalsIgnoreCase(name));
try to use this code :
// Search for the name
boolean found = false;
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
for(int i = 0;i < values.length && !found;++i)
{
if (find.toLowerCase().equals(values[i].toLowerCase()))
{
System.out.println("\n" + "Your friend " + find + " was found");
found = true;
break;
}
}
if(!found){
System.out.println("\n" + "Your friend " + find + " was not found" );
}
}

Making the first input save in a folder first and then reference it

I need my program to detect previous entries in it's contact list and negate the user from inputting two identical entries. I keep trying, but I either allow every entry, or the entry that's invalid is still saved to my list.
What I want is to make it so my program will be a phone book, and no two people in real life should have the same number. This is why I want there to be only one contact with any given number.
Here's my code for checking the entry:
System.out.print("Enter Number: ");
number = stdin.nextLine(); // read the number
while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
System.out.println("Error!");
System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
", or \"012-345-6789\" format.");
System.out.print("Enter number: ");
number = stdin.nextLine();
}
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
return;
}else{
break;
}
}
contactList[num_entries].number = number;
Here's my full code for reference:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
class Entry {
public String fname, lname, number, note;
}
class PBN {
public static Entry[] contactList;
public static int num_entries;
public static Scanner stdin = new Scanner(System.in);
public static void main(String args[]) throws Exception{
Scanner s = new Scanner(System.in);
int i;
char C;
String code, Command;
contactList = new Entry[999];
num_entries = 0;
try {
readPhoneBook("PhoneBook.txt");
} catch (FileNotFoundException e) {}
System.out.println("Codes are entered as 1 to 8 characters.\n" +
"Use Commands:\n" +
" \"e\" for enter a new contact,\n" +
" \"f\" for find contact by fist name,\n" +
" \"r\" for find contact by last name,\n" +
" \"y\" for find contact by phone number,\n" +
" \"l\" for listing all the existing contacts,\n" +
" \"d\" for removing contacts by phone number,\n" +
" \"a\" for sort alphabetically by first name,\n" +
" \"n\" for sort alphabetically by last name,\n" +
" \"p\" for sort by number,\n" +
" \"q\" to quit.");
Command = null;
C = ' ';
while(true) { // loop infinitely
System.out.print("Command: ");
Command = stdin.nextLine();
C = Command.charAt(0);
switch (C) {
case 'e': addContact(); break;
case 'f':
System.out.print("Search for contact by first name: ");
code = stdin.next();
stdin.nextLine();
index(code); break;
case 'r':
System.out.print("Search for contact by last name: ");
code = stdin.next();
stdin.nextLine();
index1(code); break;
case 'y':
System.out.print("Search for contact by phone number: ");
code = stdin.next();
stdin.nextLine();
index2(code); break;
case 'l':
listAllContacts(); break;
case 'q': // when user wants to quit
CopyPhoneBookToFile("PhoneBook.txt");
System.out.println("Quitting the application. All the entries are "
+ "stored in the file PhoneBook1.txt");
System.exit(0); // simply terminate the execution
case 'a':
sortList1();
break;
case 'n':
sortList2();
break;
case 'p':
sortListByPhoneNumber();
break;
case 'd': // m for deleting a contact; delete by phone number
System.out.print("Enter the phone number of a contact you wish to delete : ");
String number = stdin.nextLine();// read the contact number
removeEntry1(number); // remove the number from the entries
break;
default:
System.out.println("Invalid command Please enter the command again!!!");
}
}
}
public static void readPhoneBook(String FileName) throws Exception {
File F;
F = new File(FileName);
Scanner S = new Scanner(F);
while (S.hasNextLine()) {
contactList[num_entries]= new Entry();
contactList[num_entries].fname = S.next();
contactList[num_entries].lname = S.next();
contactList[num_entries].number = S.next();
contactList[num_entries].note = S.nextLine();
num_entries++;
}
S.close();
}
public static void addContact() {
System.out.print("Enter first name: ");
String fname = stdin.nextLine();
String lname;
String number;
String pattern = "^\\(?(\\d{3})?\\)?[- ]?(\\d{3})[- ](\\d{4})$";
while (fname.length() > 8 || fname.length() < 1) {
System.out.println("First name must be between 1 to 8 characters.");
System.out.print("Enter first name: ");
fname = stdin.nextLine();
}
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname;
System.out.print("Enter last name: ");
lname = stdin.nextLine();
while (lname.length() > 8 || lname.length() < 1) {
System.out.println("First name must be between 1 to 8 characters.");
System.out.print("Enter first name: ");
lname = stdin.nextLine();
}
contactList[num_entries].lname = lname;
System.out.print("Enter Number: ");
number = stdin.nextLine(); // read the number
while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
System.out.println("Error!");
System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
", or \"012-345-6789\" format.");
System.out.print("Enter number: ");
number = stdin.nextLine();
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
break;
} else {
return;
}
}
}
contactList[num_entries].number = number;
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine();
num_entries++;
System.out.println();
}
public static void listAllContacts() {
for(Entry e : contactList) {
if(e != null)
displayContact(e);
else
break;
}
}
public static int index(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].fname.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static int index1(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].lname.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static int index2(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].number.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static void displayContact(Entry contact) {
System.out.println("--"+ contact.fname+"\t");
System.out.println("--"+ contact.lname+"\t");
System.out.println("--"+ contact.number+"\t");
System.out.println("--"+ contact.note);
System.out.println("");
}
public static void sortList1() {
int i;
Entry temp;
temp = new Entry();
for (int j = 0; j< num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].fname.compareToIgnoreCase(contactList[i].fname)> 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}listAllContacts();
}
public static void sortList2() {
int i;
Entry temp;
temp = new Entry();
for (int j = 0; j< num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].lname.compareToIgnoreCase(contactList[i].lname)> 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}listAllContacts();
}
public static void CopyPhoneBookToFile(String FileName) throws Exception{
FileOutputStream out = new FileOutputStream(FileName);
PrintStream P = new PrintStream( out );
for (int i=0; i < num_entries; i++) {
P.println(
contactList[i].fname + "\t" +
contactList[i].lname + "\t" +
contactList[i].number + "\t" +
contactList[i].note);
}
}
public static void removeEntry1(String number) {
Entry[] newcontactList = new Entry[contactList.length];
int i = 0;
for(Entry e : contactList) {
if(e == null) break; // if an entry is null then break the loop
if(e.number.equals(number)) // if the given number matches the current number
continue; // then skip
newcontactList[i++] = e;
}
num_entries--; // decrease the number of entries by 1;
contactList = newcontactList;
}
public static void sortListByPhoneNumber() {
int i;
Entry temp;
for (int j = 0; j < num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].number.compareToIgnoreCase(contactList[i].number) > 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}
listAllContacts();
}
}
The problem is that while you are looping through your contactList in for (Entry e : contactList) you are not checking the whole list!
E.g. if in the first cycle e.number doesn't equal the new number it goes to else statement and breaks the loop, then it goes and calls contactList[num_entries].number = number; saving potentially the already existing number;
To fix your code with minimum changes - just remove the else{ break;}
If you want a safer and more performant solution, use HashSet data structure for your contactList or TreeSet if you want it to be sorted - it will make sure that you will never have a duplicate entry, you can use Set.contains(number) to check if the entry already exists, and additionally HashSet will improve the complexity of entry lookups to O(1), TreeSet slightly worse O(logn) - either better then looping through the whole array which is O(n).
One way you can do that by using a boolean
boolean isPresent = false;
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
isPresent = true;
break;
}
}
Now check if the variable changed or not and do the entry
if (!isPresent) {
contactList[num_entries].number = number;
//rest of code
}
In Java 8 you could use optional
Optional<String> presentPh = Arrays.stream(contactList).filter(e -> e.number.equals(number)).findAny();
Now check if you find anything in filter
if (!presentPh.isPresent()) {
contactList[num_entries].number = number;
//rest of code
}

Can someone explain why this code keeps looping?

i'm still quite new to java, can someone explain when i enter a value that meets the requirements (1-10) that the code keeps looping back to the initial for loop? How can i amend the code to fix the problem and allow to function properly?
public void rateEpisode(Scanner sc, String seriesName, int searchEpisodeNumber, ArrayList<TVSeries> tvSeries) {
for(int i = 0; i<tvSeries.size(); i++) {
for(int j = 0; j< tvSeries.get(i).getListOfEpisodes().size(); j++){
if((seriesName.equals(tvSeries.get(i).getTitle())) &&
(searchEpisodeNumber == tvSeries.get(i).getListOfEpisodes().get(j).getEpisodeNumber())){
System.out.println("Please enter your rating(1-10) of " + tvSeries.get(i).getTitle() + ", Episode " + tvSeries.get(i).getListOfEpisodes().get(j).getEpisodeNumber() + ". "
+ tvSeries.get(i).getListOfEpisodes().get(j).getEpisodeName() + " : ");
boolean validInput = false;
int userEpRating = -1;
do{
System.out.println("Test");
validInput = false;
if(sc.hasNextInt()){
userEpRating=sc.nextInt();
sc.nextLine();
if(userEpRating < 11 && userEpRating > 0){
validInput = true;
} else{
System.out.println("Please enter a rating between 1 and 10: ");
sc.nextLine();
}
}else{
System.out.println("Please enter an integer between 1 and 10: ");
sc.nextLine();
}
}while(!validInput);
tvSeries.get(i).getListOfEpisodes().get(j).setUserEpReview(userEpRating);
}
}
}
}
Move this line
tvSeries.get(i).getListOfEpisodes().get(j).setUserEpReview(userEpRating);
to here:
if(userEpRating < 11 && userEpRating > 0){
validInput = true;
tvSeries.get(i).getListOfEpisodes().get(j).setUserEpReview(userEpRating);
return;
}
...
and add return after it.
When you call return in a method that returns nothing (void) then the method exists immediately.

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