I'm trying to use an array of objects to have barrels fall from the top of the screen to the bottom. (Like that old donkey kong game.) However, I can't seem to find a way to create more instances of the object than whatever the initial length of the array was. Anyone know a way to do this?
Here's the code:
Man Man;
Man background;
Man ladders;
PFont font1;
int time;
boolean run;
boolean newBarrel;
int barrelTotal;
Barrel[] barrel = new Barrel[100];
void setup() {
newBarrel = false;
run = true;
barrelTotal = 1;
time = millis();
size(800, 800);
Man = new Man();
background = new Man();
ladders = new Man();
for (int i = 0; i < barrel.length; i++) {
barrel[i] = new Barrel();
}
}
void draw() {
if (run == true) {
for (int i = 0; i < barrel.length; i++) {
if ((Man.bottom-10 >= barrel[i].top)&&(Man.bottom-10 <= barrel[i].bottom)&&(Man.Ladder == barrel[i].randomLadder)) {
print("GAME OVER!");
run = false;
}
if ((Man.top >= barrel[i].top)&&(Man.top <= barrel[i].bottom)&&(Man.Ladder == barrel[i].randomLadder)) {
print("GAME OVER!");
run = false;
}
}
}
if (run == true) {
background.createBackground();
Man.ladders();
Man.movement();
Man.createMan();
//spawns a barrel every second
if (millis()> time + 10) {
newBarrel = false;
print(" " + barrelTotal + " ");
time = time + 10;
barrelTotal = barrelTotal+1;
newBarrel = true;
}
for (int i = 0; i < barrelTotal; i++) {
if (newBarrel == true) {
}
barrel[i].gravity();
barrel[i].createBarrel();
}
//if(barrelTotal == 100){
//for (int i = 0; i < 50; i++){
// barrel[i] = "???";
//}
//}
}
}
Use an ArrayList instead of a native array. ArrayList will expand capacity as needed, whereas an array is fixed size and cannot be changed (you'd need to create a new larger array each time, which under the covers is what an ArrayList handles for you).
You can use ArrayList for this. You will change
// from
Barrel[] barrel = new Barrel[100]; // i suggest naming it to barrels instead of barrel
// to
ArrayList<Barrel> barrel = new ArrayList<>();
// or better
List<Barrel> barrel = new ArrayList<>();
// from
for (int i = 0; i < barrel.length; i++) {
barrel[i] = new Barrel();
}
// to
for (int i = 0; i < barrel.length; i++) {
barrel.add(new Barrel());
}
// from
barrel[i].<some-method()/attribute>
// to
barrel.get(i).<some-method()/attribute>
// etc
I highly recommend this for getting started with lists
https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
I'm currently working on a school project (a small android game) and so far I've written a code which generates a random equation 2 seconds after the activity InGame is launched and displays it in a textview. Another 5 seconds later, the second equation is generated and displayed in a different textview. Now the user has to decide if the second equation has a bigger result than the first one by either pressing the button bigger or smaller. If it was correct, the next equation should be displayed and it would go on like this until the user decided wrong.
Here is my code so far:
(Code for the first equation):
// Generate random equation and display it in textview
String[] operationSet = new String[]{"+", "-", "/", "*"};
String equation;
static double doubleAnswer1;
public void start1() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation = "";
for (int i = 0; i < numOfOperations; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView_first_equation);
TextEquation.setText(equation);
// Evaluate the result of the equation
double doubleAnswer1 = eval(equation);
String stringAnswer = Double.toString(doubleAnswer1);
TextView textAnswer = (TextView)findViewById(R.id.textView4);
textAnswer.setText(stringAnswer);
}
(Code for second equation (basically same as for first equation except the name of the strings and doubles are different)):
String equation2;
static double doubleAnswer2;
public void start2() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation2 = "";
for (int i = 0; i < numOfOperations; i++) {
equation2 += numbers.get(i);
equation2 += operations.get(i);
}
equation2 += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView3);
TextEquation.setText(equation2);
// Evaluate the result of the equation
double doubleAnswer2 = eval(equation2);
String stringAnswer = Double.toString(doubleAnswer2);
TextView textAnswer = (TextView)findViewById(R.id.textView_result2);
textAnswer.setText(stringAnswer);
}
And here is my onCreate code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ingame);
// Display first equation 2 seconds after the activity is launched
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
start1();
}
}, 2000);
final Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
start2();
}
}, 7000);
// Check if user was right or wrong
final Button buttonBigger = (Button)findViewById(R.id.button_bigger);
final Button buttonSmaller = (Button)findViewById(R.id.button_smaller);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger) && doubleAnswer1 < doubleAnswer2) {
Log.v("TAG", "you are right");
} else if(v.equals(buttonSmaller) && doubleAnswer1 > doubleAnswer2) {
Log.v("TAG", "you are right");
} else {
Log.v("TAG", "you are wrong");
}
}
};
buttonBigger.setOnClickListener(listener);
buttonSmaller.setOnClickListener(listener);
}
The app launches correctly and it also displays the first and second equation, but when I press one of the button, it tells me in the logcat you are wrong but I decided 100% correct. However if I debug the app, it tells me that doubleAnswer1 and doubleAnswer2 are both = 0. That's why it all ways tells me 'you are wrong'. I don't know how to fix this, maybe I need to store the doubleAnswer1 and doubleAnswer2 somewhere.
I really don't know what to do, so it would really help me if someone has an idea what to do.
If anything is unclear in my question, feel free to ask and I will try to clarify the problem.
Thank you in advance for your help!
I think your problem lies here:
double doubleAnswer1 = eval(equation);
I did a quick internet search and did not find any native function called eval(). Instead you should look into Script Engine Manager for java:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
or exp4j which is shown here:
Executing math equation in Android
Edit:
change the following:
double doubleAnswer1 = eval(equation);
to:
doubleAnswer1 = eval(equation);
Similarly do the same for doubleAnswer2
I'm trying to add all the values from different arrays to one 2d array and display it as a table in JavaFX.
Here's my try in doing it.
private StackPane table(Stage stage) {
StackPane root = new StackPane();
String[][] staffArray = new String[365][365];
staffArray[0][0] = "No. ";
staffArray[0][1] = "Check in";
staffArray[0][2] = "Check out";
staffArray[0][3] = "Name";
staffArray[0][4] = "Surname";
System.out.println(String.valueOf(arrRoom1[0][0]));
for (int i = 0; i < arrRoom1.length; i++) {
for (int y = 1; y < arrRoom1.length; y++) {
if (arrRoom1[i] == null) {
break;
}
staffArray[y][0] = String.valueOf(y);
staffArray[y][1] = String.valueOf(arrRoom1[i][0]);
staffArray[y][2] = String.valueOf(arrRoom1[i][1]);
staffArray[y][3] = String.valueOf(names1[i]);
staffArray[y][4] = String.valueOf(surnames1[i]);
}
}
System.out.println(staffArray[1][1]);
ObservableList<String[]> data = FXCollections.observableArrayList();
data.addAll(Arrays.asList(staffArray));
data.remove(0);//remove titles from data
TableView<String[]> table = new TableView<>();
for (int i = 1; i < staffArray.length; i++) {
for (int y = 0; y < 5; y++) {
if ( staffArray[i][y] == null) {
break;
}
TableColumn tc = new TableColumn(staffArray[i][y]);
final int colNo = i;
tc.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<String[], String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<String[], String> p) {
return new SimpleStringProperty((p.getValue()[colNo]));
}
});
tc.setPrefWidth(90);
table.getColumns().add(tc);
}
}
table.setItems(data);
root.getChildren().add(table);
return root;
}
However, every time I get null values in staffArray after the loop. Where might the mistake be in the nested loop?
Alright so here is my problem and my question to you.....
I have a game in which it needs to load images from the jar file (all the images are packed into the jar file like so):
I first have the unzip of the jar file:
Then it goes to:
Then inside each of those folder i have something that looks like this:
Now reminder above is the Jarfile GameClient.jar unziped and you see where the cards are in it.
So here is my code for trying to load each and every one of those images into memory
private void addCardsAndChangeSize() throws IOException
{
String tempString;
ImageIcon tempIcon;
allCards.clear();
ClassLoader cldr = this.getClass().getClassLoader();
URL imageURL;
for(int i = 0; i < all.length; i++)
{
for(int x = 0; x < clubs.length; x++)
{
tempString = all[i][x];
tempString = "/cards/"+cardFolders[i]+"/"+tempString;
imageURL = cldr.getResource(tempString);
tempIcon = resizeImage(new ImageIcon(imageURL),70,70,false);
tempString = all[i][x];
tempIcon.setDescription(tempString);
allCards.add(tempIcon);
}
}
backCard = resizeImage(new ImageIcon(cldr.getResource(back)),70,70,false);
}
So i call that in the contructor to load all the images into an ArrayList here is the whole class if you want to know what i do.
package global;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Cards
{
private ImageIcon backCard = new ImageIcon("cards/backCard.jpg");
private String back = "/cards/backCard.jpg";
private String[] cardFolders = {
"clubs","diamonds","hearts","spades"
};
private String[] clubs = {
"aceClubs.jpg","eightClubs.jpg","fiveClubs.jpg","fourClubs.jpg","jackClubs.jpg",
"kingClubs.jpg","nineClubs.jpg","queenClubs.jpg","sevenClubs.jpg","sixClubs.jpg",
"tenClubs.jpg","threeClubs.jpg","twoClubs.jpg"
};
private String[] diamonds = {
"aceDia.jpg","eightDia.jpg","fiveDia.jpg","fourDia.jpg","jackDia.jpg","kingDia.jpg",
"nineDia.jpg","queenDia.jpg","sevenDia.jpg","sixDia.jpg","tenDia.jpg","threeDia.jpg",
"twoDia.jpg"
};
private String[] hearts = {
"aceHearts.jpg","eightHearts.jpg","fiveHearts.jpg","fourHearts.jpg","jackHearts.jpg",
"kingHearts.jpg","nineHearts.jpg","queenHearts.jpg","sevenHearts.jpg","sixHearts.jpg",
"tenHearts.jpg","threeHearts.jpg","twoHearts.jpg"
};
private String[] spades = {
"aceSpades.jpg","eightSpades.jpg","fiveSpades.jpg","fourSpades.jpg","jackSpades.jpg",
"kingSpades.jpg","nineSpades.jpg","queenSpades.jpg","sevenSpades.jpg","sixSpades.jpg",
"tenSpades.jpg","threeSpades.jpg","twoSpades.jpg"
};
private String[][] all = {
clubs,diamonds,hearts,spades
};
private ArrayList<ImageIcon> allCards = new ArrayList<ImageIcon>();
public Cards()
{
try
{
addCardsAndChangeSize();
shuffle();
}
catch(Exception e)
{e.printStackTrace();}
}
/**
* #param x Cards name with extension
* #return Face Value of Card
*/
public static int getFaceValue(String x)
{
int face = 0;
switch(x)
{
case "aceClubs.jpg":
case "aceDia.jpg":
case "aceHearts.jpg":
case "aceSpades.jpg":
face = 1;
break;
case "eightClubs.jpg":
case "eightDia.jpg":
case "eightHearts.jpg":
case "eightSpades.jpg":
face = 8;
break;
case "fiveClubs.jpg":
case "fiveDia.jpg":
case "fiveHearts.jpg":
case "fiveSpades.jpg":
face = 5;
break;
case "fourClubs.jpg":
case "fourDia.jpg":
case "fourHearts.jpg":
case "fourSpades.jpg":
face = 4;
break;
case "jackClubs.jpg":
case "jackDia.jpg":
case "jackHearts.jpg":
case "jackSpades.jpg":
case "kingClubs.jpg":
case "kingDia.jpg":
case "kingHearts.jpg":
case "kingSpades.jpg":
case "queenClubs.jpg":
case "queenDia.jpg":
case "queenHearts.jpg":
case "queenSpades.jpg":
case "tenClubs.jpg":
case "tenDia.jpg":
case "tenHearts.jpg":
case "tenSpades.jpg":
face = 10;
break;
case "twoClubs.jpg":
case "twoDia.jpg":
case "twoHearts.jpg":
case "twoSpades.jpg":
face = 2;
break;
case "threeClubs.jpg":
case "threeDia.jpg":
case "threeHearts.jpg":
case "threeSpades.jpg":
face = 3;
break;
case "sixClubs.jpg":
case "sixDia.jpg":
case "sixHearts.jpg":
case "sixSpades.jpg":
face = 6;
break;
case "sevenClubs.jpg":
case "sevenDia.jpg":
case "sevenHearts.jpg":
case "sevenSpades.jpg":
face = 7;
break;
case "nineClubs.jpg":
case "nineDia.jpg":
case "nineHearts.jpg":
case "nineSpades.jpg":
face = 9;
break;
}
return face;
}
//shuffles all the cards in the deck
private void shuffle()
{
long seed = System.nanoTime();
Collections.shuffle(allCards, new Random(seed));
}
/**
* Chooses a card at random from the deck. Also removes that card when chosen
* #return randomly chosen card
*/
public ImageIcon getRandomCard()
{
int index = ((int)Math.random() * allCards.size());
return allCards.remove(index);
}
/**
* #return Image of the back of a card
*/
public ImageIcon getBackCard()
{return backCard;}
public static ImageIcon parseImage(String x)
{
if(x.contains("Dia"))
return new ImageIcon("cards/diamonds/"+x);
else
if(x.contains("Clubs"))
return new ImageIcon("cards/clubs/"+x);
else
if(x.contains("Hearts"))
return new ImageIcon("cards/hearts/"+x);
else
if(x.contains("Spades"))
return new ImageIcon("cards/spades/"+x);
return null;
}
//adds all the cards and adds a description to them loaded into memory
private void addCardsAndChangeSize() throws IOException
{
String tempString;
ImageIcon tempIcon;
allCards.clear();
ClassLoader cldr = this.getClass().getClassLoader();
URL imageURL;
for(int i = 0; i < all.length; i++)
{
for(int x = 0; x < clubs.length; x++)
{
tempString = all[i][x];
tempString = "/cards/"+cardFolders[i]+"/"+tempString;
imageURL = cldr.getResource(tempString);
tempIcon = resizeImage(new ImageIcon(imageURL),70,70,false);
tempString = all[i][x];
tempIcon.setDescription(tempString);
allCards.add(tempIcon);
}
}
backCard = resizeImage(new ImageIcon(cldr.getResource(back)),70,70,false);
}
//resizes images
public ImageIcon resizeImage(ImageIcon imageIcon, int width, int height, boolean max)
{
Image image = imageIcon.getImage();
Image newimg = image.getScaledInstance(-1, height, java.awt.Image.SCALE_SMOOTH);
int width1 = newimg.getWidth(null);
if ((max && width1 > width) || (!max && width1 < width))
newimg = image.getScaledInstance(width, -1, java.awt.Image.SCALE_SMOOTH);
return new ImageIcon(newimg);
}
}
I keep getting null pointer exception on the tempIcon = resizeImage(new ImageIcon(imageURL),70,70,false);
Can anyone tell me why this isn't loading the images properly? Reminder i am pre-loading them into memory. My question is not how to make this better i am just simply asking what am i doing wrong with the class loader and stuff like that......
I am somewhat new at java and i know some of this code will look horrible to you but please again i am not asking how to make this code "pro" im just looking for the explanation why its giving me null.
Thanks!
P.S. If you need more pictures of info or w.e. i will try to put that up right away
Your problem is that cldr.getResource(tempString); does not return object but null. Then, something is wrong with tempString. Classloader cannot find this file, so returns null.
Change tempString = "/cards/"+cardFolders[i]+"/"+tempString;
To tempString = "cards/"+cardFolders[i]+"/"+tempString;
You should be using the getResource of Class, not ClassLoader. The getResource method in Class does useful transformations on the path before giving it to the ClassLoader version of the method, like deciding if the path is relative to the class or absolute, and so ClassLoader doesn't expect to see things like / at the start of the path. You can see this clearly in the getResource javadoc.
So i found out the solution i still don't quite understand why this is the answer but here ya go.
This is the revised code and works fine
private void addCardsAndChangeSize() throws Exception
{
String tempString;
ImageIcon tempIcon;
allCards.clear();
URL imageURL;
for(int i = 0; i < all.length; i++)
{
for(int x = 0; x < clubs.length; x++)
{
tempString = all[i][x];
tempString = "/cards/"+cardFolders[i]+"/"+tempString;
imageURL = this.getClass().getResource(tempString);
System.out.println(tempString);
System.out.println(imageURL == null);
tempIcon = resizeImage(new ImageIcon(imageURL),70,70,false);
tempString = all[i][x];
tempIcon.setDescription(tempString);
allCards.add(tempIcon);
}
}
backCard = resizeImage(new ImageIcon(this.getClass().getResource(back)),70,70,false);
}
You have to have that "/cards/" and also you this.getClass().getResource(String res);
Thanks for all your help guys!
I get no compiler errors, but I get this when I run the program and trying to run case 1, the method lesFraFil():
Exception in thread "main" java.lang.NumberFormatException: For input string: ";
"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Hybelhus.lesFraFil(Oblig4.java:63)
at Hybelhus.oversikt(Oblig4.java:134)
at Hybelhus.meny(Oblig4.java:107)
at Oblig4.main(Oblig4.java:23)
I have tried asking all my classmates, but none of them were able to help me.
import easyIO.*;
class Oblig4{
public static void main(String[] args) {
int[] antallHybler = new int[18];
for (int i = 0; i < args.length; i++) {
antallHybler[i] = Integer.parseInt(args[i]);
}
Hybelhus hh = new Hybelhus(antallHybler);
hh.meny();
}
}class Hybelhus{
Out skjerm = new Out();
In lesFil = new In("Hybeldata.txt");
In tast = new In();
Out skrivTilFil = new Out("Hybeldata.txt", true);
Hybel[][] hybler = new Hybel[3][6];
void lesFraFil(){
int maaned = lesFil.inInt(";");
int aar = lesFil.inInt(";");
int totFortjeneste = lesFil.inInt(";");
int totAntallMåneder = lesFil.inInt(";");
int månedsleieVanligHybel = lesFil.inInt(";");
int månedsleieToppEtasjeHybel = lesFil.inInt(";");
skjerm.outln(maaned + ", " + aar + ", " + totFortjeneste + ", " + totAntallMåneder + ", " + månedsleieVanligHybel + ", " + månedsleieToppEtasjeHybel);
while(!lesFil.endOfFile()){
for(int i = 0; i < hybler.length; i++){
for(int j = 0; j < hybler[i].length; j++){
String tekst = lesFil.inLine();
if(lesFil == null){
continue;
}
String[] enArray = tekst.split("; ");
hybler[i][j] = new Hybel();
hybler[i][j].etasje = Integer.parseInt(enArray[0])-1;
hybler[i][j].rom = enArray[1].charAt(0);
hybler[i][j].leietager.saldo = Integer.parseInt(enArray[2]);
hybler[i][j].leietager = new Student(enArray[3]);
}
}
}
}
Etasjer[] etasje = new Etasjer[3];
Hybelhus(int[] antallHybler) {
for(int i = 0; i < etasje.length; i++){
etasje[i] = new Etasjer(antallHybler[i]);
}
}
void SkrivUt() {
for(int i = 0; i < etasje.length; i++){
System.out.println("hei");
}
}
void meny() {
int aksjon = 0;
while (aksjon != 8) {
skjerm.outln("\nMENY");
skjerm.outln("1. Skriv oversikt");
skjerm.outln("2. Registrer ny leietaker");
skjerm.outln("3. Registrer betaling fra leietaker");
skjerm.outln("4. Registrer frivillig utflytting");
skjerm.outln("5. Månedskjøring av husleie");
skjerm.outln("6. Kast ut leietakere");
skjerm.outln("7. Øk husleien");
skjerm.outln("8. Avslutt");
aksjon = tast.inInt();
switch (aksjon) {
case 1: oversikt(); break;
case 2: regLeietaker(); break;
case 3: regBetaling(); break;
case 4: regUtflytting(); break;
case 5: kjorHusleie(); break;
case 6: kastUt(); break;
case 7: okHusleie(); break;
case 8:; avslutt(); break;
default: System.out.println ("\nDu må taste inn et av de åtte valgene over");
break;
}
}
}
void oversikt() {
final int BREDDE1 = 10;
final int BREDDE2 = 35;
final int BREDDE3 = 25;
skjerm.out("Hybel", BREDDE1);
skjerm.out("Leietager", BREDDE2);
skjerm.out("Saldo", BREDDE3);
skjerm.outln("\n----------------------------------------------------\n");
lesFraFil();
}
void regLeietaker(){
}
void regBetaling() {
}
void regUtflytting(){
}
void kjorHusleie() {
}
void kastUt(){
}
void okHusleie() {
}
void avslutt() {
}
}
class Etasjer{
Hybel[] hybelNavn;
Etasjer(int antallHybler){
hybelNavn = new Hybel[antallHybler];
for(int i = 0; i < hybelNavn.length; i++){
char c = (char) i;
c += 'A';
hybelNavn[i] = new Hybel();
}
}
}
class Hybel{
int etasje;
char rom;
Student leietager;
Hybel() {
}
}
class Student{
int saldo;
String studentNavn;
Student(String studentNavn){
this.studentNavn = studentNavn;
}
}
I don't understand what this means lesFil.inInt(";");, but to me this method obviously parses a string to an int and returns an int (from my best guess by the name of the method and since you say your program does not show any compile errors).
And since ";" is not a number, it throws a NumberFormatException
You need to use a debugger.. the line of code that is throwing this exception is line 63 of Oblig4.java. Because of formatting, I'm not sure which line this is. So look at your source code and goto line 63 and see what you are doing there..
I'm guessing it
hybler[i][j].etasje = Integer.parseInt(enArray[0])-1;
What you can do is :
String temp = enArray[0];
System.out.println(temp);
int tempInt = Integer.parseInt(temp)-1;
System.out.println(tempInt);
hybler[i][j].etasje = tempInt;
And you'll see what's going on... (if you don't know how to use a debugger!)
Good luck!
Solve your problem ???