I'm trying to establish a string array to hold the names of golfers in a scorecard application. I am asking for user input to get the number of players, and I would like to use that value to define the length of the array. I have a variable to hold the value entered called NUM_PLAYERS, and I am having a problem getting it to define my array length. String[ ] players = new String[NUM_PLAYERS]; When I get to my players entry loop I get the out of bounds exception as soon as I get past the first entry, because the array is only one element long. Here is the ScoreCalc class and my run program as they stand so far:
ScoreCalc class
GameChicago program
my suggestion is to move the initialise of the array to the constructor like this
public class ScoreCalc {
private String[] players;
public ScoreCalc(int playersNum){
this.players = new String[playersNum];
}
...
}
and to create the class after you get the user's input, like this
input = ...
ScoreCalc game = new ScoreCalc(input)
you have some loop there of variables definition with the NUM_PLAYERS
Related
so I am working on a graphical calculator (bit more of a challenge than the basic windows one), and I want to be able to do the entire "math" in one textfield, just like typing in "5+3-5*11/3" and it gives you the solution when you press '='
I decided to make it with arrays of numbers and symbols, but I have no idea how to make it to fill the next array if this one already is used:
var numbers:Array = new Array("","","","","","","","","","","","","","","","");
var actions:Array = new Array("","","","","","","","","","","","","","","","");
I am using split to split the numbers I input with symbols, and I want the numbers to be placed in the arrays. Example: I type in 555+666 and then I need to have something like
if (numbers[0] = "") {numbers[0] = 555}
else if (numbers[1] = "") {numbers[1] = 555}
else if.....
Know what I mean?
Pretty hard to describe...
something like... When I type in a number, if the numbers[0] is already filled, go fill in numbers[1], if numbers[1] is filled, go to numbers[2] etc
Even if I agree with #Nbooo and the Reverse Polish Notation
However Vectors may have a fixed length.
This is not an answer but just an example (if the length of Your Array must be defined):
//Just for information..
var numbs:Vector.<Number> = new Vector.<Number>(10,true);
var count:uint = 1;
for (var i in numbs){
numbs[i] = count++
}
trace(numbs);
// If You try to add an element to a Vector,
// You will get the following Error at compile time :
/*
RangeError: Error #1126: Cannot change the length of a fixed Vector.
at Vector$double/http://adobe.com/AS3/2006/builtin::push()
at Untitled_fla::MainTimeline/frame1()
*/
numbs.push(11);
// Will throw an Error #1126
trace(numbs);
If You use this code to update a fixed Vector, this will not throw an ERROR :
numbs[4]=11;
trace(numbs);
Output :
1,2,3,4,5,6,7,8,9,10
1,2,3,4,11,6,7,8,9,10
// length is 10, so no issue...
If You consider the performance between Arrays and vectors check this reference : Vector class versus Array class
I hope this may be helpful.
[EDIT]
I suggest you to check at those links too :
ActionScript 3 fundamentals: Arrays
ActionScript 3 fundamentals: Associative arrays, maps, and dictionaries
ActionScript 3 fundamentals: Vectors and ByteArrays
[/EDIT]
Best regards.
Nicolas.
What you want to implement is the Reverse Polish Notation. In actionscript3 arrays are dynamic, not fixed size, that means you can add elements to the array without concern about capacity (at least in your case).
const array:Array = new Array();
trace(array.length); // prints 0
array.push(1);
array.push(2);
trace(array.length); // prints 2
I suggest using "push" and "pop" methods of Array/Vector, since it's much more natural for such task. Using those methods will simplify your implementation, since you'll get rid of unnecessary checks like
if (numbers[1] == "") {...}
and replace it just with:
numbers.push(value);
and then to take a value from the top:
const value:String = numbers.pop();
I'm attempting to create a class that takes a certain number of ppm files that are formatted identically (which are input by the user in the class containing the main method), and then compares the corresponding integers in each file one by one, storing them in a temporary array so that they can be sorted and the median can be taken and written to a new ppm file ultimately creating a new image.
For example, if I had 3 files I would want to take the first integer value (after the 3 lines of the header) of each one, storing each value in the temporary array (in this case of size 3) for comparison and then I would want to do the same thing with the second value in each file, and the third, etc. This is what I'm stuck on. Right now the way that I have it set up is leading to a null pointer exception but I've tried various other things that have ran but led to the incorrect result. Any advice?
import java.io.File;
import java.io.IOException;
//import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Arrays;
public class Effects {
public Effects() throws IOException{}
public void filter(File[] files, String outputFileName) throws IOException {
//Create an array of Scanners equal to the number of files
Scanner[] scanner = new Scanner[files.length];
//Create a scanner that is linked to each file that must be read
for(int i=0; i<scanner.length; i++) {
Scanner scan = new Scanner(files[i]);
scanner[i]=scan;
//For each scanner, first skip the first 3 lines of text, then take one integer from
//file and store it in the temporary array compare [such that the integer parsed
// by scanner[0] is stored at compare[0] and so on.
while(scan.hasNext()) {
int [] compare = new int [scanner.length-1];
boolean header = true;
for(int j=0; j<files.length; j++) {
while(header==true) {
//the first 3 lines in each document need to be skipped before the integer values of relevance begin.
scanner[j].nextLine();
scanner[j].nextLine();
scanner[j].nextLine();
header = false;
}
int value = scanner[j].nextInt(); //NULL POINTER EXCEPTION
compare[j] = value;
}
}
}
}
}
The reason you're seeing the NPE is that the j=1 code runs before i=1 and therefore scanner[1] doesn't exist yet.
It might be a good idea to handle reading each file separately and combining the values later. That would also split your reading code from your calculations, making it easier to track down any future bugs.
Let me cut to the main issue, I have a grid which is 50 by 50. And I need a way of having a true or false variable for each cell in the grid and the default value would be false, every time the method is called.
I need the array so I can see which cells I have visited so I don't need to revisited them for my path finding system that I'm working on .
But currently I have a double array[] [] which I need to loop every time I use this method. (up to 3 times a second but mostly never) which means looping 2500 value. Which doesn't sound very good. What would be the best solution, is this the best solution or am I missing something stupid.
Hope you can help and point me into the right direction.
Another possible improvement is using a single-dimensional vector, maybe wrapped into a class, that will contain 2500 elements and its indexes would mean (width*50+height). Like this:
private var _visited:Vector.<Boolean>;
function checkVisited(x:int,y:int):Boolean {
return _visited(x*50+y); // x and y are in 0-49 range
}
Vectors can be two-dimensional should you need them, you declare vector of vectors like this:
var _visited:Vector.<Vector.<Boolean>>;
Initialize with pushing the filled Vector.<Boolean> once, then just change the elements as you do with a normal array.
The main advantage of vectors is that they are solid, that is, if there are 50 elements in a vector, you are sure that there exists a value at any index from 0 to 49 (even if null, or NaN in case of Numbers), this also makes internal processing of vectors easier, as the Flash engine can calculate proper memory location by just using the index and the link to the vector, which is faster than first referencing the array about whether there is a value at that index, if yes, get its memory location, then reference.
From my experience of making tile based games with different grids I usually have a Tile class, that will contain all your necessary values, most typical would be:
posX:int
posY:int
isChecked:Boolean
You can add as many as you need for your app.
Then I have a Grid class that will create you grid and have some useful methods like giving neighbor tiles.
In the Grid class I make the grid this way:
public var tileLineArray:Vector.<Tile>;
public var tile2dArray:Vector.<Vector.<Tile>>;
public function makeGrid(w:int, h:int):void
{
tileLineArray = new Vector.<Tile>();
tile2dArray = new Vector.<Vector.<Tile>>();
for (var i:int = 0; i < gridWidth; i++)
{
var rowArray:Vector.<Tile> = new Vector.<Tile>();
for (var j:int = 0; j < gridHeight; j++)
{
var t:Tile = new Tile();
t.posX = i;
t.posY = j;
tileLineArray.push(t);
rowArray.push(t);
}
tile2dArray.push(rowArray);
}
}
What it will give you is that you can access tiles in a single line to by coordinates x,y;
var myTile:Tile = tileLineArray[lineID];
var myTile:Tile = tile2dArray[targetX][targetY];
I use Vectors in this example as they outperform Arrays and you keep the type of the stored object intact.
It is not a problem for Flash to loop through the array; if you want improve performance, break the loop if you've done all what you wanted with it, continue the loop if the tile does not meet the requirements and you don't need to process it.
Also, having a 2d array can improve performance, since you can process only the area of the array that you need.
One more advice is not to be afraid to make X more smaller arrays to store some data from the bigger array and loop trough the small ones. As the data of the arrays is not a primitive (int, uint etc.) but a Class, it will hold a pointer/reference to the object, so you're not actually making copies of the objects every time.
I'm taking a online Java course and attempting my 2nd assignment. The first assignment was not difficult but this one is just way over top. I honestly don't know where to begin. The problem is this class is online, basic instructions are to read these chapters and then write the program. There's not much guidance since my instructor is not with me physically.
I've never used scanner before or created two dimensional arrays. My instructor gives notes on what to do in each area of his skeleton program but I don't have a clue which one to start with.
Your task is to implement a similar scheme to store poynomials of any number of terms, such that the
number of terms and the components (coefficient, variable and exponent) of every term are entered from
the keyboard.
To implement the interactive input we will using the Java class Scanner, defined in the java.utils
standard package. The Scanner class can be used in Java to read data types from a file. Since the input
console (keyboard) is treated as the file called System.in, we can create a Scanner for that input stream
as new Scanner (System.in), as shown below. Once you define a Scanner object, using its method
next() you can read Strings from the file/keyboard.
The incomplete program below is your assignment. You are supposed to complete without changing the
existing code.
Your output should be the terms of the polynomial entered by the user, separated by + signs.
Additional instructions in the code below, that you will change to achieve the requested functionality.
import java.util.Scanner;
public class Polynomials {
public static void storeTerm (int coeff, String var, int exp, String poly[][], int
where){
//ENTER THE COEFFICIENT, VARIABLE AND EXPONENT INTO THE
//ARRAY POLY THAT REPRESENTS THE POLYNOMIAL, AT POSITION "where"
//THAT RANGES BETWEEN INDEX 0 AND POLY.LENGTH-1
}
public static void printTerm (String [] term) {
//PRINTS EACH TERM
//IF THE EXPONENT OF THE VARIABLE IS 1 DOE NOT PRINT THE EXPONENT
//IF THE EXPONENT IS 0, PRINT ONLY THE COEFFCIENT
//IF THE COEFFICIENT IS 1, DO NOT PRINT IT, UNLESS IT IS THE ONLY COMPONENT OF
//THE TERM
}
public static void printPolynomial(String terms[][]){
//CALL printTerm in a loop to print all terms separated by + signs
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numberTerms = 0;
System.out.println("How many terms?");
numberTerms = sc.nextInt();
//ENTER HERE THE CODE TO CREATE THE TWO DIMENSIONAL ARRAY NEEDED TO STORE THE TERMS
//OF THE POLYNOMIAL
if (numberTerms <= 0)
System.out.println("Error: Polynomials must have at least one term");
else {
String coeff = "", variable="", exponent="";
for (int i = 1; i<= numberTerms; i++) {
System.out.println("Enter the coeffcient for term " + i);
coeff = sc.next();
System.out.println("Enter the variable name:");
variable = sc.next();
System.out.println("Enter the expoenent for this term");
exponent = sc.next();
//CALL METHOD storeTerm TO INPUT THIS NEW TERM INTO THE ARRAY WRITE THE CORRECT
//CALL TO storeTerm HERE
}
printPolynomial(terms);
}//endf if
}//end main
}//end class
Again not looking for answers. Just where to start. Then I'll post my results.
It is not completely obvious where the two-dimensional array enters, since the structure hints at a list of terms.
You will need to define a data structure, in Java as a class, to hold the information for each term.
From the description, it seems that the input are polynomials of the form 3x^2+5y^7 and not xy+3y^2z^3.
I wrote an array, where, when a hittest occurs, a number should be pushed into the array. However, when I use myArray.push, it enters the number, and when i call myArray.push again, instead of entering the number again and having 2 numbers in my array, it just enters the number in the same spot. So, if i use trace(myArray.length), no matter how many times it has pushed, it keeps saying I have 1 number stored.
This is my code:
if (hitTestObject(target.hit)) {
//pushes a number into an array
myArray.push();
//checks array length
if (myArray.length == 3) {
//do stuff
}
}
I've tried numbers, strings, and Math.random() in the parameters for myArray.push(), but I always get the same result of only having 1 item in my array.
For reference, this is how I wrote my variable for it:
public var myArray:Array = new Array();
You have to push something into the array. Try:
myArray.push(myArray.length);
However, it looks like you'd be better off just incrementing a number rather than creating an array. An array is a container of objects to be later referenced. So, unless you need to track that the third object in the array is in fact '2'...the array is useless. Try creating a number and increment the variable each time. Like this:
// Declared outside of the function
var integer:int = 0;
//
if (hitTestObject(target.hit)) {
integer = integer + 1;
// likewise you could use ++integer or integer++;
if (integer == 3) {
//do stuff
}
}
Based on your code, you are not actually pushing anything into the array.
The correct syntax is :
myArray.push(something);