When I test it, it builds fine. But when I run it only the intro and user output questions come up (which is what it's supposed to do), but when I input an answer an error comes up:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50
at statecapitals.StateCapitals.main(StateCapitals.java:141)
Now I know i'm new at this but what I think the error is, is that my arrays are not corresponding and i'm not sure what I did wrong. Any help would much appreciated. Here is what I have:
String[] stateName = new String[50];
String[] capName = new String[50];
int i;
for(i=0; i < 50; i++)
{
stateName[0] = "Alabama";
stateName[1] = "Alaska";
.....
capName[0] = "Montgomery";
capName[1] = "Juneau";
.....
}
boolean found = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("This program is designed...");
System.out.println("Please enter the name of a U.S. state (please enter capitalized):");
stateName[i] = keyboard.nextLine();
for(i=0; (!found) && (i < stateName.lenth); i++)
if(stateName[i].matches(capName[i]) )
System.out.print(The capital of " + stateName + " is " + capName);
found = true;
if(!found)
System.out.println("The name you entered was not on the list.");
*Updated & edited:
the line of code that was having the most trouble was:
stateName[i] = keyboard.nextLine();
Thank you for everyone's help, i've made some changes:
int i;
for(i=0; i < 49; i++)
{
stateName[i+1]
.....
capName[i+1]
...
}
Plus I added the curly brackets to my for loop at the bottom. Now when I run it, it stops on the line:
if(capName[i].matches(stateName[i]) )
and the error this time is:
Exception in thread "main" java.lang.NullPointerException
at statecapitals.StateCapitals.main(StateCapitals.java:146)
Thank you again for everyone's input.
Since i is not initizalized (in the snippet)
stateName[i] = keyboard.nextLine();
should be something like:
searchState = keyboard.nextLine();
And this comparison is pointless since it would never match (should be searchState from above):
if(stateName[i].matches(capName[i]) )
problem 1
stateName[i] = keyboard.nextLine();
problem 2
for(i=0; i < 50; i++)
{
stateName[0] = "Alabama";
stateName[1] = "Alaska";
.....
capName[0] = "Montgomery";
capName[1] = "Juneau";
.....
}
i think this should be stateName[i] = "Alabama";
Problem 3
You missed the "{" "}" in the for loop
for(i=0; (!found) && (i < stateName.length); i++){
if(stateName[i].matches(capName[i]) ){
System.out.print(The capital of " + stateName + " is " + capName);
found = true;
}
}
if(!found)
System.out.println("The name you entered was not on the list.");
You've had a lot of good suggestions to improve your code that I would try to implement.
The reason for the error is your for loop.
for(i=0; (!found) && (i < stateName.lenth); i++)
The length of the array is going to return 50, but your indexes go from 0 - 49 and because you never find a match, it goes through the whole loop.
Related
Problem:
How do I reprint the for-loops output, outside the loop? Need help to figure it out. what seems to be the error?
Research effort:
**import java.util.*;
public class Admin {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList <String> title = new ArrayList<>();
String n = in.nextLine();
int i = 0;
int j = 0;
while(!n.equals(" ")){
System.out.println("Enter a movie title");
title.add(n);
n = in.nextLine();
}
for(;i < title.size(); i++){
System.out.println("[" + i +"]" +title.get(i));
}
int [] price = new int [title.size()];
for(;j < price.length; j++ ){
System.out.println("Enter price for");
price[j] = in.nextInt();
System.out.println("Price for ["+j+"] is "+ price[j] );
}
//the problem
System.out.println("["+ i+"]"+title.get(i)+" Price: "+price[j] );
}
}
every time I run it after the loops, error shows up
Expected Result: is that it will print the "i" and "title[i]" together with the "j" and "price[j]" both outside it's loops
If I understood you correctly you want to see something like this:
[0]MovieTitle1 Price: MoviePrice1
[1]MovieTitle2 Price: MoviePrice2
There are some Problems: At first, you are going to get an IndexOutOfBoundsException,
because i and j have been increased to title.size(). This is because of the two for-Loops.
In my example this means that i == 2 and j == 2 are true after execution of both for-Loops has happened.
The title ArrayList and the price Array know the Entrys 0 and 1 (in my example) - you are trying to access Entry 2 which is out of bounds.
A possible solution would be to change this:
System.out.println("["+ i+"]"+title.get(i)+" Price: "+price[j] );
to something like this:
for(int n = 0; n < title.size(); n++) {
System.out.println("[" + n + "]" + title.get(n) + " Price: " + price[n]);
}
Here is the code:
import java.util.Scanner;
public class Finder {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String [] names = new String[5];
String searchTerm = "";
for (int i = 0; i <= names.length - 1; i++) {
System.out.print("Enter a name: ");
names[i] = scnr.next();
}
System.out.println();
System.out.print("Enter a name to search for: ");
searchTerm = scnr.next();
for (int i = 0; i <= names.length - 1; i++) {
if (searchTerm.equals(names[i])) {
System.out.println(searchTerm + " found!!");
}
else {
System.out.println(searchTerm + " not found!!");
}
}
}
}
I am working on the if/else statement in the second for loop and when I add the else part of the statement, it returns:
Enter a name: Luke
Enter a name: Kassy
Enter a name: Chloe
Enter a name: Jon
Enter a name: Jake
Enter a name to search for: Chloe
Chloe not found!!
Chloe not found!!
Chloe found!!
Chloe not found!!
Chloe not found!!
I am not sure why it just doesn't say "Chloe found!!" instead of what it says?
With your code now, when you're looping to find the element "Chloe" in the names array, you're going through each element and printing a statement out no matter what. "Chloe" is names[2] but your loop checks names[0] and names[1] first. Since they are not "Chloe", it will print "Chloe not found" (the else part of your if statement). Once it gets to names[2], it will then have found "Chloe" and the if part of your if statement will be executed, printing out "Chloe found". However your loop does not stop there, so the loop will look at names[3] and names[4] and print out "Chloe not found" because none of them equals "Chloe". The simple fix is to only print "Chloe not found" when the loop ends without finding "Chloe" and to only print "Chloe found" when in the middle of the loop, "Chloe" is found. There are many ways to do this but one way I propose is using a boolean variable to check after the loop is done to see if "Chloe" was found or not.
boolean termFound = false;
for (int i = 0; i <= names.length - 1; i++) {
if (searchTerm.equals(names[i])) {
System.out.println(searchTerm + " found!!");
termFound = true;
break;//if term is found, you can break out of the loop early
}
}
if(!termFound){ //if searchTerm was not found
System.out.println(sertTerm + " not found!!");
}
The following code works all the way up until where the user enters the score for the team int homeScore = input.nextInt(), at which point the compiler returns the following error code:
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:854)
at assignment.PremierLeagueManager.main(PremierLeagueManager.java:121)
Java Result: 1
Any idea's on how to fix this?
boolean validHome = false;
boolean validAway = false;
System.out.println("Enter name of Home team: ");
String homeName = input.next();
Iterator<FootballClub> it = premierLeague.iterator();
while (it.hasNext()) {
if (it.next().getClubName().equals(homeName)) {
validHome = true;
}
}
System.out.println("Enter name of Away team: ");
String awayName = input.next();
Iterator<FootballClub> it2 = premierLeague.iterator();
while (it2.hasNext()) {
if (it2.next().getClubName().equals(awayName)) {
validAway = true;
}
}
if (validHome == true && validAway == true) {
System.out.println("Enter number of goals scored by " + homeName + ":");
int homeScore = input.nextInt();
int x = premierLeague.indexOf(it.next());
premierLeague.get(x).setGoalsScored(homeScore);
System.out.println("Enter number of goals scored by " + awayName + ":");
int awayScore = input.nextInt();
int y = premierLeague.indexOf(it2.next());
premierLeague.get(y).setGoalsScored(awayScore);
} else {
System.out.println("One of the teams are invalid. Please try again");
}
At the top where you do "while (it.hasNext())", this loops until the iterator has no more items, so when you get to "int x = premierLeague.indexOf(it.next());", there is no next item for the iterator, so you get no such element. If you want to start over, you need to create a new iterator.
You're calling it.next() after the call to input.nextInt(), but there is no guarantee that there is any member in the iterator it. I'm not sure this is the problem, but it looks like it.
You don't tell us what the line numbers of your source is, and it is confusing that you say this is a compiler error when it looks like it is a runtime error. But that looks like an error, in any event (and you do that twice).
I have an assignment for a beginner Java course that has asked me to create a class called Hangman. The program is supposed to prompt a user (player one) to input a String, then print dashes on the screen for each character in the screen. The program then asks a second user (player two) to take guesses one character at a time until either the word has been guessed, or they have six failed attempts. As each correct guess is verified, the corresponding dash in the string is replaced with the correct letter.
At this point I have created code that will scan in a user String, and replace the String with dashes. The code also prompts the second user for a comparison letter. The code will also replace the first correct guess in the dash String.
The problem I have at this point is that I can't seem to find a way to prompt the user for additional input after the first guess. The program will accept the first correct guess, replace it, and then terminate. I removed a portion of code that checked how many incorrect / correct guesses had been input, because at this point the code would run through constantly incrementing the count and terminate the program. Any help with this problem would be greatly appreciated.
Update:
I have reworked my code to remove unwanted / unnecessary branches. Here is my updated code. At this point, I am receiving too many incorrect guesses. The code is counting every iteration through the array that does not match as incorrect. I appreciate any help you can offer.
public class Hangman
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
String word;
String letter = "";
boolean gameOver = false;
int correct = 0;
int incorrect = 0;
int index = 0;
Scanner userIn = new Scanner(System.in);
System.out.print("Player 1 enter a word: ");
word = userIn.nextLine();
String[] wordArray = word.split("");
int wordLength = word.length();
String[] wrong = {};
String[] right = {};
String[] dashes = new String[wordLength];
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
for(int i = 0; i < wordLength; i++)
{
dashes[i] = "-";
}
for(int i= 0; i < wordLength; i++)
{
System.out.print(dashes[i] +" ");
}
System.out.println();
while(incorrect < 6)
{
System.out.print("Player 2 enter a letter: ");
letter = userIn.nextLine();
letter = letter.toLowerCase();
if(letter.length() > 1)
{
System.out.println("ERROR: You have entered more than one letter.");
System.out.print("Player 2 enter a letter: ");
letter = userIn.nextLine();
}
for(int i = 0; i < wordLength; i++)
{
if( wordArray[i].equals(letter))
{
dashes[i] = letter;
System.out.println("Correct!");
for( i= 0; i < wordLength; i++)
{
System.out.print(dashes[i] +" ");
}
correct++;
}
else
{
incorrect++;
}
}
}
if(correct == wordLength)
{
System.out.println();
System.out.println("You Win!!");
System.out.println();
}
if(incorrect == 6)
{
System.out.println("You Lose.");
System.out.println("The word was " +word);
System.out.println();
}
}
}
So, that's a hefty amount of code. And I see some interesting decisions all over the place. So since you're learning I'll help you help yourself.
Before taking on an application like this you should think about your logic first (psuedo-code) before actually coding. So for a hangman game you probably want something like:
player 1 enters phrase
while wrong_guesses < max_incorrect:
prompt player 2 for a letter
check the phrase for that letter
if found
replace dashes with the letter
else
wrong_guesses++
print status message
Just glancing at your code I can see multiple places where you're asking for new input. This means you are not effectively using your loops. Your application has a lot of unnecessary branches and cleaning it up will help you debug. As an exercise, you can walk through your code and write its' psuedo-code, then compare it to mine.
Good luck!
Update:
With respect to the new and much improved code, your check loop is wrong. It should look more like this:
boolean found = false;
for(int i = 0; i < wordLength; i++)
{
if( wordArray[i].equals(letter))
{
found = true;
// replace dashes, and you don't need to loop here,
// do it after the check for better efficiency
}
}
//Outside of the loop
if (!found)
{
incorrect++;
}
//Print the current status here then
Also, your check for only 1 letter can be subverted (enter aa, then aa again). That block should be:
if(letter.length() > 1)
{
System.out.println("ERROR: You have entered more than one letter.");
System.out.print("Player 2 enter a letter: ");
//letter = userIn.nextLine();
continue; //This tells java to restart the loop
}
I'm trying to slice a string for the first time.
With this code, if I input, for example 'one two three' it works fine until the last word.
This is the last few lines of the output:
Current word is thr
Sentence is now e
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.substring(String.java:1907)
at TestCurr.main(testCurrentWord.java:18)
Has anyone any idea why it does that to the last word?
class TestCurr
{
public static void main (String []args)
{
String s;
int i;
String currentWord;
int length;
int spacePos;
System.out.println("Enter a sentence ");
s = EasyIn.getString();
spacePos = s.indexOf(" ");
length = s.length();
for (i = length -1; i >= 0; i--)
{
currentWord = s.substring(0,spacePos);
s = s.substring(spacePos +1);
System.out.println("Current word is " + currentWord);
System.out.println("Sentence is now " + s);
}
}
}
First of all, you call
spacePos = s.indexOf(" ");
length = s.length();
only once, but these values should change with each iteration of the loop. Furthermore,
s.substring(spacePos +1);
with
spacePos == s.length()-1
means you are passing an index beyond the end of the string as the start index for substring(). Once you fix the first error, this will be your next exception.
Your problem is that you only get the index of the space once. This causes the program to cut the string every three characters, as the first word is three letters long. You need to update spacePos after each iteration.
I believe your problem is in your usage of your spacePos variable.
Outside the loop, you initialize the variable like so:
spacePos = s.indexOf(" ");
Which in your example string of "one two three", yields 3.
But then inside your loop, you never set the variable again, based on what whatever is left that you haven't processed.
Try re-calculating spacePos's value inside the loop and your problem should go away.
Your current approach is too error prone.
And you have too many variables.
Try this just as an idea.
class TestCurr {
public static void main(String[] args) {
String s = null;
System.out.println("Enter a sentence: ");
s = " one two three ";
System.out.println("|" + s + "|");
int i = 0;
int j = 0;
while (true){
while (i<s.length() && s.charAt(i)==' ') i++;
j = i;
if (i>=s.length()) break;
while (i<s.length() && s.charAt(i)!=' ') i++;
System.out.println("Current word is: [" + s.substring(j, i)+ "]");
System.out.println("Sentence is now: [" + s.substring(i) + "]");
if (i>=s.length()) break;
}
}
}
As others have stated, you only get the index once. But I'm curious, why re-invent the wheel?
String s = "one two three";
String[] split = s.split(" ");
for (String out : split) {
System.out.println("Word: " + out);
}