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
Related
I have to write a method to write data to a file. It has to take an array of integers as a parameter and write them to a file, but I am getting an error on these lines:
Integer[] x = val.toArray(new Integer[val.size(25)]);
if (x < 0) break;
public static void writeToFile (String filename, int[] x) throws IOException {
PrintWriter outputWriter = new PrintWriter("integers.txt");
System.out.println("Please enter 25 scores.");
System.out.println("You must hit enter after you enter each score.");
Scanner sc = new Scanner(System.in);
int score = 0;
while (score < 25) {
int val = sc.nextInt();
Integer[] x = val.toArray(new Integer[val.size(25)]);
if (x < 0) break;
outputWriter.println(x);
score++; }
outputWriter.flush();
outputWriter.close();
}
There are a couple of things. First off, you are trying to do things that are not possible to do with an int. Look at the ever helpful java API when trying to use a class:
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
Next, if I was writing your program (which I'm not and I do not intend to), I would watch your instantiations. The array is being instantiated every loop which means that you will have a new array every time the user puts in a value. Meaning all the previous numbers are going to be lost. Also, take the integer array out of the parameter. You aren't even using it in the method.
Instantiate your array outside of the loop with a size of 25 elements:
int[] array = new int[25];
Now, you can place the items in this array every loop like this:
array[score] = val;
This places the value in the indexes 0 -> 24. It seems to me that in order to truly understand how to do this program you are going to have to have a refresher on arrays and how they work.
Finally, the computer sees this method as a sequence. So, line by line think about what is happening on your program. Ideally, this is what should be happening.
Instantiate your objects: the scanner, the array (where the ints are stored), the Print writer
give instructions to the user how to use the program.
run a loop 25 times doing this:
- scanning in an int
- placing the int into the array at the appropriate index
write the array into the file
flush the writer.
close the writer.
I'm currently working on a homework assignment for a beginner-level class and I need help building a program that tests if a sodoku solution presented as an int[][] is valid. I do this by creating helper methods that check both rows, columns and grids.
To check the column I call a method called getColumn that returns a column[]. When I test it out it works fine. I then pass it out on a method called uniqueEntries that makes sure that there are no duplicates.
Problem is, when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333). I have no idea why it does that. Here is my code:
int[][] sodokuColumns = new int[length][length];
for(int k = 0 ; k < sodokuPuzzle.length ; k++) {
sodokuColumns[k] = getColumn(sodokuPuzzle, k);
}
for (int l = 0; l < sodokuPuzzle.length; l++) {
if(uniqueEntries(sodokuColumns[l]) == false) {
columnStatus = false;
}
}
my helper is as follows
public static int[] getColumn(int[][] intArray, int index) {
int[] column = new int[intArray.length];
for(int i = 0 ; i < intArray.length ; i++) {
column[i] = intArray[i][index];
}
return column;
}
Thanks !
You said:
when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333).
I don't see any issue with your getColumn method other than the fact it's not even needed because getColumn(sodokuPuzzle, k) is the same as sodokuPuzzle[k]. If you're going to conceptualize your 2D array in such a way that your first index is the column then for your purpose of checking uniqueness you only need to write a method to get rows.
The issue you're having would seem to be with another part of your code that you did not share. I suspect there's a bug in the logic that accepts user input and that it's populating the puzzle incorrectly.
Lastly a tip for checking uniqueness (if you're allowed to use it) would be to create a Set of some kind (e.g. HashSet) and add all of your items (in your case integers) to that set. If the set has the same size as your original array of items then the items are all unique, if the size differs there are duplicates.
I have created a list of 2D arrays containing randomly generated number values for different locations.
public static int Prices[][] = new int[Cities.length][ItemNames.length];
public static List<int[][]> CityPrices = new ArrayList<int[][]>();
public static void NewDay()
{
for(int i = 0; i<Cities.length; ++i)
{
Prices[i] = PriceGenerator.ReturnPricesForCity(i);
//This method returns an array of random integers
}
CityPrices.add(Prices);
}
But then later when I want to retrieve the price history for a specific item for the amount of days passed, it returns the same value for each day
int Prices[] = new int[GlobalVariables.CityPrices.size()];
String sTest = "";
for(int i = 0; i < Prices.length; ++i)
{
Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()];
sTest = sTest + Prices[i] + ",";
}
In this case, the values returned by sTest was : 6055,6055,6055,6055,6055, for five consecutive days.
If I would for instance add a day, the values would change to a range of a new number, which in this case was : 7294,7294,7294,7294,7294,7294,
Please show me what I am doing wrong, as I have been trying to figure this one out the past 4 days with no luck.
Every element in your CityPrices list is the same: in each case, you are adding the Prices two-dimensional array. Your loop modifies Prices[i], but it doesn't change Prices, which is still a reference to the same two-dimensional array right the way through.
I think you're imagining it will pass the contents of the array in its current state, but it doesn't: it passes a reference to the array to the .add() method, so any subsequent changes to the array will be reflected in the contents of CityPrices.
If at the end of your loop you try
CityPrices.get(0) == CityPrices.get(1)
you'll see it returns true.
In the assignment: Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()]; you are basically referencing an int[][] at the same index for both dimensions.
On top of that, the spinCity.getSelectedItemPosition() invocation might be returning the same index at every iteration of your loop, hence your identical values.
It's hard to assume anything further as you haven't posted the code for spinCity.
Here is the problem:
"Say you have an array for which the ith element is the price of a
given stock on day i.
If you were only permitted to complete at most one transaction (ie,
buy one and sell one share of the stock), design an algorithm to find
the maximum profit."
Here is my solution.
public class Solution {
public int maxProfit(int[] prices) {
int[] sell = new int[prices.length];
for(int i = 0; i<prices.length; i++){
for(int j = 0; j<i; j++){
sell[i] = Math.max(prices[i] - prices[j], sell[i]);
}
}
int sellPrice = prices[0];
int day = 0;
for(int i = 0; i<prices.length; i++){
if(sellPrice < prices[i]){
sellPrice = prices[i];
day = i;
}
}
int buyPrice = prices[0];
for(int i = 0; i<day; i++){
buyPrice = Math.min(buyPrice, prices[i]);
}
return sellPrice - buyPrice;
}
}
I'm not sure if it work, which is not a problem now. The problem is, it always shows Runtime Error at Line 9: (int sellPrice = prices[0];)
and
Line 18: (int buyPrice = prices[0];) as "java.lang.ArrayIndexOutOfBoundsException: 0".
So what's wrong with it? How to fix it? Thank you so much.
The only reason prices[0] would throw an AIOOBE is because the prices doesn't have any prices in it.
For example:
public static void main(String[] args)
{
int[] ints = new int[] {};
System.out.println(ints[0]);
}
Throws this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(Main.java:7)
Whereas this, works.
public static void main(String[] args)
{
int[] ints = new int[] {93727};
System.out.println(ints[0]);
}
Check if you are not passing a zero length array to your maxProfit method and be sure to initialize the array before using it in your method.
Here is the possibilty:
ArrayIndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
The array you passing to this method is empty. That is no elements in that array. The part
equal to the size of the array. (size is 0 and index is zero)
That is the cause in your case.
You're getting an exception probably because the prices array was not instantiated correctly.
Also, your algorithm is not guaranteed to be correct: consider the following set of prices,
$4, $5, $1, $3
The maximum profit made would be 2 dollars, but your algorithm would result in $1.
Here's some correct answers: Maximum single-sell profit
How does your main look like??
Make sure the array prices[] is created and also initialized.
If it is created like int[] prices = new int[] {}; you will see an error saying index out of bound.
Make sure you initialize (from user input or using hard coded values).
If it is from user input make sure that the values are assigned.
Hard Coded one will look like this:
int price[] = {100,200,500,2000,700,500,400};
Hope it helps
leetcode
When prices.lenght = 0, prices[] is null at line 9 and 18.
That's why you got errors.
I'm trying to define an array starting from data that come from another array.
The code will explain the situation better than thousands words.
public class QualityCheck {
public QualityCheck (JTable table)
{
//the data come from a JTable (that represents a school timetable)
String [] dailyLessons= new String[table.getColumnCount()];
String [] dailyClasses= new String[table.getColumnCount()];
//checking all the days
for (int i=1; i<table.getColumnCount(); i++)
{
//checking all the hours in a day
for (int j=0; j<table.getRowCount(); j++)
{
//lesson is an array that contains the subject and the room in which the subject is erogated
//lesson[0] contains the subject
//lesson[1] contains the room
String[] lesson = ((TabellaOrario.MyTableModel)table.getModel()).getLesson(j,i);
//I'd like to put ALL the daily subjects in dailyLesson
dailyLessons[j] = lesson[0];
//I'd like to put All the daily rooms in dailyClasses
dailyClasses[j] = lesson[1];
}
//trying if dailyLessons has the elements
for (String s: dailyLessons)
{
System.out.println(s);
}
}
}
}
If a run this code, the compiler protest with this error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 7
and it evidence the string
dailyLessons[j] = lesson[0];
How can I do to define dailyLesson?
You are allocating both of the arrays to the same size table.getColumnCount(),
and then you use index j for both of them again, which goes up to table.getRowCount() - 1.
You probably should allocate one of them to size table.getRowCount(), and then use j as the index for only that one, and i for the other, but you never use dailyClasses so I'm not sure.
Edit:
Apparently the intent is to fill both the arrays with the data of one column. Then the fix is to change the size of the arrays to the amount of rows:
// Changed table.getColumnCount() -> table.getRowCount()
String [] dailyLessons= new String[table.getRowCount()];
String [] dailyClasses= new String[table.getRowCount()];
You init the arrays with table.getColumnCount() and loop using j < table.getRowCount().
If table.getColumnCount() is smaller that table.getRowCount() then you will get AIOBE.
You need at least to init the arrays with table.getRowCount().
EDIT
You could create a little class with encapsulates dailyLessons and dailyClasses
class Lesson {
public String dailyLesson;
public String dailyClass;
}
and create an array of that class, this way you'll always have the same number of daily lessons and classes:
String [] lessons = new Lesson [table.getRowCount()];
and later inside the loop:
lessons.dailyLesson = lesson[0];
lessons.dailyClass = lesson[1];
Also you could use an ArrayList instead of a simple array so you wont have to bother about the size of the array.