JAVA - can't call my array method - java

Eclipse says: 'chiffres cannot be resolved to a variable', how to fix the call method ?
public class Table {
public static void main(String[] args) {
Tableau1 table = new Tableau1();
table.CreerTable();
table.AfficherTable(chiffres);
}}
part:
and class Tableau1 with array: to declare it
public class Tableau1 {
int [][] chiffres;
int nombre;
public void CreerTable(){
int[][] chiffres= {{11,01,3},
{12,02,4},
{12,03,5}};
//edited
this.chiffres=chiffres;
}
public int[][] AfficherTable(int[][] chiffres){
this.nombre=12;
for(int i=0;i<2;i++){
System.out.println("essai"+chiffres[i][1]);
if(chiffres[i][0]==nombre){System.out.println("ma ligne ="+chiffres[i][0]+","+chiffres[i][1]+","+chiffres[i][2]);
};
}
return chiffres;
}
}
Thanks a lot

You have 3 problems here.
Problem 1 :
1) You method AfficherTable(chiffres) need not to pass an argument, since it is an instance member.
You can simply call
table.AfficherTable();
That solves your problem.
Before doing that problem no 2
Problem 2:
2) You delcared chifferes as a instance member int [][] chiffres;
and you are initializing it's in constructor
public void CreerTable(){
int[][] chiffres= {{11,01,3},
{12,02,4},
{12,03,5}};
}
But if you closely look, you are creating new array again. That won't work, since you are creating new array and forgot your instance member.
Change your constructor to
public void CreerTable(){
chiffres= new int[3][3] {{11,01,3},
{12,02,4},
{12,03,5}};
}
Problem 3 :
After changing that constructor, since you are using it in the same class member, you need not to receive it. Hence you change your method declaration as
public int[][] AfficherTable(){
You'll be fine I guess now.

table.CreerTable();
table.AfficherTable(chiffres);
By resolving chiffres it searches in the Class Table as you don't specify that chiffres comes from Tableau1.
Therefore the solution is:
table.CreerTable();
table.AfficherTable(table.chiffres);

chiffers is neither a local variable of the main method, nor a field of the class Table, that's why the error.

Related

How to intialise objects in the array list

I am trying to initialize objects in my ArrayList
The following is my code and what it does is that it receives an ArrayList, already defined in the main method. However, it is not executing the readInput method in the code below. readInput is a method declared in another class called customer that takes in keyboard input from the user. Its a complete class BTW. I believe that there is no object in the ArrayList at the moment as i have run some test to see whats the problem. Im new to using Arraylist. Therefoere i am unsure of how to solve this proble.
What custs.set(i, new customer()); does is actually to initialize the object in index.
public static void freeCustomer(ArrayList<customer> custs,
ArrayList<supplement>supps)
{
for(int i=0;i<custs.size();i++)
{
custs.set(i, new customer());
custs.get(i).readInput();
for(int s=0;s<supps.size();s++)
{
supps.set(s, new supplement());
supps.get(s).readInput();
}
}
}
If I understood right,you want to add user input from a customer method.I would use add method.I just made a fast example of add method.From here you can expand to loops,etc.
public static void freeCustomer(ArrayList<customer> custo,customer c)
{
custo.add(new customer(c.readInput()));
}
public static void main(String[] args) {
ArrayList<customer> custo = new ArrayList<customer>();
customer c=new customer("");
freeCustomer(custo,c);
}
}

Java ArrayList a good way to access same list from many classes

