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

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:

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.

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

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.

Trying to Make an Average Finder, Not Using ReadLine(), using Only Console

New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;

Java: How to write computing data in arraylist?

Hello guys I'am beginner of the Java and i've got some problems with array&arraylist. My main problem is how to write computing, dynamic data into the array and later how to read it? Here's my weird code:
public static void main(String[] args) {
int yil, bolum = 0, kalan;
Scanner klavye = new Scanner(System.in);
ArrayList liste = new ArrayList();
//or shall i use this? >> int[] liste = new int[10];
System.out.println("Yıl Girin: "); // enter the 1453
yil = klavye.nextInt();
do{ // process makes 1453 separate then write in the array or arraylist. [1, 4, 5, 3]
kalan = yil % 10;
liste.add(kalan); //my problem starts in here. How can i add "kalan" into the "liste".
bolum = yil / 10;
yil = bolum;
}while( bolum == 0 );
System.out.println("Sayının Basamak Sayısı: " + liste.size()); //in here read the number of elements of the "liste"
klavye.close();
}
Edit:
//needs to be like that
while( bolum != 0 );
System.out.println("Sayının Basamak Sayısı: " + liste);
I think that you most likely want your loop stopping condition to be:
while( bolum != 0)
because bolum will only be 0 when there are no more digits left in your number to process. Also, as amit mentions above it could be the case that the user entered 0 when prompted for a number, so you should take that into account.
To obtain a string representation of your ArrayList (showing the elements it contains through their string representations), you can just use
System.out.println("Sayının Basamak Sayısı: " + liste);
No need to convert to an array. This works because it causes liste's toString method to be called (which is why we don't need to call it explicitly).
You must change this line:
}while( bolum == 0 );
To this:
}while( bolum > 0 );
If you want to print your elements in the ArrayList, update your last statement to print as below:
System.out.println("Sayının Basamak Sayısı: " + liste);
Or you can iterate your list and print as :
for(Object i: liste){
System.out.println(i);
}
This will print your individual list items in separate lines.
Also please fix your while condition as while(bolum != 0); as it may terminate after the very first iteration as bolum will be non zero i.e. 1, 2...(!= 0).

Loop/array (Java)

I am having some problems in getting a loop to work. My goal is to create a loop which will allow the user to fill in lottery numbers in several rows (the user may decide how many rows he/she wants to fill out, but it can not be more than a maximum number specified earlier in the code). So far, my code is as follows:
import java.util.Scanner;
public class LotteryTicket {
public LotteryRow[] rows;
public int numberOfRows;
public Player ticketOwner;
public LotteryTicket(int maxNumberOfRows) {
this.rows = new LotteryRow[maxNumberOfRows];
}
Scanner input = new Scanner(System.in);
public void fillInTicket() {
System.out.print("How many rows do you want to fill in? ");
int n = input.nextInt();
while (n < 1 || n > rows.length) {
System.out.println("The number of rows must lie between 1 and " + rows.length);
System.out.print("How many rows do you want to fill in? ");
n = input.nextInt();
}
for (int index = 0; index < n; index++) {
rows[index].fillInRow();
}
numberOfRows = n;
}
When I try to run this in a main-method, and I enter a proper number of rows, I get the error message:
Exception in thread "main" java.lang.NullPointerException
at LotteryTicket.fillInTicket(LotteryTicket.java:24)
Line 24 is the line in which I call upon the fillInRow()-method which I have created in another class, so I suspect the problem lies here. I know that this method works fine, as I have tried it in a test program. However, am I not referring correctly to this fillInRow()-method?
Any help will be much appreciated!
You created an array with size maxNumberOfRows, but you haven't populated it with any objects. It initially just contains null references.
To fix the code, you have to call the LotteryRow constructor to create an object and then put a reference to that object in your array. You can fix your code like this:
for (int index = 0; index < n; index++) {
rows[index] = new LotteryRow();
rows[index].fillInRow();
}
You must create a new object and place it in the array before you call a method on it. Java arrays of objects are initialized to all nulls.
You never initialize rows. Yes, you create the Array with this.rows = new LotteryRow[maxNumberOfRows]; but that does NOT create a new LotteryRow Object for every Array Entry, so the whole array is filled with null. You have to create the LotteryRow Objects by yourself

Categories