Storing lines from a text file within a java array [duplicate] - java

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.

Related

How would you go about adding a space between every random number? [duplicate]

This question already has answers here:
Elegantly Insert Spaces During Loop Between Values Without Trailing Space
(3 answers)
Java: join array of primitives with separator
(9 answers)
Closed 6 months ago.
I'm trying to get the console to output 100 random numbers between 0 and 50, all on the same line with a space between each. I have everything but the formatting for the space. I know I need to use the printf function, but am completely lost on how to properly impliment it. This is what I have so far, but the output formatting is incorrect.
public static void main(String[] args) {
Random rand = new Random();
for (int count = 0; count <=100; count++)
{
int randomNum = rand.nextInt(51);
System.out.printf("%1d %1d", randomNum, randomNum);
}
}
Here's a version neither using a condition or a separate first print but avoiding any leading or trailing space.
public static void main(String[] args) {
Random rand = new Random();
String delim="";
for (int count = 0; count <100; count++)//fixed as per comments elsewhere.
{
int randomNum = rand.nextInt(51);
System.out.printf("%s%1d", delim,randomNum);
delim=" ";// Change this to delim="," to see the action!
}
}
It's a classic faff to print out n items with n-1 internal separators.
PS: printf feels like overkill on this. System.out.print(delim+randomNum); works just fine.
[1] Your code actually prints 101 numbers. Embrace the logic computers (and java) applies to loops and 'the fences' (the start and end): The first number is inclusive, the second is exclusive. By doing it that way, you just subtract the two to know how many items there are. so, for (int count = 0; count < 100; count++) - that loops 100 times. Using <= would loop 101 times.
[2] You're making this way too complicated by focusing on the notion of 'there must be a space in between 2', as if the 2 is important. What you really want is just 'after every random number, print a space'. The only downside is that this prints an extra space at the end, which probably doesn't matter:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum + " ");
}
is all you actually needed. No need to involve printf:
I know I need to use the printf function
No, you don't. No idea why you concluded this. It's overkill here.
If you don't want the extra space.. simply don't print it for the last number:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum);
if (count < 99) System.out.print(" ");
}
[3] You mention that the code shuold print it all 'on one line', which perhaps suggests the line also needs to actually be a line. Add, at the very end, after the loop, System.out.println() to also go to a newline before you end.

Why is my code giving me an ArrayIndexOutOfBoundsException? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
Hello I am a beginner programmer and I have tried various different methods to get my code to work, but all of them have failed. I would be very thankful if someone could show me what it wrong with my code and how to fix the arrayindexoutofboundsexception error. Thank you so much in advance!!!
Here is my code:
public static void main(String[] args) {
// TODO code application logic here
// getting the number of rows and columns for the maze from the user
Scanner scanner = new Scanner(System.in);
System.out.print("How many rows are in the maze? ");
int rows = scanner.nextInt();
int[][] maze = new int[rows][];
System.out.print("How many columns are in the maze? ");
int columns = scanner.nextInt();
maze[rows] = new int[columns];
// getting the data/danger levels for each row from the user
for (int c = -1; c < maze[rows].length; c++) {
System.out.print("Enter the danger in row " + (c + 1) + ", " + "separated by spaces: ");
maze[rows][c] = scanner.nextInt();
}
System.out.println(maze[rows][columns] + "\n");
}
}
intial value for c variable is -1.
so when you do this
maze[rows][c] = scanner.nextInt();
you get the error since -1 index doesn't exists.
Change it to
maze[rows][c+1] = scanner.nextInt();
You start loop-counter c at value -1, but array starts with index [0]. The loop increment (c++ as last argument in for-loop) is executed at the end of each loop iteration, not at its beginning.
The problem is this line:
maze[rows] = new int[columns];
Arrays in Java are 0-indexed, so if I create a maze with 3 rows, the last index is 2. What you want is this:
maze[rows - 1] = new int[columns]
A quick note that you can debug simple programs very quickly in an IDE like IntelliJ Idea by setting breakpoints and seeing the execution of your program step-by-step:

Is it necessary to resolve the errors shown in the output window of Netbeans IDE even if my code is working the way I want?

Say I want to get the 'of' typed in the input by the user
I am making an app, not finishing off in this dumb output screen (This is only an example)
import java.util.*;
Scanner input = new Scanner(System.in);
String text = input.nextLine();
int check = 0;
for(int i = 0; i < text.length(); i++;){
if(text.substring(i, i + 2) .equals("of")){
check = 0;
}
}
If the user enters abofd, it surely recognises the of at position at 2-4.
But when i value is 4 it checks position from 4-6, but as position 6 is not present is not present it gives an error.
I know you are thinking me to set i < text.length() - 1 at line 5, but my original code needs to run until the end!
It is always a good idea to validate input coming from a user, but you are very much overcomplicating things! Even worse, you wrote down outright wrong code:
String text = input.nextLine();
int check = 0;
for(int i = 0; i < text.length(); i++;){
if(text.substring(i, i + 2) .equals("of")){
The above can't work! You see, i iterates from 0 to text LENGTH. But then you are using i+2 to get a substring from text. (so: say hello to your first ArrayIndexOutOfBoundsException).
Instead, you can do things like:
if (text.contains("of")) {
or
if (text.indexOf("of") >= 0) {
to find out if your string contains "of".
And to answer your question in the title: absolutely yes. Programming is about being a good craftsman to a very large degree. A good craftsman keeps all his tools and materials in order. He doesn't allow for mess, waste, ...
So, long story short: from day one, to all eternity: when writing code, you strive for a zero tolerance policy: no compiler errors, no warnings, nothing in your code that doesn't belong there!

Java: java.util.NoSuchElementException

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.

TD - is a loop the right choice?

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.

Categories