Hello i am trying to familiarize myself with Java by doing a very simple "bankaccount" application and it doesn't even save to db or something so it resets all data on rerun.
The problem i am trying to find a good way of doing is that i have an ArrayList of accounts that i want to be able to access from any class so that during runtime for example after an deposit if i access that account later when i want to get balance i get an that account from the ArrayList and it is updated to the deposit value.
When googling i found this solution but i dont like it since it uses static ArrayList. is there any more elegant way than this for an applicaiton that only saves the state/data during runtime.
Simple class that adds the test accounts and so on where first value is acountId and second is balance
public class AccountsModel {
private ArrayList<AccountModel> listOfAccounts;
public AccountsModel() {
listOfAccounts = new ArrayList<AccountModel>();
listOfAccounts.add(new AccountModel(1,0));
listOfAccounts.add(new AccountModel(2,0));
listOfAccounts.add(new AccountModel(3,0));
listOfAccounts.add(new AccountModel(4,0));
}
public ArrayList<AccountModel> getListOfAccounts(){
return listOfAccounts;
}
}
Then in my main class i just do this
static AccountsModel accounts = new AccountsModel();
public static ArrayList<AccountModel> listOfAccounts = accounts.getListOfAccounts();
this "works" as i can get the same list from anywhere within the application. But is there any simple and elegant way of doing this some other way?
You said you dislike the static solution but to me "It needs to be accessed by many classes" screams static variables.
Basically, you create a wrapper for your ArrayList which carries out operations:
class AccountsModel {
private static ArrayList<AccountModel> singleton;
// a static constructor also wouldn't be a bad idea here
public static void init() {
/* add a bunch of AccountModels here*/
}
public static ArrayList<AccountModel> getAccounts() {
return singleton;
}
}
An example of a main method:
public static void main(String[] args) {
ArrayList<AccountModel> accounts = AccountModels.getAccounts();
}

get method returns null array when invoked form anther class . It results nullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting NullPointerException when I try to access array elements from another class using the get method. My code uses a constructor to initialize the array, and it works just fine.
MagazineValue.class
public class MagazineValue {
public MagazineValue(){
}
private String[]magazineName;
public MagazineValue(String[] magazineName){
this.magazineName = new String[magazineName.length];
System.arraycopy(magazineName, 0, this.magazineName, 0,
magazineName.length);
}
public String[] getMagazineName(){
return magazineName;
}
}
The constructor here copy's array value from the argument to a private array variable.
When I try to invoke getMagazineName() from another class, it shows that the array is still null. Is there any way I can solve this? It sure seems easy but it took me a lot of time.
FirebaseValueListner.class
public class FirebaseValueListner {
public void setMagazineName(){
String[]magazineName={"African Daily" , "African Bussines", "African Women"};
MagazineValue setValue= new MagazineValue(magazineName);
}
}
The FirebaseValueListner gets values from the Firebase database and saves it values to an ArrayList and later copy's the values to arrays.
The arrays are passed to the constructor of the MagazineValues.
LibraryFragment.class `
public class LibraryFragment {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[]magazineName;
MagazineValue getMagazineName;
getMagazineName=new MagazineValue();
magazineName=getMagazineName.getMagazineName();
System.out.println("Magazine Name : " +magazineName[1]);
}
}
`
You must have defined a constructor with no arguments. Because you write getValue = new MagazineValue(); It may not initialize the field magazineName.

I'm not sure why a variable is inaccessible

