I am busy writing an algorithm that will scan a text file and add its contents into an array. However I keep getting an error message which says:
"Exception in thread "AWT-EventQueue-0"
java.util.NoSuchElementException"
I have read up on the java documents and learned that this error has something to do with the fact that I haven't set up my text file properly, however I do not understand how to fix it.
I have included my code and the contents of the text file:
String [] CardPictureNames = new String [16];
try {
Scanner car = new Scanner (new File("cardNames.txt")).useDelimiter("#");
String CN = "";
while(car.hasNext()){
for(int j=0; j <= CardPictureNames.length; j++ ){
CN = car.next();
CardPictureNames[j] = CN;
}
}
car.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(MemoryForm.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this,"The file containing the names of the cards is missing.");
}
Here are the contents of the text file:
2 of Clubs#
10 of Clubs#
Ace of Hearts#
Ace of Spades#
Joker#
King of Hearts#
Queen of Clubs#
Queen of Diamonds#
2 of Clubs#
10 of Clubs#
Ace of Hearts#
Ace of Spades#
Joker#
King of Hearts#
Queen of Clubs#
Queen of Diamonds#
Can someone please explain to me how I can fix this problem?
Thank you in advance.
Replace your while/for loop combo with this
for(int j=0; j <= CardPictureNames.length; j++ ){
if (car.hasNext()) {
CN = car.nextLine();
CardPictureNames[j] = CN;
}
}
What you are attempting to do is loop it twice. Which is unnecessary. The if statement is added to prevent the exception from happening by not running the code that gets the card names unless there is another line (which there isn't at the end)
Now I'm assuming there is a better way to do this. But this works. And the so called "better" way probably wouldn't make much of a difference.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
My program is returning an Index out of bounds errors. I am a bit confused why this is happening. I have tried a few things and was wondering if anyone can point me in better direction any help will do.
public static void booknames() throws FileNotFoundException {
Scanner in = new Scanner(new File("books.txt"));
String []books;
books = new String[20];
while (in.hasNextLine()) {
for(int i = 0; i <= books.length; i++ ) {
String line = in.nextLine();
books[i] = line;
System.out.println("A[" + i + "]" + books[i]);
}
}
}
The compiler returns the error of
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20
at assignment7bookrecommender.bookrecommender.booknames(bookrecommender.java:23)
at assignment7bookrecommender.bookrecommender.main(bookrecommender.java:9)
Here is my books.txt file for more reference.
A Walk in the Woods
Salem's Lot
John Adams
Illustrated Guide to Snowboarding
Dracula
Your Mountain Bike and You: Why Does It Hurt to Sit?
1776
Dress Your Family in Corduroy and Denim
High Fidelity
Guns of August
Triathlete's Training Bible
Jaws
Schwarzenegger's Encyclopedia of Modern Bodybuilding
It
What's That?
Team of Rivals
No Ordinary Time: Franklin and Eleanor Roosevelt: The Home Front in World War II
Truman
Basic Fishing: A Beginner's Guide
Life and Times of the Thunderbolt Kid
Any help would be greatly appreciated.
You have a for loop inside a while loop...
while (in.hasNextLine()) {
for(int i = 0; i <= books.length; i++ ) {
String line = in.nextLine();
...
The while loop is checking if your input file has a next line, but then your for loop goes ahead and reads 20 lines. (21 currently, but even if you fix that...) You only need one loop, so you should chose one method or the other to control how many lines you read.
I am creating a game board. I need it to reveal a the selected column after a user input, while the rest of the columns still print as "X". This game holds values I have set in each column, but does not print them on the screen. When the user selects a column, I need it to print showing the value that column is holding while the rest of the columns still print "X" so they do not reveal what they have. I am new to this, thank you for your help.
This is the function where I think the problem is. If you look, you will see that I have the if statement "if (isCovered) - then I want it to print the covered version. Then the "else" - which is where I want it to print just the one that was guessed as its actual value. I have tried multiple ways of achieving this with no luck. Is there are way to make it like (!isCovered)? But that doesn't work, because it states it needs to be an array and the function "!" does not work. Right now it just seems like it never prints the "else" statement at all. I have functions that take the user input and compare them to "isCovered" and they work correctly, because the piece moves on the board as it should. I just cannot get it to print the actual value instead of an "X". Thank you for any help and if further information would be helpful, please let me know. It is due today unfortunately I only had a few days to work on it and have been working constantly on it.
public static void PrintRevealBoard(int[][] myArray,Boolean[][] isCovered)
{
int i, j;
for (i = 0; i<myArray.length ; i++ ) { // array.length = max rows
System.out.print((i+1) + " ");
for(j = 0; j <myArray[0].length; j++) { // array[0].length = max
cols
if(isCovered[i][j]){
System.out.print(GetRollColorCovered(myArray[i][j]) + " ");
} else {
System.out.print(GetRollColor(myArray[i][j]) + " ");
}
}
your main module is kinda messy. And I don't know how GetRollColor(dice) works. Anyway as I understand you have a two dimensional array and you want to show only a specific value. Seems like u want to show the entire input column.
use this to update isRevealed() after the input of inputCol.
public static Boolean[][] updateRevealed(Boolean[][] isRevealed, int inputCol){
for(int i=0;i<isRevealed[inputCol].length;i++)
isRevealed[inputCol][i] = true;
return isRevealed;
}
update like this,
isRevealed = updateRevealed(isRevealed,inputCol);
your printRevealBoard is almost correct. Just remove the first line. It doesn't make sense and you don't want it as I see
int isRevealed = inputCol;
I don't know how your array looks like. But because of the first for loop u will definitely get an
index out of bounds exception
loop runs until I becomes myarray.length. and in the next loop you access index I of myArray. Exception will be thrown if I=myArray.length. u gotta fix it. If any problem occurs lemme know.
thankyou
edit:
try this for printRevealBoard
public static void printRevealBoard(char[][] myarray , Boolean[] []isRevealed){
for(int i=0;i<myarray.length;i++){
for(int j=0;j<myarray[0].length;j++){
if (isRevealed[i][j]) System.out.print(myArray[i][j] + " ");
else System.out.print("* ");
}
System.out.println();
}
}
So, I've searched around stackoverflow for a bit, but I can't seem to find an answer to this issue.
My current homework for my CS class involves reading from a file of 5000 random numbers and doing various things with the data, like putting it into an array, seeing how many times a number occurs, and finding what the longest increasing sequence is. I've got all that done just fine.
In addition to this, I am (for myself) adding in a method that will allow me to overwrite the file and create 5000 new random numbers to make sure my code works with multiple different test cases.
The method works for the most part, however after I call it it doesn't seem to "activate" until after the rest of the program finishes. If I run it and tell it to change the numbers, I have to run it again to actually see the changed values in the program. Is there a way to fix this?
Current output showing the delay between changing the data:
Not trying to change the data here- control case.
elkshadow5$ ./CompileAndRun.sh
Create a new set of numbers? Y for yes. n
What number are you looking for? 66
66 was found 1 times.
The longest sequence is [606, 3170, 4469, 4801, 5400, 8014]
It is 6 numbers long.
The numbers should change here but they don't.
elkshadow5$ ./CompileAndRun.sh
Create a new set of numbers? Y for yes. y
What number are you looking for? 66
66 was found 1 times.
The longest sequence is [606, 3170, 4469, 4801, 5400, 8014]
It is 6 numbers long.
Now the data shows that it's changed, the run after the data should have been changed.
elkshadow5$ ./CompileAndRun.sh
Create a new set of numbers? Y for yes. n
What number are you looking for? 1
1 was found 3 times.
The longest sequence is [1155, 1501, 4121, 5383, 6000]
It is 5 numbers long.
My code:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class jeftsdHW2 {
static Scanner input = new Scanner(System.in);
public static void main(String args[]) throws Exception {
jeftsdHW2 random = new jeftsdHW2();
int[] data;
data = new int[5000];
random.readDataFromFile(data);
random.overwriteRandNums();
}
public int countingOccurrences(int find, int[] array) {
int count = 0;
for (int i : array) {
if (i == find) {
count++;
}
}
return count;
}
public int[] longestSequence(int[] array) {
int[] sequence;
return sequence;
}
public void overwriteRandNums() throws Exception {
System.out.print("Create a new set of numbers? Y for yes.\t");
String answer = input.next();
char yesOrNo = answer.charAt(0);
if (yesOrNo == 'Y' || yesOrNo == 'y') {
writeDataToFile();
}
}
public void readDataFromFile(int[] data) throws Exception {
try {
java.io.File infile = new java.io.File("5000RandomNumbers.txt");
Scanner readFile = new Scanner(infile);
for (int i = 0; i < data.length; i++) {
data[i] = readFile.nextInt();
}
readFile.close();
} catch (FileNotFoundException e) {
System.out.println("Please make sure the file \"5000RandomNumbers.txt\" is in the correct directory before trying to run this.");
System.out.println("Thank you.");
System.exit(1);
}
}
public void writeDataToFile() throws Exception {
int j;
StringBuilder theNumbers = new StringBuilder();
try {
PrintWriter writer = new PrintWriter("5000RandomNumbers.txt", "UTF-8");
for (int i = 0; i < 5000; i++) {
if (i > 1 && i % 10 == 0) {
theNumbers.append("\n");
}
j = (int) (9999 * Math.random());
if (j < 1000) {
theNumbers.append(j + "\t\t");
} else {
theNumbers.append(j + "\t");
}
}
writer.print(theNumbers);
writer.flush();
writer.close();
} catch (IOException e) {
System.out.println("error");
}
}
}
It is possible that the file has not been physically written to the disk, using flush is not enough for this, from the java documentation here:
If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.
Because of the HDDs read and write speed, it is advisable to depend as little as possible on HDD access.
Perhaps storing the random number strings to a list when re-running and using that would be a solution. You could even write the list to disk, but this way the implementation does not depend on the time the file is being written.
EDIT
After the OP posted more of its code it became apparent that my original answer is not relatede to the problem. Nonetheless it is sound.
The code OP posted is not enough to see when is he reading the file after writing. It seems he is writing to the file after reading, which of course is what is percieved as an error. Reading after writing should produce a program that does what you want.
Id est, this:
random.readDataFromFile(data);
random.overwriteRandNums();
Will be reflected until the next execution. This:
random.overwriteRandNums();
random.readDataFromFile(data);
Will use the updated file in the current execution.
I apologies for my poor knowledge of programming and english in advance.
So my friends and I are a creating a tower defence game as our 2nd semester project at our university. The semester is about user involvment, so we decided to create a tower defence as we can include user in a lot of things. But we have given our tower defence game a twist, we have included questions inbetween waves, which gives a reward of x amount of gold if answered correct.
As it is right now we only have one question for each wave, and we would like to include up to 5 questions for each wave, this is done due to if people want to play it more than once, they cannot just remember the right answer from earlier. We have already made a list of questions in a text file which looks like this, example:
Which Chinese leader’s widow was sentenced to death as a member of the Gang of Four?
A: Zhou Enlai
B: Jiang Zemin
C: Mao Zedong
D: Sun Yat-Sen
3
Example done, and this is done with up to 50 questions.
And our code for reading this txt file so far looks like this:
public class ReadFile {
public static void OpenFile(){
try {
FileReader fr = new FileReader("/save/QuestionsB.txt");
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = readLines();
for (int j=0; j < Value.numberOfQuestions; j++){
for (int i=0; i<5; i++){
Value.textData[j][i] = textReader.readLine();
}
}
textReader.close();
}
catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void loadQuestions(){
try {
Scanner loadScanner = new Scanner(new File("save/questionFile.qreepz"));
while (loadScanner.hasNextLine()) {
for (int j=0; j < Value.numberOfQuestions; j++){
for (int i=0; i<6; i++){
Value.textData[j][i] = loadScanner.nextLine();
}
}
}
loadScanner.close();
} catch (Exception e) { }
}
My question is now, how do we create a game with 5 questions saved for eachwave, and one random is selected, I hope you know what I mean.
I was thinking about doing some kind of if loop, but I am not sure of how to do this. I hope you can help, thank you for your time!
Here is some code to get you started. I'll leave it to you as to how and where to place it.
Question[] possibleQuestions = //collate your questions into an array.
Random rand = new Random();
Question thisRoundsQuestion = possibleQuestions[rand.nextInt(possibleQuestions.length)];
//offer question to user.
Info on Random.nextInt() can be found here.
This solution does not cover repeating questions. If you would like to never repeat a question you will either need to keep track of the Questions asked or use a Collection such as an ArrayList and remove Questions as you use them to make sure they're not in the pool next time around.
Im trying to write a game of Yahtzee as part of an online course (not actually enrolled, just playing along at home) I have hit a bit of a wall manipulating values in the array that keeps track of the dice values. This is the section of code that seems to be causing trouble;
for (int i=0; i<N_DICE; i++){ //goes through each die.
if (display.isDieSelected(i) == false){ //checks if player wants to reroll the die.
dice [i] = dice[i];//problem line-should reassign the same value back to the die.
}
else {
dice [i] = rgen.nextInt(1, 6);
}
}
Assigning a new random number works, and if I roll all 5 dice every turn its happy.
I've changed the offending line to dice[i]=1 for testing purposes and while it takes some fun out of the game, the program works, so I'm thinking its something simple I'm doing wrong with that line.
I've tried assigning dice[i] to a temp variable (inside and out of the if loop) and then assigning temp back to dice[i].
I've tried just leaving the if loop empty.
I've tried setting it up as a multi dimesional array with a seperate array for each roll.
I've tried adding a cast (didnt think that'd do it but I was out of ideas).
All of these have had the same results.
Only been programming a few weeks, I'd be very gratefull if someone could tell me what I'm doing wrong.
Not sure what you're trying to do with that line:
dice[i] = dice[i];
Since it's a NOP, why not just omit it?
I don't really see the purpose of:
dice[i] = dice[i]
Can't you just use something like:
for (int i=0; i<N_DICE; i++){
if (display.isDieSelected(i)){
dice [i] = rgen.nextInt(1, 6);
}
}
The code looks completely correct, although I would write it a bit more compactly:
for (int i = 0; i < N_DICE; i++) {
if (display.isDieSelected(i)) {
dice[i] = rgen.nextInt(1, 6);
}
}
So your problem probably lies somewhere else. Is dice a new array, or is it always the same in the program? If it is a field in some class, it should have the final modifier, like this:
public class YahtzeeState {
private final int[] dice = new int[N_DICE];
}
This declaration makes sure that the dice array cannot be replaced later with a completely different array. The values in the array can still be changed though.
How is the dice-array initialized? I don't know your entire code but I could imagine that it doesn't work because the dice-array gets it values only in this loop?
Maybe you should try something like:
for (int i=0; i<N_DICE; i++){
if (display.isDieSelected(i) || dice[i] == null)
dice [i] = rgen.nextInt(1, 6);
}