I need to create an array of integers contained within an array of words. I keep getting an error
cannot convert from int[] to java.lang.String[]
where it says
private String[][] expenseName = {clothes, tuition, transportation, food, housing, books};
This is my code
public class Budget{
///////////////fields////////////////
int expenseAmount[] = {1000, 2000, 3000, 4000, 5000, 6000};
int monthNumber[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int clothes[]= {100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210};
int tuition[] = {200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200};
int transportation[]={100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210};
int food[]={80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80};
int housing[]={150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150};
int books[]= {200, 0, 0, 0, 0, 0, 0, 300, 0, 0, 0, 0};
int i=0; // this is arbitrary. Never hard code numbers unless that number is never going to change. in that case you make a variable and define it.
int month_num;
private String[][] expenseName = {clothes, tuition, transportation, food, housing, books};
/////////constructors///////////////
public Budget() {}
public Budget(int name) {this.expenseName[i][i] = name;}
public Budget(String name, int clothes, int tuition, int transportation, int food, int housing, int books)
{
this.expenseName[i] = name;
this.clothes[i] = clothes;
this.tuition[i] = tuition;
this.transportation[i] = transportation;
this.food[i] = food;
this.housing[i] = housing;
this.books[i] = books;
this.monthNumber[i] = month_num;
}
/////////////methods///////////
public String getexpenseName() {return expenseName[i][i];}
public int getclothes() {return clothes[i];}//change the I
public int gettuition() {return tuition[i];}
public int gettransporation() {return transportation[i];}
public int getfood() {return food[i];}
public int gethousing() {return housing[i];}
public int books() {return books[i];}
public int getmonthNumber() {return monthNumber[i];}//change the i
public void setExpenseName(String name)
{
this.expenseName[i][i] = name;
}
public boolean setexpenseAmount(int num)
{
if (this.expenseAmount[i] == 0)
{this.expenseAmount[i] = num;
return true;
}
else
return false;
You need quotes around your strings:
private String[] expenseName = {"clothes", "tuition", "etc"};
or you need to declare it int[][]
private int[][] expenseName = {clothes, tuition};
As the error message clearly states, you can't put an int[] into an array of String[]s.
Change
private String[][] expenseName = {clothes, tuition, transportation, food, housing, books};
to
private int[][] expenseName = {clothes, tuition, transportation, food, housing, books};
In Java, you cannot use an array of int as an array of String.
That will just not work, like the error says.
I guess that you must be familiar with some language where there is no type checking and you can do whatever you want. But this is Java.
You have to convert the int[] to String[], for example like this.
public class ArrayIntToString {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3 };
String[] numbersAsStrings = new String[numbers.length];
int i = 0;
for (Integer number : numbers) {
numbersAsStrings[i++] = number.toString();
}
}
}
Related
This question already has answers here:
Java: moving items in array
(6 answers)
Closed 6 years ago.
How to move element of array to specific position on Android JAVA.
We have
int oldPosition, int newPosition
and some like
JSONObject[] tmp = new JSONObject[999];
array of JSONObjects
If you want to just move
tmp[newPosition]=tmp[oldPosition];
Swap
JSONObject jo= tmp[oldPosition];
tmp[oldPosition]=tmp[newPosition];
tmp[newPosition]=jo;
EDIT: There are other ways but you can go through this as well to get your result :)
Exercise : You can understand this logic and use JSONObject type and do necessary changes, Watch out for NullPointerExceptions , handle everything i am lazy to do them
let's say you have int array --> private int array[];
array = new int[]{10,20,30,40,50,60,70,80,90,100};
call this method if you want to swap elements,
swapNumbers(array,9,1);
.
public int[] swapNumbers(int [] arr, int possition1, int possition2){
int temp = arr[possition2];
arr[possition2] = arr[possition1];
arr[possition1] = temp;
System.out.println("array -->" + Arrays.toString(array));
return arr;
}
out put : array[10, 100, 30, 40, 50, 60, 70, 80, 90, 20]
But that doesn't satisfy you?
you need out put to be like this : array[10, 100, 20, 30, 40, 50, 60, 70, 80, 90]
you can use below method
resetUpMyArray(array, array[9],1);
System.out.println("array Finally changed-->" + Arrays.toString(array));
enjoy,
public int[] resetUpMyArray(int[] inputArray, int deleteMeValue,int addMePosition) {
List resultLinkedList = new LinkedList();
for (int itemValue : inputArray)
if (deleteMeValue == itemValue) {
System.out.println("Do not add this value"+itemValue);
} else {
System.out.println("Do add this value "+itemValue +"position-"+deleteMeValue);
resultLinkedList.add(itemValue);
}
System.out.println("array -as new L.L->" + resultLinkedList);
resultLinkedList.add(addMePosition,deleteMeValue);
System.out.println("array -as new L.L all set->" + resultLinkedList);
array = new int[resultLinkedList.size()];
for (int i = 0; i < resultLinkedList.size(); i++) {
array[i] = (int) resultLinkedList.get(i); // Watch out for NullPointerExceptions!
}
return array;
}
Here is two simple algorithm.
Switch values :
switch(array, from, to)
tmp = array[to]
array[to] = array[from]
array[from] = tmp
That will give something like
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
|--<---->--|
[10, 20, 60, 40, 50, 30, 70, 80, 90, 100]
This will simply store the values that will be replace at the index to to be place at index from
Move and shift values:
This one will move one values a shift the values next.
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
|------------^
[10, 20, , 40, 50, 60, 30, 70, 80, 90, 100]
<-----------
[10, 20, 40, 50, 60, 30, 70, 80, 90, 100]
For this, the solution is quite the same, store the values in tmp but shift every value to fill the gap. This code will only work if from < to
tmp = array[to]
i = from
while(i < to)
array[i] = array[i+1]; --Shift the value
i = i + 1
array[to] = tmp;
I'm trying to create a basic "tree" shape in processing. I have an initial constructor that takes my arguments and draws them in fixed locations on the background, but I also have a secondary constructor that is supposed to assign random values that I specify so that each time it is drawn the trees are in different locations. However, I am having an issue with Processing where it says The function random(int) does not exist and I can't seem to find a solution to the issue.
I realize this is a naive approach to graphics, but I am just trying to get my feet wet with Processing.
My Tree.java class:
import processing.core.PApplet;
import java.util.Random;
public class Tree{
// Instance variables
private int centerX, centerY;
private float scale;
private int trunkR, trunkG, trunkB, leavesR, leavesG, leavesB;
private static PApplet sketch;
public Tree(int theCenterX, int theCenterY, float theScale,
int theTrunkR, int theTrunkG, int theTrunkB,
int theLeavesR, int theLeavesG, int theLeavesB)
{
centerX = theCenterX;
centerY = theCenterY;
scale = theScale;
trunkR = theTrunkR;
trunkG = theTrunkG;
trunkB = theTrunkB;
leavesR = theLeavesR;
leavesG = theLeavesG;
leavesB = theLeavesB;
}
public Tree(){
centerX = random(960.0);
centerY = random(700.0);
scale = random(2.0);
trunkR = random(255.0);
trunkG = random(255.0);
trunkB = random(255.0);
leavesR = random(255.0);
leavesG = random(255.0);
leavesB = random(255.0);
}
public void draw(){
sketch.noStroke();
sketch.fill(trunkR, trunkG, trunkB);
sketch.rect(centerX, centerY, 80*scale, 300*scale);
sketch.fill(leavesR, leavesG, leavesB);
sketch.triangle(centerX - 40*scale, centerY + 40*scale, centerX + 40*scale, centerY - 80*scale, centerX + 120*scale, centerY + 40*scale);
}
public static void setup(PApplet theSketch){
sketch = theSketch;
}
}
And here is my main class that calls the tree class to create the objects:
Tree tree, tree2, tree3, tree4, randomTree;
void settings(){
size(1000, 1000);
}
void setup(){
setupGraphicClasses();
tree = new Tree(width/2 - 400, height/2 - 100, 1.0, 67, 12, 12, 27, 129, 28);
tree2 = new Tree(width/2 + 200, height/2 + 150, 1.5, 67, 12, 12, 27, 129, 28);
tree3 = new Tree(width/2, height/2 - 80, 0.5, 67, 12, 12, 27, 129, 28);
tree4 = new Tree(width/2 + 320, height/2 - 170, 0.9, 67, 12, 12, 27, 129, 28);
randomTree = new Tree();
}
void draw() {
background(127);
noStroke();
fill(16, 85, 17);
rect(0, 500, 1000, 500);
fill(70, 195, 255);
rect(0, 0, 1000, 500);
tree.draw();
tree4.draw();
tree2.draw();
tree3.draw();
randomTree.draw();
}
public void setupGraphicClasses() {
Tree.setup(this);
}
Why would I be getting this error? I have tried casting the instance variables as float since those are the parameters the random() function accepts as parameters, but then I get a different error message.
You're calling the random() function from your Tree class, not your sketch class. That won't work, because only the sketch class knows about the random() function.
One approach to fix this is to pass an instance of your sketch into the Tree class, then use that to get to the random function. Something like this:
void setup(){
Tree tree = new Tree(this);
}
class Tree{
public Tree(PApplet sketch){
float x = sketch.random(100);
}
}
If all you need is the random() function, this might be overkill though. You could just use the Math.random() function instead. Of course, this locks you into deploying as Java, which might be overly restrictive.
hi recently i implemented the bezier curve it works fine but my problem is i dont know how to map x,y points to the screen because it gives me x,y in form of decimal points i will appreciate any help
this is my code which works i think .
import java.util.ArrayList;
public class Bezier {
public static void main(String[] args) {
ArrayList<Point> CP = new ArrayList<Point>();
CP.add(new Point(-5, 0));
CP.add(new Point(0, 5));
CP.add(new Point(5, 0));
CP.add(new Point(0,-5));
Bezier curve = new Bezier(3, 0, 0.01, CP);
curve.DefineBezierCurve();
ArrayList<Point>Results = curve.getCurvePoints();
for(int i = 0; i<Results.size() ; i++){
Point x = Results.get(i);
System.out.println(x.Y);
}
}
// class definitions
private ArrayList<Point> controlPoints;// the control points
private double t;//the value of t indicates the location of the point on the line sigment
private double step;// the increment value that the t increments
private int N;//the Beziar Curve Order
private ArrayList<Point>CurvePoints;// genrated (x,y) values of the curve
// constructor
public Bezier(int n , double t , double step ,ArrayList<Point> CP ){
this.N = n ;
this.t = t;
this.step = step;
this.controlPoints = CP;
CurvePoints = new ArrayList<Point>();
}
private int factorial(int x){
int result =1;
for(int i= x ; x>0 ; x--){
result*=x;
}
return result;
}
private int BinomialCoefficient(int i){
// we get the order form the global variable
int factN = factorial(this.N);
int factI = factorial(i);
int factN_I = factorial(this.N-i);
int theCoefficient = (factN/(factI*factN_I));
return theCoefficient ;
}
private Point BI_N_P(int i){
int coefficient = BinomialCoefficient(i);
Point CurrentControlPoint = this.controlPoints.get(i);
double X = coefficient* Math.pow(t,i)* Math.pow((1-t),(this.N-i))*CurrentControlPoint.X ;
double Y = coefficient* Math.pow(t,i)* Math.pow((1-t),(this.N-i))*CurrentControlPoint.Y ;
Point Tmp = new Point(X, Y);
return Tmp;
// this.CurvePoints.add(PointOnCrve);
}
private void DefineBezierCurve(){
while(t<=1){
Point PointOnCurve = new Point(0, 0);
for(int i = 0 ; i<=this.N ; i++){
Point tmp = BI_N_P(i);
PointOnCurve.X+=tmp.X;
PointOnCurve.Y+=tmp.Y;
}
this.CurvePoints.add(PointOnCurve);
this.t+=this.step;
}
}
public ArrayList<Point> getCurvePoints(){
return this.CurvePoints;
}
}
class Point{
public double X;
public double Y;
public Point(double x,double y){
X=x;
Y=y;
}
}
i used the genrated points to draw them in excel and this was my result
example of cubic bezier curve initial t=0,step = 0.01 , with control points
(-5, 0),(0, 5),(5, 0),(0,-5)
generated X points
-5.0
-4.85001
-4.700079999999999
-4.55027
-4.400639999999999
-4.25125
-4.102159999999999
-3.9534299999999996
-3.80512
-3.6572900000000006
-3.5100000000000007
-3.3633100000000002
-3.2172800000000006
-3.07197
-2.92744
-2.7837499999999995
-2.6409599999999993
-2.4991299999999996
-2.3583199999999995
-2.2185899999999994
-2.0799999999999996
-1.9426099999999988
-1.8064799999999992
-1.6716699999999989
-1.5382399999999987
-1.4062499999999998
-1.2757599999999993
-1.1468299999999993
-1.0195199999999995
-0.8938899999999995
-0.7699999999999991
-0.6479099999999991
-0.527679999999999
-0.4093699999999989
-0.29303999999999886
-0.17874999999999885
-0.06655999999999862
0.043470000000001674
0.15128000000000164
0.256810000000002
0.3600000000000019
0.4607900000000018
0.5591200000000022
0.6549300000000019
0.7481600000000019
0.838750000000002
0.9266400000000021
1.011770000000002
1.094080000000002
1.173510000000002
1.2500000000000018
1.3234900000000016
1.3939200000000018
1.4612300000000018
1.5253600000000018
1.5862500000000017
1.6438400000000017
1.6980700000000017
1.7488800000000018
1.7962100000000016
1.8400000000000019
1.8801900000000014
1.916720000000001
1.9495300000000007
1.9785600000000012
2.0037500000000006
2.0250400000000006
2.042370000000001
2.05568
2.0649100000000002
2.0700000000000003
2.07089
2.06752
2.0598299999999994
2.0477599999999994
2.031249999999999
2.010239999999999
1.984669999999999
1.9544799999999984
1.9196099999999983
1.8799999999999981
1.8355899999999976
1.7863199999999972
1.7321299999999973
1.672959999999997
1.6087499999999963
1.539439999999996
1.4649699999999957
1.3852799999999954
1.3003099999999952
1.2099999999999946
1.1142899999999942
1.0131199999999938
0.9064299999999934
0.7941599999999929
0.6762499999999925
0.552639999999992
0.4232699999999916
0.28807999999999107
0.14700999999999054
generated Y points
0.0
0.14701
0.28808
0.42327
0.55264
0.6762500000000001
0.79416
0.90643
1.0131200000000002
1.1142900000000002
1.21
1.3003099999999999
1.3852799999999996
1.4649699999999997
1.5394399999999997
1.6087499999999997
1.6729599999999996
1.7321299999999997
1.78632
1.83559
1.88
1.91961
1.95448
1.98467
2.0102400000000005
2.0312500000000004
2.0477600000000002
2.0598300000000003
2.0675200000000005
2.0708900000000003
2.0700000000000003
2.0649100000000002
2.0556800000000006
2.0423700000000005
2.0250400000000006
2.00375
1.9785599999999997
1.9495300000000002
1.91672
1.8801899999999998
1.8399999999999999
1.7962099999999999
1.748879999999999
1.6980699999999993
1.6438399999999993
1.5862499999999993
1.5253599999999992
1.461229999999999
1.3939199999999987
1.3234899999999983
1.2499999999999982
1.173509999999998
1.094079999999998
1.011769999999998
0.9266399999999977
0.8387499999999977
0.7481599999999973
0.6549299999999975
0.5591199999999971
0.46078999999999715
0.359999999999997
0.2568099999999969
0.15127999999999653
0.043469999999996345
-0.06656000000000395
-0.17875000000000396
-0.2930400000000042
-0.40937000000000445
-0.5276800000000048
-0.6479100000000048
-0.7700000000000049
-0.8938900000000052
-1.0195200000000053
-1.1468300000000053
-1.2757600000000053
-1.4062500000000062
-1.538240000000006
-1.6716700000000062
-1.8064800000000063
-1.9426100000000066
-2.0800000000000067
-2.218590000000007
-2.3583200000000066
-2.499130000000007
-2.6409600000000077
-2.783750000000008
-2.927440000000008
-3.0719700000000083
-3.217280000000008
-3.363310000000008
-3.5100000000000087
-3.6572900000000086
-3.805120000000009
-3.9534300000000084
-4.102160000000009
-4.251250000000009
-4.40064000000001
-4.550270000000009
-4.7000800000000105
-4.85001000000001
Multiply the set of points by some scale factor, then round to an integer. I would suggest the factor Screen Width/MAX(list of x points) for x, and Screen Height/MAX(list of y points) for y. This should give you a list of points scaled to the current size of the screen. Here's some python code that implements the idea.
X = "-5.0 -4.85001 -4.700079999999999 -4.55027 -4.400639999999999 -4.25125 -4.102159999999999 -3.9534299999999996 -3.80512 -3.6572900000000006 -3.5100000000000007 -3.3633100000000002 -3.2172800000000006 -3.07197 -2.92744 -2.7837499999999995 -2.6409599999999993 -2.4991299999999996 -2.3583199999999995 -2.2185899999999994 -2.0799999999999996 -1.9426099999999988 -1.8064799999999992 -1.6716699999999989 -1.5382399999999987 -1.4062499999999998 -1.2757599999999993 -1.1468299999999993 -1.0195199999999995 -0.8938899999999995 -0.7699999999999991 -0.6479099999999991 -0.527679999999999 -0.4093699999999989 -0.29303999999999886 -0.17874999999999885 -0.06655999999999862 0.043470000000001674 0.15128000000000164 0.256810000000002 0.3600000000000019 0.4607900000000018 0.5591200000000022 0.6549300000000019 0.7481600000000019 0.838750000000002 0.9266400000000021 1.011770000000002 1.094080000000002 1.173510000000002 1.2500000000000018 1.3234900000000016 1.3939200000000018 1.4612300000000018 1.5253600000000018 1.5862500000000017 1.6438400000000017 1.6980700000000017 1.7488800000000018 1.7962100000000016 1.8400000000000019 1.8801900000000014 1.916720000000001 1.9495300000000007 1.9785600000000012 2.0037500000000006 2.0250400000000006 2.042370000000001 2.05568 2.0649100000000002 2.0700000000000003 2.07089 2.06752 2.0598299999999994 2.0477599999999994 2.031249999999999 2.010239999999999 1.984669999999999 1.9544799999999984 1.9196099999999983 1.8799999999999981 1.8355899999999976 1.7863199999999972 1.7321299999999973 1.672959999999997 1.6087499999999963 1.539439999999996 1.4649699999999957 1.3852799999999954 1.3003099999999952 1.2099999999999946 1.1142899999999942 1.0131199999999938 0.9064299999999934 0.7941599999999929 0.6762499999999925 0.552639999999992 0.4232699999999916 0.28807999999999107 0.14700999999999054"
X = X.split(" ");
absX = list();
for x in X:
absX.append(abs(float(x)));
max_X = max(absX);
min_X = min(X);
screen_width = 1024;
scale_factor = screen_width/float(max_X + float(max(X)));
newX = list();
for x in X:
x = int(float(x)*scale_factor) + screen_width;
newX.append(x)
print(newX);
This returns the following list of X coordinates:
[300, 322, 344, 366, 387, 409, 430, 452, 473, 495, 516, 537, 559, 580, 601, 621, 642, 663, 683, 703, 723, 743, 763, 782, 802, 821, 840, 858, 877, 895, 913, 931, 948, 965, 982, 999, 1015, 1030, 1045, 1061, 1076, 1090, 1104, 1118, 1132, 1145, 1158, 1170, 1182, 1193, 1205, 1215, 1225, 1235, 1244, 1253, 1262, 1269, 1277, 1284, 1290, 1296, 1301, 1306, 1310, 1314, 1317, 1319, 1321, 1323, 1323, 1323, 1323, 1322, 1320, 1318, 1315, 1311, 1307, 1301, 1296, 1289, 1282, 1274, 1266, 1256, 1246, 1236, 1224, 1212, 1199, 1185, 1170, 1155, 1139, 1121, 1104, 1085, 1065, 1045]
And here's the Y:
[768, 784, 799, 814, 829, 843, 856, 868, 880, 891, 902, 912, 921, 930, 938, 946, 953, 960, 966, 971, 976, 981, 984, 988, 991, 993, 995, 996, 997, 997, 997, 997, 996, 994, 992, 990, 987, 984, 980, 976, 972, 967, 962, 956, 950, 944, 937, 930, 922, 914, 906, 898, 889, 880, 870, 861, 851, 840, 830, 819, 807, 796, 784, 772, 761, 749, 736, 723, 710, 697, 683, 669, 655, 641, 627, 612, 598, 583, 568, 553, 538, 522, 507, 491, 475, 460, 444, 428, 411, 395, 379, 363, 346, 330, 313, 297, 280, 264, 247, 230]
This script isn't perfect and doesn't return values within the correct range, but it should give you an idea as of where to start.
I have three classes and am trying to make a game whereby users move along a grid depending on what is rolled by a die.
I have my main BoardGame class, containing the GUI and the counters which currently are Jlabel images (i'm open to suggestions as to what I could use instead of a JLabel - i wasnt so sure myself). I have a Grid class which I have arranged into a 2D array and called an instance of in the BoardGame class, and I have a die class which rolls a random number from 1-6.
I am trying to get me counters to start at the first square on the grid, and then advance in a left-to-right-right-to-left fashion. I am unsure however of how to make the counters move through the grid in the first place. Hopefully, if I can figure this out, I believe I can then implement them moving a specific amount via the die.
Thanks for the help in advance
GameBoard class:
public class GameBoard extends javax.swing.JFrame {
private JLabel Board;
private JLabel GreenDot;
private JLabel redDot;
private JButton startButton;
private Grid grid;
private Die die;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Grid grid = new Grid();
GameBoard inst = new GameBoard(grid);
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public GameBoard(Grid grid) {
super();
this.grid = grid;
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
{
redDot = new JLabel();
getContentPane().add(redDot);
redDot.setText("jLabel1");
redDot.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/download.png")));
redDot.setBounds(220, 434, 20, 12);
redDot.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false));
}
{
GreenDot = new JLabel();
getContentPane().add(GreenDot);
GreenDot.setText("jLabel1");
GreenDot.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/3d-green-ball-th.png")));
GreenDot.setBounds(222, 453, 21, 13);
GreenDot.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false));
}
{
startButton = new JButton();
getContentPane().add(startButton);
startButton.setText("Start Game");
startButton.setBounds(64, 443, 83, 23);
}
{
Board = new JLabel();
getContentPane().add(Board);
Board.setLayout(null);
Board.setText("jLabel1");
Board.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/board.jpg")));
Board.setBounds(204, -1, 742, 484);
}
pack();
this.setSize(963, 523);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
}
Grid class:
public class Grid {
int[][] multi = {
{ 0, 0,-1, 0, 0,-1, 0,-1, 0, 0},
{ 0, 0, 0, 0, 0, 0,-1, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{ 0,-1, 0,-1, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0,-1, 0, 0, 1},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{ 0, 0, 0,-1, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}
};
}
Die class:
public class Die {
public Die() {
}
public void dieRoll() {
int SIDES = 6;
int roll = (int) (Math.random() * SIDES) + 1;
System.out.println(roll);
}
}
A simple way of doing this would be to change the die class so it has
{
private int sides;
public Die(int numSides){
sides = numSides;
}
public int roll(){
return (int) (Math.random() * SIDES) + 1
}
}
Then you can roll a six sided die like so
//this creates the die
Die sixSides = new Die(6);
//this rolls the die and prints the roll
System.out.print("That roll got you a " + sixSides.roll());
to move along a 2D array, all you need to do is use the modulus and you need to create a point object class
public position move(int num, int x, int y){//input is dice roll int then current position
for(int i = 0; i < num;i++){
if(i%10==0){
y++;
x = 0;
}else{
x++;
}
}
return new point(x,y);
}
To access the x and y positions of the point object you would need to write get and set methods for the object.
something like this
point player1 = new point(0,0);
int xposition = player1.getX
I'm trying to set items from a method called FootballClub and so far it's fine.
but then I created an arrayList from it and I somehow can't find a way to store this information into a JTable.
The problem is that i cant find a way to set a fixed number of rows
Here is my code:
Class StartLeague:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public class startLeague implements LeagueManager{
//setting the frame and other components to appear
public startLeague(){
JButton createTeam = new JButton("Create Team");
JButton deleteTeam = new JButton("Delete Team");
JFrame frame = new JFrame("Premier League System");
JPanel panel = new JPanel();
frame.setSize(1280, 800);
frame.setVisible(true);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
panel.setLayout(new GridLayout(20, 20));
panel.add(createTeam);
panel.add(deleteTeam);
panel.add(new JLabel(""));
//JLabels to fill the space
}
}
FootBall Club Class:
import java.util.ArrayList;
public class FootballClub extends SportsClub{
FootballClub(int position, String name, int points, int wins, int defeats, int draws, int totalMatches, int goalF, int goalA, int goalD){
this.position = position;
this.name = name;
this.points = points;
this.wins = wins;
this.defeats = defeats;
this.draws = draws;
this.totalMatches = totalMatches;
this.goalF = goalF;
this.goalA = goalA;
this.goalD = goalD;
}
The SportsClub Class(abstract):
abstract class SportsClub {
int position;
String name;
int points;
int wins;
int defeats;
int draws;
int totalMatches;
int goalF;
int goalA;
int goalD;
}
And finally, LeagueManager, which is an interface:
import java.util.ArrayList;
public interface LeagueManager {
ArrayList<FootballClub> originalLeagueTable = new ArrayList<FootballClub>();
FootballClub arsenal = new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19);
FootballClub liverpool = new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16);
FootballClub chelsea = new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19);
FootballClub mCity = new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26);
FootballClub everton = new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9);
FootballClub tot = new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1);
FootballClub newcastle = new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1);
FootballClub south = new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5);
}
Can somebody please help me?
I've trying and trying for days.
Thank you.
"The problem is that i cant find a way to set a fixed number of rows"
You don't need to set the number of rows. Use a TableModel. A DefaultTableModel in particular.
String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
DefaultTableModel tableModel = new DefaultTableModel(col, 0);
// The 0 argument is number rows.
JTable table = new JTable(tableModel);
Then you can add rows to the tableModel with an Object[]
Object[] objs = {1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19};
tableModel.addRow(objs);
You can loop to add your Object[] arrays.
Note: JTable does not currently allow instantiation with the input data as an ArrayList. It must be a Vector or an array.
See JTable and DefaultTableModel. Also, How to Use JTable tutorial
"I created an arrayList from it and I somehow can't find a way to store this information into a JTable."
You can do something like this to add the data
ArrayList<FootballClub> originalLeagueList = new ArrayList<FootballClub>();
originalLeagueList.add(new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16));
originalLeagueList.add(new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26));
originalLeagueList.add(new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9));
originalLeagueList.add(new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1));
originalLeagueList.add(new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1));
originalLeagueList.add(new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5));
for (int i = 0; i < originalLeagueList.size(); i++){
int position = originalLeagueList.get(i).getPosition();
String name = originalLeagueList.get(i).getName();
int points = originalLeagueList.get(i).getPoinst();
int wins = originalLeagueList.get(i).getWins();
int defeats = originalLeagueList.get(i).getDefeats();
int draws = originalLeagueList.get(i).getDraws();
int totalMatches = originalLeagueList.get(i).getTotalMathces();
int goalF = originalLeagueList.get(i).getGoalF();
int goalA = originalLeagueList.get(i).getGoalA();
in ttgoalD = originalLeagueList.get(i).getTtgoalD();
Object[] data = {position, name, points, wins, defeats, draws,
totalMatches, goalF, goalA, ttgoalD};
tableModel.add(data);
}
You probably need to use a TableModel (Oracle's tutorial here)
How implements your own TableModel
public class FootballClubTableModel extends AbstractTableModel {
private List<FootballClub> clubs ;
private String[] columns ;
public FootBallClubTableModel(List<FootballClub> aClubList){
super();
clubs = aClubList ;
columns = new String[]{"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
}
// Number of column of your table
public int getColumnCount() {
return columns.length ;
}
// Number of row of your table
public int getRowsCount() {
return clubs.size();
}
// The object to render in a cell
public Object getValueAt(int row, int col) {
FootballClub club = clubs.get(row);
switch(col) {
case 0: return club.getPosition();
// to complete here...
default: return null;
}
}
// Optional, the name of your column
public String getColumnName(int col) {
return columns[col] ;
}
}
You maybe need to override anothers methods of TableModel, depends on what you want to do, but here is the essential methods to understand and implements :)
Use it like this
List<FootballClub> clubs = getFootballClub();
TableModel model = new FootballClubTableModel(clubs);
JTable table = new JTable(model);
Hope it help !
I created an arrayList from it and I somehow can't find a way to store this information into a JTable.
The DefaultTableModel doesn't support displaying custom Objects stored in an ArrayList. You need to create a custom TableModel.
You can check out the Bean Table Model. It is a reusable class that will use reflection to find all the data in your FootballClub class and display in a JTable.
Or, you can extend the Row Table Model found in the above link to make is easier to create your own custom TableModel by implementing a few methods. The JButtomTableModel.java source code give a complete example of how you can do this.
You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the List.
PingScan p = new PingScan();
List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
for (final Future<String> f : scanResult) {
try {
if (f.get() instanceof String) {
String ip = f.get();
Object[] data = {ip};
tableModel.addRow(data);
}
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
}
}
Basic method for beginners like me.
public void loadDataToJtable(ArrayList<String> liste){
rows = table.getRowCount();
cols = table.getColumnCount();
for (int i = 0; i < rows ; i++) {
for ( int k = 0; k < cols ; k++) {
for (int h = 0; h < list1.size(); h++) {
String b = list1.get(h);
b = table.getValueAt(i, k).toString();
}
}
}
}