I'm writing a small program that creates a gui to display the contents of a csv file. I've tried following the outline from the Oracle website (http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data), but my problem is that the 'getColumnCount' method that is used to build the table can't access the 'headers' variable. Or more likely, it can, but the changes I thought I made to it in the main method did not connect to it. If anyone can shed some light on what's wrong and how to fix it, it'd be much appreciated.
public class MyTableModel implements TableModel {
private String[] headers; //This line.
private Object[][] tableData;
public static void main(String[] args) {
String fileName = "products.csv";
String[] csvList = readCSV(fileName);
String[] headers = Arrays.copyOfRange(csvList, 0, 10); //Or maybe this line isn't changing the one above.
}
private static String[] readCSV(String file) {
//Some code to fill the list.
return fileString;
}
#Override
public int getColumnCount() {
return headers.length; //<<This line of code
}
}
#Hovercraft Full Of Eels
Oh, I should have mentioned. I'm implementing this class like this, which is to say, I'm calling it from elsewhere.
private static void createGUI() {
csvTabler table = new csvTabler();
table.setTitle("CSV Table");
table.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table.createJTable();
table.pack();
table.setVisible(true);
}
private void createJTable() {
jTable = new JTable(new MyTableModel());
}
I'm sure this affects your solution but I'm not sure how to adjust..
String[] headers = Arrays.copyOfRange(csvList, 0, 10); //Or maybe this line isn't changing the one above.
Yep, that's it in a nutshell .... you're trying to change an instance field from a static method and are also shadowing the variable to boot, and that just won't work. Understand that the headers variable declared within the main method is local to this method -- visible only within the method -- and so changes to it will have absolutely no effect on the headers instance field in the class. Instead create a constructor and pass the header data in when you need to pass it into the class.
A bad idea is to make headers static -- just don't do this as this throws out the OOPs baby with the bathwater, essentially fixing your problem with a kludge rather than making a much cleaner more fundamental improvement to your program.
For example:
public class MyTableModel implements TableModel {
private String[] headers; //This line.
private Object[][] tableData;
public MyTableModel(String[] headers, Object[][] tableData) {
this.headers = headers;
this.tableData = tableData;
}
#Override
public int getColumnCount() {
return headers.length; //<<This line of code
}
public static void main(String[] args) {
String fileName = "products.csv";
String[] csvList = readCSV(fileName);
String[] headers = Arrays.copyOfRange(csvList, 0, 10);
Object[][] tableData = ..MyTableModel.. // code to create this
// now create a table model with your data and use it.
MyTableModel myTableModel = new MyTableModel(headers, tableData);
}
private static String[] readCSV(String file) {
String fileString = "";
//Some code to fill the list.
return fileString;
}
}
Other issues: You should almost never implement TableModel but rather extend either DefaultTableModel or AbstractTableModel. Otherwise your model will miss most of the necessary machinery to make it work.
Regarding:
What if I made the instance field static as well? But assuming that no such easy option exists. Do I do away with my main() method? I suspected that a constructor would be better, but the main method was helpful for testing at first, and I was getting a lot of errors with the constructor I tried to build.
Again, avoid statics as this increases connectedness of your code, its "coupling" without benefit which greatly increases your risk of hard to find bugs as your program grows.
Regarding, "do I do away with my main method" -- but of course your program will need a main method somewhere, so you already know the answer to this. The main method should be small and should serve only to set the pieces of the application in motion, and nothing more.
regarding "I suspected that a constructor would be better, but the main method was helpful for testing at first, and I was getting a lot of errors with the constructor I tried to build." -- a constructor is necessary, the main method and the constructor are no mutually exclusive, and as for errors -- fix them, one at a time.

ArrayStoreException: null while casting List to Array

This may sound silly, but, I get this error while casting from List to Array:
ArrayStoreException: null
The code that i am using right now is :
public void onSuccess(List<Agent> resultList) {
Agent[] array = new Agent[resultList.size()];
resultList.toArray(array);
Agent its a class that i have defined with their own field definitions, being all of them private final Strings
But i dont know what i could be missing atm.
Thank you in advance for your help.
Kind regards,
You're probably passing your ArrayList<Agent> to some method which
has just an ArrayList or List parameter (untyped). This method
can pass compilation but mess things up at runtime. Example below.
If you comment out the call to messUp in my example things are OK.
But messUp can add things which are not Agents to your list,
and cause problems this way.
This is my best guess without seeing your code.
Hope it helps.
import java.util.ArrayList;
import java.util.List;
public class Test009 {
public static void main(String[] args) {
List<Agent> resultList = new ArrayList<Agent>();
resultList.add(null);
resultList.add(new Agent1());
resultList.add(new Agent());
messUp(resultList);
test(resultList);
}
private static void messUp(List lst){
lst.add("123");
}
public static void test(List<Agent> resultList){
Agent[] array = new Agent[resultList.size()];
resultList.toArray(array);
System.out.println("done");
}
}
class Agent {
protected int x;
}
class Agent1 extends Agent{
protected int y;
}
Additional Note: OK, well, this doesn't explain
the "null" part of your error message.
So the root cause is somewhat different.

Categories