I'm having problems writing a code with String Arrays [closed] - java

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
}

Related

Java chatbot mirroring and canned responses

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);
}

Flag variable with user input to quit

I have a program that is supposed to simulate a game of poker in java. I have a method class called Poker and a check class called CheckPoker which calls the methods in the method class. I haven't even been able to check if the algorithmic part works because while asking if the user would like to switch out any cards. The loop should quit after 5 cards have been entered or if the user enters "1" but in running the program, the for loop doesn't quit until 5 card values have been entered and then throws a "java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 56" error. I have tried a for loop, a while loop, a do-while loop, but none have seemed to work thus far.
import java.util.*;
public class Poker {
private String[] deck = {
"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK","DA",
"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ", "CQ","CK","CA",
"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ", "HQ","HK","HA",
"S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ", "SQ","SK","SA"};
private List<String> hand = new ArrayList<>();
public Poker(){
Collections.shuffle(Arrays.asList(deck));
}
public void playGame(){
System.out.print("The first five cards are: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
}
System.out.println(" ");
int k = 0;
String j;
List<String> discard = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.next();
if(!j.equals("1")){
j = in.next();
discard.add(j);
k++;
}else{
break;
}
}
List deckList = Arrays.asList(deck);
String[] discard1 = discard.toArray(new String[0]);
for(int l = 0; l<k; l++){
int m = deckList.indexOf(discard1[l]);
String n = deck[m];
deck[m] = deck[l+5];
deck[l+5] = n;
}
System.out.print("Your new hand is: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
hand.add(deck[i]);
}
System.out.println(" ");
}
Try the code below. It seems you were grabbing two cards per iteration and not capturing them all in the ArrayList.
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.nextLine();
if(j.equals("1") {
break;
}
discard.add(j);
k++;
}

Accepting string inputs into an array and checking the availability of the string in the array

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

java user-defined array (and user-defined array size) returning [null, null, null, ...]

This is my first question on this site, I'm running this on NetBeans 8.0.2 and trying to print out my user-defined array but it keeps returning null values. For example if you say there are 2 employees and enter both of their names, it will return [null, null]
How to fix this error? I'm a novice.
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Arrays;
class Tips_Calculation2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
// counter for the if statement that should return all employees from the array
int counter = numberOfEmps;
int[] nOEarray = new int[numberOfEmps];
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
String[] namesArray = new String[i];
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
}
}
Disregard import java.text.DecimalFormat as I plan to use this import later on in my code. Thank you in advance to anyone who is kind/smart enough to respond.
First of all you never put your nameCycler to array. Second of all you create your namesArray every iteration which I think is wrong.
You're creating a brand new (full of null) array namesArray on every pass through the loop--and then never assigning anything to it. I think you're looking for something like this instead. Note that Java indexes from zero, not one.
String[] names = new String[numberOfEmps]
for(int i = 0; i < names.length; i++) {
names[i] = scanner.next();
}
System.out.println(Arrays.toString(names));
First of all, you should initialise the array outside of your loop. Secondly, you forgot to set the name to the array value(s).
Try this:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Arrays;
class Tips_Calculation2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
int[] nOEarray = new int[numberOfEmps];
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
String[] namesArray = new String[numberOfEmps];
for (int i = 0; i < numberOfEmps; i++) {
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
}
}
Replace
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
String[] namesArray = new String[i];
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
With
String[] namesArray = new String[numberOfEmps];
for(int i = 0; i < numberOfEmps; i++)
{
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
And see whether it works.
You never assign the name to the array and in every iteration you define the array new:
String[] namesArray = new String[numberOfEmps];
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
namesArray [i] = nameCycler ;
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
Added comments in the code to point out changes.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
// removed 'nOEarray' and 'counter'
if (numberOfEmps > 0) {
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
// initializing 'namesArray' outside for loop.
String[] namesArray = new String[numberOfEmps];
for(int i = 0; i < numberOfEmps; i++) { // initialized with 0 and updated condition with '<'
namesArray[i] = scan.next(); // assigning value to 'i'th position of namesArray
}
System.out.println(Arrays.toString(namesArray)); // Printing array outside for loop
}
}
"How to fix this error" not. This is not an error.
String[] namesArray = new String[i]; // step one, you declare an array of Strings
// which you don't initialize
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
//you print all the (non-initialized) elements of namesArray
//since you didn't initialize the elements, it takes the default value, which is null
}
fill the elements of the array with Strings before trying to print them.

Hangman Code Issue (Java)

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.

Categories