NoSuchField error in Java code with two classes - java

I have the following code:
public class Table {
Table2[] data = new Table2[2000];
public Table() {
for (int i = 0; i < data.length; i++) {
data[i] = new Table2();
}
}
}
And:
public class Table2 {
Integer[] data;
public Table2() {
data = new Integer[100];
}
Im having problems accessing Table.data[0].data[0]
Table.data[0].data[0] is not null.
The program works in Eclipse but outside of Eclipse i get a NoSuchField error. Im not sure how to fix this.

You must be doing some typo/mistake in your code accessing it. If you do it as follows, no matter where (eclipse or outside) you are accessing it, the result will be same.
public class Main {
public static void main(String[] args){
Table table=new Table();
table.data[0].data[0]=10;
System.out.println(table.data[0].data[0]);
}
}
Output:
10

Related

i have one method (example: Read() ) in one JFrame , now i want to use the same method in new JFrame (say example: JFrame2). How can I do that?

Dataset.java
package base_project;
import ....
public class Dataset extends javax.swing.JFrame {
public Dataset() {
initComponents();
addRowToJTable();
}
static ArrayList<a> ar = new ArrayList<a>();
public void Read()
{
}
public void addRowToJTable()
{
DefaultTableModel model = (DefaultTableModel) jTableDataset.getModel();
Read();
String Data[][]=new String[ar.size()][12];
for (int i=0;i<ar.size();i++)
{ }
}
private void jButtonDSNextActionPerformed(java.awt.event.ActionEvent evt) {
Classification c = new Classification();
c.setVisible(true);
this.setVisible(false);
}
public static void main(String args[]) {
}
This is my first JFrame form which is named as Dataset.java . In this file i have used Read() method. This file contains one buttton which leads to next JFrame called Classification. The code of Classification.java is as follows:
Classification.java
package base_project;
import ....
public class Classification extends javax.swing.JFrame {
public Classification() {
initComponents();
addRowToJTable();
}
static ArrayList<a> ar = new ArrayList<a>();
static ArrayList<q> aq = new ArrayList<q>();
static ArrayList<s> as = new ArrayList<s>();
public static void Read()
{}
public static void Set_Q()
{}
public static void Set_s()
{}
public void addRowToJTable()
{
DefaultTableModel modelQID = (DefaultTableModel) jTableQID.getModel();
DefaultTableModel modelSA = (DefaultTableModel) jTableSA.getModel();
Read();
Set_Q();
Set_s();
String DataQ[][]=new String[aq.size()][6];
for (int i=0;i<aq.size();i++)
{
}
String DataS[][]=new String[as.size()][6];
for (int i=0;i<as.size();i++)
{
}
}
public static void main(String args[]) {
}
This runs fine. But the problem is that i have to again write the whole Read() method in this Classification.java also. So eachtime whenever i want to use that method i have to again write it in every new JFrame , which i don't want. So what can i do to avoid that?
I'm no expert in java so please bear with me. I've tried looking through the java docs and on this site but cannot seem to find a solution to my problem.
THANKS in advance.
Theres a few things that are a little confusing, as followd:
Firstly, there should only ever be one public static void main(String args[]) {} method because this is the start of the program which there can only ever be one.
Secondly, when a class extends another class it shares all of the methods in the super class. This is what you are doing when you go "Classification extends JFrame" and "Dataset extends JFrame" both classes now technically have the same methods, plus whatever you add on top in each class.
Therefore, one of the key OOP principals is that if two classes share the exact same code, you put that code in the super class. In this case both classes extend JFrame, but you cannot edit JFrame as it is part of the existing Java API. Therefore, to make the read() method common between both files, you should create a wrapper such as (AbstractReadFrame.java):
public abstract class AbstractReadFrame extends JFrame {
// AbstractReadFrame shares all methods within JFrame
public void read() {
// code for reading, this is shared between all classes which extends AbstractReadFrame
}
// other common code
}
public class Classification extends AbstractReadFrame {
// shares all methods within AbstractReadRame and JFrame
public void addRowToJTable() {
DefaultTableModel modelQID = (DefaultTableModel) jTableQID.getModel();
DefaultTableModel modelSA = (DefaultTableModel) jTableSA.getModel();
Read();// calls read() in AbstractReadFrame
Set_Q();
Set_s();
String DataQ[][] = new String[aq.size()][6];
for (int i = 0; i < aq.size(); i++) {
}
String DataS[][] = new String[as.size()][6];
for (int i = 0; i < as.size(); i++) {
}
}
// other code
}
public class Dataset extends AbstractReadFrame {
// shares all methods within AbstractReadRame and JFrame
public void addRowToJTable() {
DefaultTableModel model = (DefaultTableModel) jTableDataset.getModel();
Read(); // calls read() in AbstractReadFrame
String Data[][] = new String[ar.size()][12];
for (int i = 0; i < ar.size(); i++) {
}
}
// other code
}
However, in classification.java you have declared read() to be static which means it will not be work with in the way i have mentioned above. I'd recommend reading about inheritance in Java (such as https://www.tutorialspoint.com/java/java_inheritance.htm)
as this will help you a lot with structuring your program.
By having the super class hold all common code, you only have to write it once and run it whenever you wish.

Adding custom class objects to list showing ambiguity

This is a sample test code I wrote to ensure what I know is right
class Form {
List<Sample> samples;
List<Sample> sampleList;
public List<Sample> getSamples() {
return samples;
}
public void setSamples(List<Sample> samples) {
this.samples = samples;
}
public List<Sample> getSampleList() {
return sampleList;
}
public void setSampleList(List<Sample> sampleList) {
this.sampleList = sampleList;
}
void setInitialData() {
this.samples = new ArrayList<Sample>();
this.sampleList = new ArrayList<Sample>();
}
}
class Sample {
}
public class ListAddingAmbiguity {
public static void main(String[] args) {
Form form = new Form();
form.setInitialData();
Sample sample = new Sample();
form.getSamples().add(sample);
form.getSampleList().add(sample);
System.out.println(form.getSamples().size());
System.out.println(form.getSampleList().size());
}
}
The output coming is
1
1
And it is correct, samples and sampleList are two different references pointing to two different memory locations, so adding to samples won't change the size of sampleList.
But in my project code it is different, this is my Form class
public class InvoiceForm extends BaseActionForm {
private List<ProductTO> products;
private List<ProductTO> productList;
// getters and setters
}
This is the code in my Action class
private void setProductsToInvoice(InvoiceForm invoiceForm) throws Exception {
if(invoiceForm.getProducts() != null && !invoiceForm.getProducts().isEmpty()){
ProductTO productTO = new ProductTO();//ProductEntryHandler.getInstance().prepareProductsForInvoice();
invoiceForm.getProducts().add(productTO);
invoiceForm.getProductList().add(productTO);
}else {
List<ProductTO> productTOs = new ArrayList<ProductTO>();
productTOs.add(ProductEntryHandler.getInstance().prepareProductsForInvoice());
invoiceForm.setProducts(productTOs);
invoiceForm.setProductList(productTOs);
}
}
Both the products and productList are having a size of 1 initially, so in the above code if block will execute. The commented portion is the earlier code. Even if it is the new code ProductTO productTO = new ProductTO(); or the old code ProductTO productTO = ProductEntryHandler.getInstance().prepareProductsForInvoice(); the problem is the same.
Like I said when execution comes to the method both the lists are having a size of 1. When the line invoiceForm.getProducts().add(productTO); is executed the size of products and productList size becomes 2, which is in conflict with my test code. Now when the nest line invoiceForm.getProductList().add(productTO); is executed both the list size is becoming 3. I don't know why its happening, can anybody help?
The following code else case in setProductsToInvoice set both products and productList to the same list:
List<ProductTO> productTOs = new ArrayList<ProductTO>();
productTOs.add(ProductEntryHandler.getInstance().prepareProductsForInvoice());
invoiceForm.setProducts(productTOs);
invoiceForm.setProductList(productTOs);
The correct way, or at least the less incorrect way, is something like this:
ProductTO newProd =
ProductEntryHandler.getInstance().prepareProductsForInvoice());
invoiceForm.setProducts(new ArrayList<ProductTO>());
invoiceForm.getProducts().add(newProd);
invoiceForm.setProductList(new ArrayList<ProductTO>());
invoiceForm.getProductList().add(newProd);
I'd suggest an investigation to determine why there are two lists apparently being maintained in parallel in the first place. At first glance, it has a bit of a smell to it...

java : Identifier expected error when calling a void method from another class

So I've been trying to create a set of cards by defining them through their value then create one class per color. I have a method for creating a list of 13 cards from 2 to ace:
package test;
import java.util.*;
public class Cartes {
void liste_cartes(){
ArrayList liste_cartes = new ArrayList();
for(int i=2; i<15; i++) {
liste_cartes.add(i);
}
}
}
I've tried using this method in my color class !
package test;
import java.util.*;
public class Coeur {
Cartes cartes = new Cartes();
cartes.liste_cartes();
}
However I'm getting an <identifier expected> error on cartes.liste_cartes();. Relatively new to Java here, so any help is much appreciated.
For Java program,JVM first looks for main() to run the program. Try writing this:-
public class Coeur {
public static void main(String[] args) {
Cartes cartes = new Cartes();
cartes.liste_cartes();
}
}
Wrap cartes.liste_cartes(); in a method, like
public void dummyMethod(){ //should probably be your main method, if in your main class
cartes.liste_cartes();
}
Also, your ArrayList is of raw type. Make use of generics.
ArrayList<Integer> liste_cartes = new ArrayList<Integer>();

How do I correctly instantiate a public class+data structure in a class so that other objects can use it?

In my code, I have a seperate Runner class that instantiates a World, which has a 4x4 array of Locations (a separate class) stored as a Location[][] array. When I print/try to use the Location array, its value is null, and it throws a NullPointerException.
public class Runner
{
public static void main(String[] args)
{
...
WumpusWorld test_loc = new WumpusWorld();
System.out.print(test_loc) //This prints an ID for the WumpusWorld object
System.out.print(test_loc.world) //Null value prints here
//I'd like to pass the test_loc.world values to an actor here
...
}
}
The applicable code for the WumpusWorld is as follows:
public class WumpusWorld
{
public Location[][] world;
public WumpusWorld()
{
new WumpusWorld((byte) 4); //this constructor is used
}
...
public WumpusWorld(byte size)
{
this.world = new Location[size][size];
for(byte i = 0; i<size; i++)
{
for(byte j = 0;j<size;j++)
{
world[i][j] = new Location(j,i,true,false,false);
}
//Location instances called in the form world[x][y]
//are error free in constructor
...
}
}
Your problem might be in the way you call public WumpusWorld(byte size) from the default constructor.
Try this:
public WumpusWorld()
{
this((byte) 4);
}
With new in the call, I had uninitialized values in the inner class

Access a List in JUnit Test Case

I have this ParkingLot.java
public class ParkingLot {
private final int size;
private Car[] slots = null;
List<String> list = new ArrayList<String>();
public ParkingLot(int size) {
this.size = size;
this.slots = new Car[size];
}
public List licenseWithAParticularColour(String colour) {
for (int i = 0; i < slots.length; i++) {
if (slots[i].getColour() == colour) {
System.out.println(slots[i].getLicense());
list.add(slots[i].getLicense());
return list;
}
}
return null;
}
}
I have created a ParkingLotTest.java as follows
public class ParkingLotTest {
private Car car1;
private Car car2;
private Car car3;
private Ticket ticket1;
private Ticket ticket2;
private Ticket ticket3;
private ParkingLot parkingLot;
private List<String> list = new ArrayList<String>();
#Before
public void intializeTestEnvironment() throws Exception {
this.car1 = new Car("1234", "White");
this.car2 = new Car("4567", "Black");
this.car3 = new Car("0000", "Red");
this.parkingLot = new ParkingLot(2);
this.ticket1 = parkingLot.park(car1);
this.ticket2 = parkingLot.park(car2);
this.ticket3 = parkingLot.park(car3);
this.list = parkingLot.list;
}
#Test
public void shouldGetLicensesWithAParticularColour() throws Exception {
assertEquals(, parkingLot.licenseWithAParticularColour("White"));
}
}
In the above Test Case, I want to check that the List is filled with the correct Licenses.
1. How do i create a field in the ParkingLotTest.java so that the List in the first class is same as list in the second class file.
First, I don't think you need a list on ParkingLot so your question actually doesn't make much sense :)
Second, just set up the expected result in each test method:
public class ParkingLotTest {
//...
#Test
public void shouldGetLicensesWithAParticularColour() throws Exception {
List<Car> expected = new ArrayList<Car>();
expected.add(...);
assertEquals(expected, parkingLot.licenseWithAParticularColour("White"));
}
}
And don't forget to also test unexpected values or special cases. For example:
#Test
public void shouldNotGetLicensesWithANullColour() throws Exception {
...
assertEquals(expected, parkingLot.licenseWithAParticularColour(null));
}
#Test
public void shouldNotGetLicensesWithAnUnknownColour() throws Exception {
...
assertEquals(expected, parkingLot.licenseWithAParticularColour("unknown"));
}
Some additional remarks:
I wouldn't use a Car[] for the slots but a List<Car>.
You don't really need the List<String> list in ParkingLot (and the current implementation of licenseWithAParticularColour is buggy).
I would use an Enum for the color.
However you want?
That's somewhat in jest, but however you normally build a List will do just fine - as long as it's consistent with what you want your tested interface list to be.
For this particular case, I'd recommend building a List<Car> as your test reference, then visiting each Car and parking it. You can then build the licenses list from that reference list, and compare it to the parking lot one. Just make sure your iteration direction is correct.
BTW, from what I see, I don't think things work the way they're supposed to work - good thing you're testing it.
Pascal's Answer worked for me.
#Pascal Again, I made this function:
public List getSlotNumbersWithAParticularColour(String colour) {
List<Integer> listOfTicketsWithAColour = new ArrayList<Integer>();
for (int i = 0; i < slots.length;) {
if (slots[i].getColour() == colour) {
listOfTicketsWithAColour.add(i);
}
return listOfTicketsWithAColour;
}
return null;
}
The fault is not in the for loop, adding an i++ is "dead-code" acc to Eclipse. Adding the i++ doesnt cause any difference.
And the corresponding test-case:
public void getSlotNumbersWithAGivenColour() throws Exception {
List<String> expected = new ArrayList<String>();
expected.add("0");
expected.add("3");
assertEquals(expected, parkingLot.getSlotNumbersWithAParticularColour("White"));
}
The test fails. The function only returns 0, instead of 0,3. Any idea why?

Categories