So I got this java chatbot program that I'm working on.
Depending on what the user says, the chatbot either gives a canned response canned_phrases or a mirrored response if the user's response has one of the keywords I love pizza --> you love pizza.
The problem is that the chatbot does not give back the mirrored version. I think the problem is that the words are being overwritten by each other but I'm not sure how to fix that.
Thank for your help!
import java.util.Random;
import java.util.Scanner;
public class Conversation {
public static void main(String[] args) {
String[] canned_phrases = {"Yes",
"Hmmm. Please tell me more news",
"Of course",
"Okay",
"Interesting...",
"Indeed"};
int canned_times = canned_phrases.length;
Scanner conversation_start = new Scanner(System.in);
System.out.println("\nWelcome!\n");
System.out.println("How many rounds of conversation would you like to have?\n");
int rounds = conversation_start.nextInt();
conversation_start.nextLine();
String[] transcript = new String[2 * rounds + 1];
transcript[0] = "Sounds great! How are you doing today?";
System.out.println(transcript[0]);
for (int i = 0; i < rounds; i++) {
String user_words = conversation_start.nextLine();
String mirrored;
String new_version = user_words.replace("I", "you");
new_version = new_version.replace("me", "you");
new_version = new_version.replace("am", "are");
new_version = new_version.replace("you", "I");
new_version = new_version.replace("my", "your");
new_version = new_version.replace("your", "my");
new_version = new_version.replace("my", "you");
if (!new_version.equals(user_words)) {
mirrored = new_version;
}
else {
mirrored = canned_phrases[(int) Math.floor(canned_times * Math.random())];
}
System.out.println(mirrored);
transcript[2 * i + 1] = user_words;
transcript[2 * i + 1] = mirrored;
}
System.out.println("Thank you for chatting with me! Come back soon!");
System.out.println(" ");
System.out.println("TRANSCRIPT ");
for (int i = 0; i <= transcript.length; i++) {
System.out.println(transcript[i]);
}
System.exit(0);
}
}
I think the best way to achieve what you want is to split the user-entered sentence into words and change the individual words according to your rules, for example if the word is my then change it to your. In the below code, I iterate through all the words in order, changing each word as needed and appending them to a StringBuilder so that after iterating through all the words, the StringBuilder contains the mirrored sentence.
(More notes after the code.)
import java.util.Random;
import java.util.Scanner;
public class Conversation {
public static void main(String[] args) {
String[] cannedPhrases = {"Yes",
"Hmmm. Please tell me more news",
"Of course",
"Okay",
"Interesting...",
"Indeed"};
int cannedTimes = cannedPhrases.length;
Random rand = new Random();
Scanner conversationStart = new Scanner(System.in);
System.out.println("\nWelcome!\n");
System.out.println("How many rounds of conversation would you like to have?\n");
int rounds = conversationStart.nextInt();
conversationStart.nextLine();
String[] transcript = new String[2 * rounds];
transcript[0] = "Sounds great! How are you doing today?";
System.out.println(transcript[0]);
int index = -1;
for (int i = 0; i < rounds; i++) {
String userWords = conversationStart.nextLine();
String mirrored;
StringBuilder result = new StringBuilder();
String[] words = userWords.split(" ");
boolean first = true;
for (String word : words) {
if (first) {
first = false;
}
else {
result.append(' ');
}
switch (word) {
case "I":
word = "you";
break;
case "me":
word = "you";
break;
case "am":
word = "are";
break;
case "you":
word = "I";
break;
case "my":
word = "your";
break;
case "your":
word = "my";
break;
}
result.append(word);
}
String newVersion = result.toString();
if (!newVersion.equals(userWords)) {
mirrored = newVersion;
}
else {
mirrored = cannedPhrases[rand.nextInt(cannedTimes)];
}
System.out.println(mirrored);
transcript[++index] = userWords;
transcript[++index] = mirrored;
}
System.out.println("Thank you for chatting with me! Come back soon!");
System.out.println(" ");
System.out.println("TRANSCRIPT ");
for (int i = 0; i < transcript.length; i++) {
System.out.println(transcript[i]);
}
System.exit(0);
}
}
You should try to adhere to Java naming conventions. I changed the variable names in your code accordingly.
Rather than manipulate the [first] for loop variable i to handle both the conversation round and the transcript index, I used a separate variable, named index for the transcript.
Switching on string was added in Java 7.
The for loop that prints the transcript was wrong. The terminating condition should be i < transcript.length (and not i <= transcript.length).
The above code assumes that the user-entered sentence consists of words separated by single spaces. If you want more sophisticated handling of the user-entered sentence, for example handling punctuation, like commas, periods, etc, then you will need to change the split method's regular expression.
Here is output from a sample run:
Welcome!
How many rounds of conversation would you like to have?
2
Sounds great! How are you doing today?
OK
Of course
Why do you say that
Why do I say that
Thank you for chatting with me! Come back soon!
TRANSCRIPT
OK
Of course
Why do you say that
Why do I say that
I made little modification to your code and now it work as you expected:
public static void main(String[] args) {
String[] canned_phrases = {"Yes", "Hmmm. Please tell me more news", "Of course", "Okay", "Interesting...", "Indeed"};
int canned_times = canned_phrases.length;
Scanner conversation_start = new Scanner(System.in);
System.out.println("\nWelcome!\n");
System.out.println("How many rounds of conversation would you like to have?\n");
int rounds = conversation_start.nextInt();
conversation_start.nextLine();
String[] transcript = new String[2*rounds+1];
transcript[0] = "Sounds great! How are you doing today?";
System.out.println(transcript[0]);
for (int i = 0; i < rounds; i++) {
String user_words = conversation_start.nextLine();
String mirrored;
String new_version = user_words.replace("I", "you");
new_version = new_version.replace("me","you");
new_version = new_version.replace("am","are");
//1st change as you replaced it above so not swap it again
//new_version = new_version.replace("you","I");
new_version = new_version.replace("my","your");
new_version = new_version.replace("your","my");
new_version = new_version.replace("my","you");
//by commenting the line above, will enter the IF-block
if (!new_version.equals(user_words)) {
mirrored = new_version;
} else {
mirrored = canned_phrases[(int) Math.floor(canned_times * Math.random())];
}
System.out.println(mirrored);
transcript[2*i+1] = user_words;
//2nd change to not overwrite the same index i added 2 instead of 1
transcript[2*i+2] = mirrored;
}
System.out.println("Thank you for chatting with me! Come back soon!");
System.out.println(" ");
System.out.println("TRANSCRIPT ");
//3rd change i removed the = from the loop condition to prevent exception appeared
for (int i = 0; i < transcript.length; i++) {
System.out.println(transcript[i]);
}
System.exit(0);
}
Related
So I am completely new to java, and I want to create a code to accept string inputs from a user, and store it into an array. After this in the next statement, I will type a value into the terminal, and I want the code to compare my string input to one of the strings in the array and print available on the terminal when the string is available and vice versa. The first part of my code was right (hopefully) but I had a problem in comparing the strings. I feel it doesn't check the strings with my input in the code. Here is my code, Could anyone please help me with this? Thank you so much.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a[] = new String[20] //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() //entering a string to search
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) //I feel the problem is here
System.out.println(search + "course is available");
break;
else
System.out.println(search + "course is not available");
}
}
}
}
I expect the output to be
<string> course is available
when my string matches a string in the array and
<string> course is not available
when my entered string doesn't match a string in the array
But there is no output :(
I have modified your code and commented on line where it need to be explained. check it carefully.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
String a[] = new String[no_of_courses]; // do not assume when you have proper data.
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); // accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); // entering a string to search
boolean flag = false;
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) // I feel the problem is here
{
flag = true;//do not print here. just decide whether course is available or not
break;
}
}
//at the end of for loop check your flag and print accordingly.
if(flag) {
System.out.println(search + "course is available");
}else {
System.out.println(search + "course is not available");
}
}
}
}
class Course {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a[] = new String[20] ; //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if(no_of_courses <= 0)
System.out.println("Invalid Range");
else
{
System.out.println("Enter course names:");
for(int i=0 ; i < no_of_courses ; i++)
{
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() ; //entering a string to search
boolean found = false;
for(int i = 0 ; i < no_of_courses ; i++)
{
if(a[i].equalsIgnoreCase(search)) //I feel the problem is here
{
**found = true;**
break;
}
}
if(found) {
System.out.println(search+ "course is available");
}else {
System.out.println(search+ "course is not available");
}
}
}
}
This is really a good effort and you almost got it. So just a couple of things
Since you are inputting the number of courses, just use that value to initialise your array (it's just a good practice to get into to try not initialise things before you actually need them).
If you are doing String comparisons and case sensitivity does not matter, rather use .equalsIgnoreCase(String)
To solve your problem, you just needed a boolean variable to indicate whether or not you had found a match. Initially this would be FALSE (no match found) and you would run through your array until a match is found. Once found this would be flagged TRUE and you'd breakout your loop (which you correctly did).
Only once out your loop, you'd print out whether you found a match.
Have a look:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0) {
System.out.println("Invalid Range");
} else {
String a[] = new String[no_of_courses];
System.out.println("Enter course names:");
for (int i = 0; i < a.length; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); //entering a string to search
boolean courseFound = Boolean.FALSE;
for(int i = 0; i < a.length; i++) {
if (a[i].equalsIgnoreCase(search)) {
courseFound = Boolean.TRUE;
break;
}
}
if(courseFound) {
System.out.println(search + "course is available");
} else {
System.out.println(search + " course is not available");
}
}
}
Oh, just for interest (and when you start working with some more advanced constructs), you could always just use stream, which was introduced in Java 8. It'll trim down 12 lines to 5...
if(Arrays.stream(a).anyMatch(i -> i.equalsIgnoreCase(search))) {
System.out.println(search + " course is available");
} else {
System.out.println(search + " course is not available");
}
I noticed a few things - Does your program run to the end? When i copy/pasted into my ide i noticed a few missing semi-colons, and like Yhlas said, your last if/else statement syntax is incorrect.
And this doesn't have anything to do with whether or not your program will give you the right answer, but your last loop will print over and over again because it will check each element in a, and each time it loops and finds a mismatch it will print something out
For this program, I need to have the user input strings, which will then be put into an array along with their reversed counterparts. The entire array would then be alphabetized. So it should work like this:
Input: strawberry banana, apple, grapes
Output: apple, ananab, banana, elppa, grapes, separg, strawberry, yrrebwarts
I have the code for this, and it works to some degree. However, it only alphabetizes the reversed and the normal but separately. So it ends up looking like this:
Output: ananab, elppa, separg, yrrebwarts, apple, banana, grapes, strawberry
As you can see it is alphabetizing the words to some degree, but not how it should be. Here is my code:
import java.util.Scanner;
public class WordGame {
public static void main(String[] args) {
String reverseInput = " "; //creates an empty string where the reverse will be stored before putting it into the array
String[] wordArray = new String[1000]; //creates an array that allows for 500 words, and 500 reverses of said words
int s = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the words you would like to reverse. To finish entering words enter a blank line:");
String userInput = sc.nextLine(); //allows for user to input words
int length = userInput.length();
int i = 0;
while (!userInput.equals("")){ //runs until the user enters a blank line
reverseInput = " ";
for(i = length - 1; i >= 0; i--)
reverseInput += userInput.charAt(i);
wordArray[s] = userInput; //reverses user inputted strings by taking the last letter and putting it in front, repeating until the whole word is reversed
wordArray[s + 1] = reverseInput;
s += 2;
userInput = sc.nextLine();
length = userInput.length();
}
for(int j = 0; j < s-1; j++){ //beginning of alphabetical sorting
for(int k = 0; k < s-1-j; k++){
int l = 0;
while((int)wordArray[k].charAt(l) == (int)wordArray[k+1].charAt(l))
l++;
if ((int)wordArray[k].charAt(l) > (int)wordArray[k+1].charAt(l)){
String holder = wordArray[k];
wordArray[k] = wordArray[k+1];
wordArray[k+1] = holder;
}
}
}
for(i = 0; i < wordArray.length; i++){
if (wordArray[i]!= null){
System.out.print(wordArray[i] + " "); //prints out contents of array
}
}
}
}
I am not sure what the issue is. Any help would be much appreciated. Thanks!
As far as I can see you put an extra blank in front of your "reverseInput" with reverseInput = " ";
Because your reverse string won't start with a char you think (it starts with a blank) the result is not what you really want. Try to delete the blank and retry you code.
There are definitely easier ways to do this, depending on if you want to use Java's built in classes for this kind of thing. I just wrote this up, it accomplishes the sort with reversed Strings that you want.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
public static void main(String args[]) {
ArrayList<String> values = new ArrayList<String>();
values.add("strawberry");
values.add("banana");
values.add("apple");
values.add("grapes");
Solution s = new Solution();
values = s.sortList(values);
int itemCt = 1;
for (String item : values) {
System.out.println(itemCt + ": " + item);
itemCt++;
}
}
public ArrayList<String> sortList(List<String> strings) {
ArrayList<String> combinedList = new ArrayList<String>();
for (String str : strings) {
combinedList.add(str);
combinedList.add(new StringBuilder(str).reverse().toString());
}
Collections.sort(combinedList);
return combinedList;
}
}
Disclaimer, I've been at java for about a month. I'm completely lost on this. I'm trying to have a user input a phrase and if any strings in that phrase is found on the array, it returns the corresponding string in one line. if the string isn't found, it would just skip it.
so if someone typed in "dog eat my fish"
and the array holds:
dog perro
eat munched
fish yellow trout
it would return:
perro munched yellow trout
I haven't written the code to print out what I've got yet, but I know this code isn't working.
any help would be greatly appreciated.
import java.io.*;
import java.util.*;
public class ArrayTest2 {
public static void main(String[] args)
throws java.io.IOException {
Scanner input = new Scanner(System.in);
String userString = " ";
userString = englishString();
String[][] wordList = new String[10][2];
loadEnglishString(wordList);
}
public static String englishString() {
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a phrase to translate: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadEnglishString(String[][] wordList)
throws java.io.IOException {
String filName = " ";
filName = ("/home/chrism/ArrayTest2.txt");
Scanner input = new Scanner(new File(filName));
while(input.hasNextLine()) {
String line = input.nextLine();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
boolean stop = false;
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++)
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
break;
}
}
}
input.close();
}
}
You'll definitely want to change your for loop. Brackets are your friend.
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++) {
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
}
}
The way you had it, both increments were registering as dead code because your second break would always called the first time through the loop, and your else was registering as coupled with the first if(stop).
Edit: don't know for sure about how the else would couple, but the break is definitely called after the first run through.
//package com.myjava.stokenizerr;
import java.util.StringTokenizer;
public class MyStringTokenizer {
public static void main(String a[]){
/* your code for user input string */
/* assume input as dog eat my fish */
String input = "dog eat my fish";
String msg = "dog perro eat munched fish yellow trout";
StringTokenizer st1 = new StringTokenizer(msg," ");
StringTokenizer st2 = new StringTokenizer(input," ");
while(st1.hasMoreTokens()){
System.out.println(st1.nextToken()); // Store this one(first) string array
}
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken()); // Store in another(second) array
}
/* Now Compare both the arrays */
/* If the strings are equal then remove string from second array */\
/* If equal just skip it */
}
}
See the above code st1.nextToken() and st2.Tokens() will give you the values
For comparing take two loops
for(i==0;i<array1length();i++) {
for(j==0;j<array2length();j++) {
// Your code for comparsion
}
}
I am trying to create a simple hangman program in java for a school assignment and I have it working for the most part. The main problem I have with it is that it keeps printing out the hidden word twice. It also only goes through and asks the user to enter an word 8 times when it should be 15 times. Can someone tell me where I went wrong?
// Its in a separate method.
public static void application1() throws Exception {
// Tells the user about the game.
System.out.println("Welcome to Hangman!");
System.out.println("Please try to guess the word within 15 letters.");
String option = "";
// Creates a array of all the phrases.
String answer[] = new String[20];
answer[0] = "computer";
answer[1] = "radio";
answer[2] = "calculator";
answer[3] = "teacher";
answer[4] = "bureau";
answer[5] = "police";
answer[6] = "geometry";
answer[7] = "president";
answer[8] = "subject";
answer[9] = "country";
answer[10] = "environment";
answer[11] = "classroom";
answer[12] = "animals";
answer[13] = "province";
answer[14] = "month";
answer[15] = "politics";
answer[16] = "puzzle";
answer[17] = "instrument";
answer[18] = "kitchen";
answer[19] = "language";
do {
// Creates a random number to choose which word to choose from.
int rand = (int)(Math.random() * 20 + 0);
StringBuffer word = new StringBuffer("");
// This makes the unknown word as long as the actual word.
for (int i = 0; i < answer[rand].length(); i++) {
word.append("_");
}
System.out.println(word);
char input = ' ';
// This is where it checks the input and replaces the letters.
for (int i = 0; i < 15; i++) {
input = (char) System.in.read();
for (int j = 0; j < answer[rand].length(); j++) {
if (input == answer[rand].charAt(j)) {
word.setCharAt(j, input);
}
}
// This is where the hidden word get printed twice.
System.out.println(word);
}
// Asks the user if they want to restart the application.
System.out.println("Would you like to try again? (Y/N)");
option = input();
} while (option.equalsIgnoreCase("y"));
}
Use a Scanner to get your input.
Scanner in = new Scanner(System.in);
String line = in.nextLine();
char input = line.charAt(0);
I think System.in.read(); is returning the entered character and the enter key. (the \n char).
That makes your cycle run twice for each input, printing two times and looking like it only accepts 8 chars.
if (word.equals(answer[rand])) {
System.out.println("Congratulations! You guessed the word!");
// Asks the user if they want to restart the application.
System.out.println("Would you like to try again? (Y/N)");
option = input();
}
else if (i == 14) {
System.out.println("Sorry, you did not guess the word.");
// Asks the user if they want to restart the application.
System.out.println("Would you like to try again? (Y/N)");
option = input();
// Returns to the main menu.
menu();
}
This doesn't recognize the word is correct.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I have to write a piece of code that manages an event. There are 4 events with limited seats. I'm supposed to write string arrays for each one. The program will then add the name to the pertaining string. My problem is I don't know how to keep adding values to a String array using a loop without deleting the previous values. Any help will be greatly appreciated.
import java.util.Scanner;
public class Assignment_1 {
public static void main(String[] args) {
String [] Hockey_Game;
Hockey_Game = new String[10];
String [] Turner_Concert;
Turner_Concert = new String [5];
String [] Cats_Play;
Cats_Play = new String [3];
String [] StarTrek_Convention;
StarTrek_Convention = new String [3];
System.out.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
for (int i = 0; i < Hockey_Game.length; i++){
Hockey_Game[i] = name;
}
for (String x: Hockey_Game ){
System.out.print(x +",");
}
This should be doing what you're looking for...
import java.util.Scanner;
public class Assignment_1 {
public static void main(String[] args) {
String[] Hockey_Game;
int numHockey = 0;
Hockey_Game = new String[10];
String[] Turner_Concert;
int numConcert = 0;
Turner_Concert = new String[5];
String[] Cats_Play;
int numPlay = 0;
Cats_Play = new String[3];
String[] StarTrek_Convention;
int numCon = 0;
StarTrek_Convention = new String[3];
for (int user = 0; user < 1; user++) {
System.out
.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
switch (input) {
case 1:
if (numHockey < Hockey_Game.length) {
Hockey_Game[numHockey] = name;
}
numHockey++;
for (int j = 0; j < numHockey; j++) {
System.out.print(Hockey_Game[j] + ",");
}
break;
case 2:
if (numConcert < Turner_Concert.length) {
Turner_Concert[numConcert] = name;
}
numConcert++;
for (int j = 0; j < numConcert; j++) {
System.out.print(Turner_Concert[j] + ",");
}
break;
// ... continue for last two ...
}
}
}
}
I do agree with the other answerer that you should be using List/ArrayList for this, but if the purpose of the assignment was to use arrays, here's how you could do it.
Since you need to loop for 4 users (as per your comment), you should have a loop around the whole input process:
for (int i = 0; i < 4; i++) {
// read the input
// add name to correct array
}
You should keep counters for each of your event types:
// here come all your variable declarations
// declare the counters
int hockeyCounter = 0;
int tinaCounter = 0;
int catsCounter = 0;
int startrekCounter = 0;
// no need to redeclare the keyboard all the time, just once is enough
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
System.out.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
switch (input) {
case 1: Hockey_Game[hockeyCounter++] = name; break;
case 2: Turner_Concert[tinaCounter++] = name; break;
case 3: Cats_Play[catsCounter++] = name; break;
case 4: StarTrek_Convention[startrekCounter++] = name; break;
default: System.out.println(input + " is not a valid input");
}
}
Is this now perfect? No, not quite. There are still some problems:
I didn't account for the maximum number of available tickets. This code will crash if all customers want a ticket to the cats' play.
There is a lot of code duplication. It already annoyed me enough to ignore the previously mentioned problem.
Variable names should always start with a lowercase (and preferably use camelCase). This is a Java convention, which helps other people read your code.
It would be better to somehow solve all these problems at once. For this I would propose an array of arrays (although that is maybe more complicated for a beginner, but would make the code much simpler):
final int EVENT_COUNT = 4;
final String[] EVENTS = { "Hockey Game", "Tina Turner Concert",
"Cats Play", "Star Trek Convention" };
final int[] LIMITS = { 10, 5, 3, 3 };
String[][] buyers = new String[EVENT_COUNT][];
int[] counters = new int[EVENT_COUNT];
for (int i = 0; i < EVENT_COUNT; i++) {
buyers[i] = new String[LIMITS[i]];
}
final int CUSTOMER_COUNT = 4;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < CUSTOMER_COUNT; i++) {
System.out.println("Which Event would you like to purchase a ticket for?");
for (int j = 0; j < EVENT_COUNT; j++) {
System.out.print((j+1) + ". " + EVENTS[j] + " ");
}
System.out.println();
int input = keyboard.nextInt();
if (input < 1 || input > EVENT_COUNT) {
System.out.println(input + " is not a valid choice");
i--;
} else if (counters[input-1] >= LIMITS[input-1]) {
System.out.println(EVENTS[input-1] + " is sold out!");
i--;
} else {
System.out.println("Please enter your first and last name");
buyers[input-1][counters[input-1]++] = scan.nextLine();
}
}
Don't use String[] use List
List<String> event1 = new List<String>();
. . .
event1.add(name);
Also define an int[] (this time an array would suffice) that holds the maximum slots for each event, that way when the customer asks for a spot on an already maxed out event you can give him the bad news.
My problem is I don't know how to keep adding values to a String array using a loop without deleting the previous values.
Given the following string array definition:
String[] sa = new String[3];
You can replace existing elements' values...
sa[0] = "test"; // index 0 = "test"
sa[1] = "another"; // index 1 = "test", index 1 = "another"
sa[1] = "different"; // index 1 = "test", index 1 = "different"
You can append to a String array element just like a normal string...
sa[2] = "123"; // index 2 = "123"
sa[2] += "456"; // index 2 = "123456"
Now you can do either of those things in a loop as you see fit...
for (int i = 0; i < sa.length; i++) {
String userInputVar = getUserInput();
sa[i] = userInputVar; // replace value
sa[i] += "foo"; // append to value
}