Can someone explain why this code keeps looping? - java

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.

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.

How to break from a loop after finding a word

I am trying to create a Hangman and I have 2 problems.
1) The first problem is when the user finds the word, the loop does not stop.
2) I have a variable attempts which allows to know the number of attempts. Even if the user finds the letter, the number of attempts decrease.
The word to find is no
Here is a demonstration:
1) I enter the letter n
You have 5 attempts.
--
Enter your letter : n
2) I enter the letter o
The letter is good.
You have 4 attempts.
n-
Enter your letter : o
3) Normally the loop should stop.
The letter is good.
You have 3 attempts.
no
Enter your letter :
If you have an idea thank you in advance.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
attempts--;
}
}
}
You are just missing a checking loop or method. Check the solution below.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
boolean done = true;
for(boolean b : word_found)
done = done && b;
if(done) break;
else attempts--;
}
I will follow to your solution, not suggest a better one.
Ad 1. Add a check if the array word found contains only true after your first for cycle and if there are only true values in the array, print "you won" and set attempts to 0
Ad 2. Move attempts-- to the else case of your first for cycle OR add attempts++ in the true case of your first for cycle
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = { /* "yes", */ "no" };
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while (attempts > 0) {
System.out.println("You have " + attempts + " attempts.");
for (int i = 0; i < word_random.length(); i++) {
if (word_found[i]) {
System.out.print(word_random.charAt(i));
} else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
boolean match = false;
for (int i = 0; i < word_random.length(); i++) {
if (word_random.charAt(i) == letter) {
System.out.println("The letter is good. ");
word_found[i] = true;
match = true;
if (i == word_found.length - 1) {
System.out.println("THE END: attempts: " + attempts);
return;
}
}
}
if (!match) {
attempts--;
}
}
System.out.println("THE END");
}
I suggest you to modify the last part of your code like I did, and it should work.

Avoiding null in an array?

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.

my 2nd if statement is being ignored dont know why

