This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
So my code so far is this...
import javax.swing.*;
public class TestNo2{
public static void main(String[] args){
String[] nameNum = new String[0];
int numberNames;
JTextField inputName = new JTextField(5);
JPanel nameWindow = new JPanel();
nameWindow.add(new JLabel("How many names would you like to sort?"));
nameWindow.add(inputName);
int numNames = JOptionPane.showConfirmDialog(null, nameWindow
,"Accept and sort list of students."
,JOptionPane.OK_CANCEL_OPTION);
if(numNames == JOptionPane.OK_OPTION){
String numNamesS = inputName.getText();
numberNames = Integer.parseInt(numNamesS);
nameNum = new String[numberNames];
for(int counterOne=0;counterOne<nameNum.length;counterOne++){
for(int counterTwo=1;counterTwo<=nameNum.length;counterTwo++){
nameNum[numberNames] = JOptionPane.showInputDialog(null
,"Enter the name of student "+counterTwo
,"Name Input"
,JOptionPane.QUESTION_MESSAGE);
}
}
}
}
}
There's no error when I build it but when I run the program, I would only be allowed to enter one name then the error occurs.
This is the error that shows up.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at TestNo2.main(TestNo2.java:23)
Thank you for your time in reading this.
for(int counterTwo=1;counterTwo<=nameNum.length;counterTwo++){
should be:
for(int counterTwo=1;counterTwo < nameNum.length;counterTwo++){
Because the expression counterTwo<=nameNum.length causes the array to exceed its bounds (remember that actual length of array starts from zero and is 1 Less than actual length you specified.
So if you have an array defined like:
someArray[] something = {1,2,3,4,5,6};
The value of something.length would be 6. But the actual length is 5 (Counting as: 0,1,2,3,4,5).
And why do you have two loops for just gettings names and adding to String Array? Just one is enough...
for(int counterOne=0;counterOne<nameNum.length;counterOne++){
nameNum[counterOne] = JOptionPane.showInputDialog(null
,"Enter the name of student "+(counterOne+1)
,"Name Input"
,JOptionPane.QUESTION_MESSAGE);
}
And then sort the array nameNum with whatever method you plan to use.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
I'm still new to programming and I want to make a program that will take the food order from user until the user presses "n" to stop. But I can't seem to make it work like I want it to.
I want my output to be like this.
Buy food: Burger
Order again(Y/N)? y
Buy Food: Pizza
Order again(Y/N)? n
You ordered:
Burger
Pizza
But my output right now is this.
Buy food: Burger
Order again(Y/N)? y
Buy food: Pizza
Order again(Y/N)? n
You ordered:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Array.getFoodName()" because "food_arr2[i]" is null
at Food.main(Food.java:50)
Here is my code:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Food food = new Food();
Array[] food_arr;
boolean stop = false;
String foodName;
int k = 1;
int j = 0;
while(stop == false) {
food_arr = new Array[k];
System.out.print("Buy food: ");
foodName = s.next();
food_arr[j] = new Array(foodName);
food.setFoodArray(food_arr);
System.out.print("Order again(Y/N)? ");
String decide = s.next();
if(decide.equalsIgnoreCase("y")) {
k++;
j++;
}
else if(decide.equalsIgnoreCase("n")) {
stop = true;
}
}
Array[] food_arr2 = food.getFoodArray();
for (int i = 0; i < food_arr2.length; ++i) {
System.out.println("\nYou ordered: ");
System.out.println(food_arr2[i].getFoodName()); //This line is the error according to my output
}
}
I don't know how to fix this and I was hoping for someone to help me.
I think I see what you are trying to do with the k value setting the size of the array you are using.
However, with each iteration of the while loop:
food_arr = new Array[k];
Will create a new empty array each time!
So, for example, on the second iteration
food.setFoodArray(food_arr);
Will set foods array as something like [null, "Pizza"]
Even if this did work, creating a new array each time is not a very efficient method.
I would strongly recommend using a different, dynamically allocated data structure such as an ArrayList and defining it outside the scope of the while loop.
ArrayList<Food> food_arr = new ArrayList<Food>()
// Note that I'm just guessing the data type here - I can't see what you are actually using!
while(stop == false) {
System.out.print("Buy food: ");
foodName = s.next();
food_arr.add(foodName)
// etc, etc
}
food.setFoodArray(food_arr)
// ! Note: You will need to convert the array list into an array
// ! or change the data struture in the Food class
// etc, etc
However, this is just the first solution that popped into my head, check out different kinds of data structures and think about how else you could design this program yourself!
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Removing an element from an Array (Java) [duplicate]
(15 answers)
Closed 4 years ago.
Got a simple auction program running, only problem is that if a user is removed before auction is closed his/hers bids are supposed to be removed. I dont have it 100% down yet but I think I am on the right path.
The bids have to be arrays and right now it is kinda removed or just moved maybe. This was a the error earlier.
Top Bid:[Wow 400 kr, Boy 311 kr, Man 33 kr, Dude 2 kr]
command>remove user
Name>wow
Wow has been removed from registry
command>list auctions
Auction # 1: Item. Top Bid:[Boy 311 kr, Man 33 kr, Exception in thread "main" java.lang.NullPointerException
public void removeBid(String name) {
for(int a = 0;a < bidIndex; a++) {
if(bids[a].getUser().getName().equals(name)) {
bids[a]=null;
bidIndex--;
break;
}
}
sortBids();
public void sortBids() {
if(bidIndex > 1) {
for(int a = 0; a < bidIndex -1; a++) {
for(int b = a + 1; b < bidIndex; b++) {
if(bids[a] == null || bids[a].getBid() < bids[b].getBid()) {
Bid temp = bids[a];
bids[a] = bids[b];
bids[b] = temp;
}
}
Arrays cannot change size once initialized. If you create an array new String[10]; it will forever have 10 items (which are null by default). Setting an index to null doesn't change this.
String[] items = new String[] {"String1", "String2", "String3"};
items[1] = null;
This arrays would now look like [String1, null, String3].
If you need to change arrays as much as it seems, you're better off using a List or Map.
I would suggest using a HashMap if you want to easily link one object to another. In this case it looks like you'd be linking a String (name) to the Bid object.
Map<String, Bid> bids = new HashMap<String, Bid>();
Bid bid1 = new Bid(/*...*/);
Bid bid2 = new Bid(/*...*/);
// Add bids to the map
bids.put("Wow", bid1);
bids.put("Boy", bid2);
// Get any of these objects
Bid retrievedBid = bids.get("Wow");
// Or remove them
bids.remove("Wow");
HashMaps are similar in concept to associative arrays from other languages, where you have a key -> value relationship. Each key is unique, but the value can repeat.
They can also be converted to arrays if the final result you need is an array.
Bid[] bidsArray = new Bid[0];
bidsArray = bids.values().toArray(bidsArray);
One way you can achieve this is to convert the array to a list and then remove the bid using Java streams and convert back.
List<Bid> bidsList = Arrays.asList(bids);
bidsList = bidsList.stream()
.filter(n -> !n.getUser().getName().equals(name))
.collect(Collectors.toList());
bids = bidsList.toArray(new Bid[bidsList.size()]);
This question already has answers here:
Scanner input accepting Strings skipping every other input inside a while loop. [duplicate]
(3 answers)
Closed 7 years ago.
Everything compiles, but when I print the size and the array elements, it indicates that not all of the values are added in because the size and the values would only be partial. Also, sometimes the sentinel value does not work( I have to enter it twice at times).What's wrong?
import java.util.ArrayList;
import java.util.Scanner;
public class BowlingScoresArrayList{
public static final int SENTINEL = -999;
public static final int MIN=-1;
public static void main (String [] Args) {
ArrayList<Integer> bowlingScores = new ArrayList<Integer>();
Scanner reader = new Scanner(System.in);
System.out.println("Enter your scores: ");
do {
bowlingScores.add(reader.nextInt());
} while (reader.nextInt()!= SENTINEL);
System.out.println(bowlingScores);
System.out.println(bowlingScores.size());
So I tried entering these values:
Enter your scores:
1
2
2
3
-999
-999
And it yields this:
[1, 2, -999]
3
You're problem is, you're using two nextInt statements...
do {
bowlingScores.add(reader.nextInt());
} while (reader.nextInt()!= SENTINEL);
So you're asking the user to provide input twice.
Instead, something like...
int in = SENTINEL;
do {
in = reader.nextInt();
if (in != SENTINEL) {
bowlingScores.add(in);
}
} while (in != SENTINEL);
would produce the desired results
Hi guys so I keep getting the following error when I try running my program.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Simulation.getJob(Simulation.java:12)
at Simulation.main(Simulation.java:58)
The piece of code I'm working with looks like this:
//all of this is under main.
m = Integer.parseInt( in.nextLine() );
//make sure the file has stuff in it
while(in.hasNext()){
in.useDelimiter("\n");
//Create an array of type job to keep track of our number of jobs.
Job[] jobs = new Job[m];
for(int i = 1; i < m; i++){
jobs[i] = getJob(in);
System.out.println(jobs[i]);
}
}
//getJob function is here:
public static Job getJob(Scanner in){
String[] s = in.nextLine().split(" ");
int a = Integer.parseInt(s[0]);
int d = Integer.parseInt(s[1]);
return new Job(a,d);
}
The data from the in file looks like this
3
2 2
3 4
5 6
The problem is that your code does not match the input format: when the nested for loop is over, the outer while loop takes you back to the beginning of the reading code, and tries to read another set of m items.
To fix this, simply remove your outer loop:
in.useDelimiter("\n");
//Create an array of type job to keep track of our number of jobs.
Job[] jobs = new Job[m];
for(int i = 0; i < m; i++){
jobs[i] = getJob(in);
System.out.println(jobs[i]);
}
Note that the loop index i needs to start at zero, not at 1, because Java arrays are zero-based.
I was doing some beginner programming with series and input but im having the same problem constantly.Cant find the solution.Basically what i want my program to do for now i input a list of numbers and print them out.And im getting the same error over and over whatever i change in program.Here is my code.
import java.util.Scanner;
public class Test437 {
public static void main(String[] args) {
int limit = 25;
int cnt;
int addtion;
double dbt; //Devided by two % 2
Scanner input = new Scanner(System.in);
int [] ya = new int[8];
for(cnt = 0;cnt < ya.length;cnt++)
{
System.out.print("ya[" + cnt + "]= ");
ya[cnt] = input.nextInt();
}
System.out.println(ya[cnt]);
}
}
Im getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at Test437.main(Test437.java:22)
System.out.println(ya[cnt]); this line is outside loop. Cnt is equal to an array size so it cannot be used in such way because there is no element in the array with such index.
The line:
System.out.println(ya[cnt]);
needs to be in a loop again to print out all the array values after accepting them:
for (cnt = 0;cnt < ya.length;cnt++) {
System.out.println(ya[cnt]);
}
Alternatively, you could do:
System.out.println(Arrays.toString(ya));
cnt condition to leave the loop is to exceed the length therefore you get in indexoutofbounds
This line
System.out.println(ya[cnt]);
is trying to access element at ya.Length index which does not exists.
In your example ya[8] contains elements at position from 0 to 7 (ya[0] ya[1] ... ya[7] and you're trying to access ya[8] bacuase cnt variable is 8 after the for statement ends.
Therefore the compiler throws an indexOutOfBounds exception.