Hello guys i am basically creating a program that takes about 5 inputs from users and stores them in an array called course....every time user enter 1 course i want to ask the user if he wants to continue.. if he type yes the program continues or else it shows the values in array(course)......
i am facing issues :-
1.i dont wanna ask user to continue if he is already entering the last value which is 5th one.
2.my 2nd loop is basically being ignored i dont know why if it works every thing would've been ok.
3.if the user enters last value and press yes according to my program it is still not printing the values in my course(array).
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ArrayExample;
import java.util.Scanner;
/**
*
* #author jodh_
*/
public class ArrayExample {
public static void main(String args[]) {
String[] course = new String[5];
for (int i = 0; i < 5; i++) {
System.out.println("Please enter course name " + (i + 1) + ": ");
Scanner gettingname = new Scanner(System.in);
String coursenames = gettingname.nextLine();
course[i] = coursenames;
if (i < 4) {
for(int j =0; j<4; j++){
System.out.println("");
System.out.println("Would you like to continue? ((y)Yes / (n)No)");
Scanner gettingYesOrNo = new Scanner(System.in);
String input = gettingYesOrNo.nextLine();
if (input.equals("yes") || input.equals("y") || input.equals("Y") || input.equals("YES") || input.equals("Yes")) {
System.out.println("");
break;
} else if (input.isEmpty()) {
System.out.println("Input cannot be empty!! Please try again");
} else if (input.equals("no") || input.equals("No") || input.equals("NO") || input.equals("n") || input.equals("N")) {
System.out.println("Your select courses are as follows");
}
for (int x = 0; x < i + 1; x++) {
System.out.println("");
System.out.println((x + 1) + ": " + course[x]);
}
System.exit(0);
}
}
}
}
}
This will work fine if you change the break to continue.Try my code.
String[] course = new String[5];
for (int i = 0 ; i < 5 ; i++){
System.out.println("Please enter course name " + (i + 1) + ": ");
Scanner gettingname = new Scanner(System.in);
String coursenames = gettingname.nextLine();
course[i] = coursenames;
if (i < 4){
System.out.println("");
System.out.println("Would you like to continue? ((y)Yes / (n)No)");
Scanner gettingYesOrNo = new Scanner(System.in);
input = gettingYesOrNo.nextLine();
if (input.equals("yes") || input.equals("y") || input.equals("Y") || input.equals("YES") || input.equals("Yes")) {
System.out.println("");
continue;
} else if (input.isEmpty()) {
System.out.println("Input cannot be empty!! Please try again");
} else if (input.equals("no") || input.equals("No") || input.equals("NO") || input.equals("n") || input.equals("N")) {
System.out.println("Your select courses are as follows");
}
}
for (int x = 0; x < i + 1; x++) {
System.out.println("");
System.out.println((x + 1) + ": " + course[x]);
}
}
}
Here is the output
Please enter course name 1:
androiid
Would you like to continue? ((y)Yes / (n)No)
y
Please enter course name 2:
dsfnfv
Would you like to continue? ((y)Yes / (n)No)
y
Please enter course name 3:
sfgngff
Would you like to continue? ((y)Yes / (n)No)
y
Please enter course name 4:
grgngr
Would you like to continue? ((y)Yes / (n)No)
y
Please enter course name 5:
fgmt
1: androiid
2: dsfnfv
3: sfgngff
4: grgngr
5: fgmt
Process finished with exit code 0
I've made quite a few changes in your code like removing some unnecessary loops but its working now
public static void main(String args[]) {
String[] course = new String[5];
Scanner gettingname = new Scanner(System.in);
int i=0;
for (; i < 5; i++) {
System.out.println("Please enter course name " + (i + 1) + ": ");
course[i] =gettingname.nextLine();
System.out.println("");
if(i==4) break;
System.out.println("Would you like to continue? ((y)Yes / (n)No)");
Scanner gettingYesOrNo = new Scanner(System.in);
String input = gettingYesOrNo.nextLine();
if (input.equals("yes") || input.equals("y") || input.equals("Y") || input.equals("YES") || input.equals("Yes")) {
System.out.println("");
continue;
}
else if (input.isEmpty()) {
System.out.println("Input cannot be empty!! Please try again");
}
else if (input.equals("no") || input.equals("No") || input.equals("NO") || input.equals("n") || input.equals("N")) {
break;
}
}
System.out.println("Your select courses are as follows");
for (int x = 0; x < i+1 ; x++) {
System.out.println("");
System.out.println((x + 1) + ": " + course[x]);
}
}
}
This is why code formatting is so very important! Spacing the nested if/else if/for statements allows you to follow the logic of your program much quicker and easier.
Here is a formatted version of your code:
import java.util.Scanner;
/** * * #author jodh_ */
public class ArrayExample
{
public static void main(String args[])
{
String[] course = new String[5];
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter course name " + (i + 1) + ": ");
Scanner gettingname = new Scanner(System.in);
String coursenames = gettingname.nextLine();
course[i] = coursenames;
if (i < 4)
{
for(int j =0; j<4; j++)
{
System.out.println("");
System.out.println("Would you like to continue? ((y)Yes / (n)No)");
Scanner gettingYesOrNo = new Scanner(System.in);
String input = gettingYesOrNo.nextLine();
if (input.equals("yes") || input.equals("y") || input.equals("Y") || input.equals("YES") || input.equals("Yes"))
{
System.out.println("");
break;
}
else if (input.isEmpty())
{
System.out.println("Input cannot be empty!! Please try again");
}
else if (input.equals("no") || input.equals("No") || input.equals("NO") || input.equals("n") || input.equals("N"))
{
System.out.println("Your select courses are as follows");
}
for (int x = 0; x < i + 1; x++)
{
System.out.println("");
System.out.println((x + 1) + ": " + course[x]);
}
System.exit(0);
}
}
}
}
}
In this formatted code we can easily see where each piece of code is being executed.
If you take a look at the part that checks for "yes" you will see that if the conditions are met it breaks out of the inner for loop. This means that all code underneath this break within the inner loop is not executed if the user gives an answer of "yes".
if (input.equals("yes") || input.equals("y") || input.equals("Y") || input.equals("YES") || input.equals("Yes"))
{
System.out.println("");
break;
}
Your print statement is inside this inner for loop, which in fact means that it will only execute if the conditions of the "yes" if statement are not met. If you were to input the text "cat" in the "would you like to continue?" prompt it would skip all the if/else if statements since none of them are being met, execute the print loop, output the courses, and System.exit(0); terminate the program.
It appears that the intended purpose is to output the courses if the user inputs "no". So lets see if we can move the print loop inside the "no" if.
else if (input.equals("no") || input.equals("No") || input.equals("NO") || input.equals("n") || input.equals("N"))
{
System.out.println("Your select courses are as follows");
for (int x = 0; x < i + 1; x++)
{
System.out.println("");
System.out.println((x + 1) + ": " + course[x]);
}
System.exit(0);
}
This will output the courses only if the user inputs "no". And then it will termanate the program. Perfect!
So lets talk about this empty input condition:
else if (input.isEmpty())
{
System.out.println("Input cannot be empty!! Please try again");
}
Unless you need to specifically check that the input is empty you probably want to replace this with just an else statement. Lets see what that would look like.
if (input.equals("yes") || input.equals("y") || input.equals("Y") || input.equals("YES") || input.equals("Yes"))
{
System.out.println("");
break;
}
else if (input.equals("no") || input.equals("No") || input.equals("NO") || input.equals("n") || input.equals("N"))
{
System.out.println("Your select courses are as follows");
for (int x = 0; x < i + 1; x++)
{
System.out.println("");
System.out.println((x + 1) + ": " + course[x]);
}
System.exit(0);
}
else
{
System.out.println("Invalid input!! Please try again.");
j--;
}
You need to decrement j because at the end of the for loop it will increment forward to the next course. Since the user input was invalid we want to keep the course iterator right where it is and continue to ask the user if they woud like to continue until a valid selection has been made.
We're almost there!
Now that we have sorted the input conditions, what happens when the user reaches the 5th course?
Right now we only have the courses print if the user answers "no". So at the end of the course loop we need to print the full course string array. The final product looks like so:
import java.util.Scanner;
/** * * #author jodh_ */
public class ArrayExample
{
public static void main(String args[])
{
String[] course = new String[5];
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter course name " + (i + 1) + ": ");
Scanner gettingname = new Scanner(System.in);
String coursenames = gettingname.nextLine();
course[i] = coursenames;
if (i < 4)
{
for(int j =0; j<4; j++)
{
System.out.println("");
System.out.println("Would you like to continue? ((y)Yes / (n)No)");
Scanner gettingYesOrNo = new Scanner(System.in);
String input = gettingYesOrNo.nextLine();
if (input.equals("yes") || input.equals("y") || input.equals("Y") || input.equals("YES") || input.equals("Yes"))
{
System.out.println("");
break;
}
else if (input.equals("no") || input.equals("No") || input.equals("NO") || input.equals("n") || input.equals("N"))
{
System.out.println("Your select courses are as follows");
for (int x = 0; x < i + 1; x++)
{
System.out.println("");
System.out.println((x + 1) + ": " + course[x]);
}
System.exit(0);
}
else
{
System.out.println("Invalid input!! Please try again");
j--;
}
}
}
}
System.out.println("Your select courses are as follows");
for (int x = 0; x < 5; x++)
{
System.out.println("");
System.out.println((x + 1) + ": " + course[x]);
}
}
}
Note: There are more optimal ways to get to the same result but I tried to keep the code as close to the original logic as possible.
Here's some code I wrote that might fix your program. You'll have to implement the rest but it should be easy enough.
import java.util.Scanner;
public class ArrayExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String[5];
String yesOrNo;
int index = 0;
do{
System.out.println("Please enter course name " + (index + 1) + ": ");
course[index] = input.nextLine();
if(index < 4) {
System.out.println("Would you like to continue? ((y)Yes / (n)No)");
yesOrNo = input.nextLine();
}
index++;
}while(yesOrNo.toLowerCase().startsWith("y) && index < 5)
//if the loop is exited then we know either the user chose not to continue or all the course names have been filled
//handle that here
}
}
The logic of what I did:
The while loop condition makes it so that you won't continue looping when all the courses are filled. And inside of the loop it checks if the index is not 4.
there's no more need for your second loop
you can print your array after the loop now.
Making two scanners is completely useless and takes up memory because you didn't even close them.
I hope this helps.

Categories

Resources