I am a novice Java programmer trying to use classes defined in a different file. So, I've written these two .java files:
First, there's MyLibrary.java:
package mymainprogram;
public class MyLibrary {
public class MyRecord {
int number;
char letter;
}
public static int TriplePlusThree(int input_number) {
return ((input_number*3) + 3);
}
}
Then, MyMainProgram.java:
package mymainprogram;
import java.util.Scanner;
public class MyMainProgram {
public static void main(String[] args) {
Scanner keyread = new Scanner(System.in);
System.out.print("Enter Number to Process: ");
int num = keyread.nextInt();
int result = MyLibrary.TriplePlusThree(num);
System.out.println("3x + 3 = "+result);
String letters = "ABCDEFGHIJ";
MyLibrary.MyRecord[] TenRecs = new MyLibrary.MyRecord[10];
for (int i = 0; i < 10; i++) {
TenRecs[i].number = i; //NullPointerException here
TenRecs[i].letter = letters.charAt(i);
}
}
}
I had no problem getting the method to work just fine; now my goal is to create an array where each member of the array has an integer and character. (Note: I'm not looking for better ways to accomplish this objective; I'm merely using this trivial example to try to get this working).
When I tried to run my program, I got:
java.lang.NullPointerException
I researched this, and found this page, which says:
If we try to access the objects even before creating them, run time errors would occur. For instance, the following statement throws a NullPointerException during runtime which indicates that [this array] isn't yet pointing to [an] object. The objects have to be instantiated using the constructor of the class and their references should be assigned to the array elements in the following way.
studentArray[0] = new Student();
So, I tried to do that in my Main Program:
MyRecordArray[0] = new MyLibrary.MyRecord();
but that gives this error:
an enclosing instance that contains MyLibrary.MyRecord is required
That error message led me to this Stack Exchange question, which says:
you have to create an object of X class (outer class) and then use objX.new InnerClass() syntax to create an object of Y class.
X x = new X();
X.Y y = x.new Y();
So, in accordance with that answer, I've added these two lines to my program:
MyLibrary mylibrary = new MyLibrary();
MyLibrary.MyRecord myrecord = mylibrary.new MyRecord();
Those lines don't give any warnings or compilation errors, so I feel like I'm one step closer, but I'm still trying to figure out how to make an array. I know if I wanted to make an array of integers, I would simply do this:
int[] TenInts = new int[10];
So, I've tried things like:
myrecord[] TenRecs = new myrecord[10];
MyRecord[] TenRecs = new MyRecord[10];
But nothing is working, and I feel like I'm grasping at straws now. I get the feeling that the right set of eyes could solve this pretty quickly.
You need to declare the inner class as static.
You can modify the code as follows to suit your requirements:
This is the code for MyLibrary
public class MyLibrary {
public static class MyRecord{
int number;
char letter;
public MyRecord(){
number = 0;
letter = '\0';
}
public MyRecord(int number, char letter){
this.number = number;
this.letter = letter;
}
}
public static int TriplePlusThree(int input_number){
return (input_number * 3 + 3);
}
}
This is the code for the MyMainProgram
import java.util.Scanner;
public class MyMainProgram {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter number to process");
int num = in.nextInt();
System.out.println("3x + 3 = " + MyLibrary.TriplePlusThree(num));
String letters = "ABCDEFGHIJ";
MyLibrary.MyRecord[] TenRecords = new MyLibrary.MyRecord[2];
for (int i=0; i<TenRecords.length; i++){
TenRecords[i] = new MyLibrary.MyRecord();
TenRecords[i].number = i;
TenRecords[i].letter = letters.charAt(i);
}
// Printing class records
for (int i=0; i<TenRecords.length; i++){
System.out.println("Printing records of record " + i + " : ");
System.out.println("Number : " + TenRecords[i].number);
System.out.println("Letter : " + TenRecords[i].letter);
}
in.close();
}
}
You can create the instance of the inner class as follows:
TenRecords[i] = new MyLibrary.MyRecord();
Hope this helps.
The nested class MyRecord contains a hidden reference to the outer class MyLibrary and therefore must be associated with an instance of MyLibrary. This way MyRecord can access private members of MyLibrary.
MyLibrary.MyRecord myrecord = mylibrary.new MyRecord();
Wow, this is funny syntax. In all my years of java programming, I never used such a construct. Typically, you would create objects of inner classes (MyRecord) within the outer class (MyLibrary). Another common thing is to declare the inner class as static which would eliminate the need for an instance of the outer class.
MyRecord[] TenRecs = new MyRecord[10];
This will create an array where all the elements are NULL. You have to initialize each of them (e.g. with a loop).
If you initialize MyRecord[10] the array has null objects. You still have to initialize each element in the array to a new MyRecord object. Otherwise you will get the NPE.
one way to do is : List<MyRecord> TenRecs = new ArrayList<MyRecord>();
TenRecs.add( new MyRecord() );
or for ( int i = 0; i < 10; i++ ) TenRecs[i] = new MyRecord();
also if you add an import statement : import mymainpackage.MyLibrary.MyRecord; You don't need to do mylibrary.new MyRecord(); just do new MyRecord();
You have to create each object in array before initialize. Refer to this link.
Create each object like this.
MyLibrary outer = new MyLibrary();
TenRecs[i] = outer.new MyRecord();
Full code:
MyLibrary.MyRecord[] TenRecs = new MyLibrary.MyRecord[10];
for (int i = 0; i < 10; i++) {
MyLibrary outer = new MyLibrary();
TenRecs[i] = outer.new MyRecord();
TenRecs[i].number = i;
TenRecs[i].letter = letters.charAt(i);
}
There are several points you need to note.
First, difference between a instance inner class and a static inner class.
An instance inner class, declared without static modifier,
public class OutterClass {
public class InstanceInnerClass {}
}
should be created like this:
OutterClass outter = new OutterClass();
InstanceInnerClass iInner = outter.new InstanceInnerClass();
while a static inner class, declared with static modifier,
public class OutterClass {
public static class StaticInnerClass {}
}
should be created like this:
StaticInnerClass sInner = new OutterClass.StaticInnerClass();
Secondly, you accessed an array entry before it is filled
MyLibrary library = new MyLibrary();
MyLibrary.MyRecord[] TenRecs = new MyLibrary.MyRecord[10];
for (int i = 0; i < 10; i++) {
// Create new instance
TenRecs[i] = library.new MyRecord();
TenRecs[i].number = i;
TenRecs[i].letter = letters.charAt(i);
}
Related
I'm very new to programming.
I have a main class and another class, myClass.
When I run the program there is an error in the main class.
It is supposed to be an array of objects and the loop is supposed to set/change/declare things for each object.
Code from the main class:
myClass[] myObj= new myClass[100];
for(int i = 0; i<amount;i++){
myObj[i].setF(sc.next());
myObj[i].setG(sc.next());
myObj[i].myMethod[0]=sc.nextInt();
myObj[i].myMethod[1]=sc.nextInt();
myObj[i].myMethod[2]=sc.nextInt();
}
error says line says "Java returned: 1" and the links redirect me to: <java classname="#{classname}" dir="${work.dir}" failonerror="${java.failonerror}" fork="true" jvm="${platform.java}">
In the myObj class there are no issues, and from what I can tell trough testing it, the error is specifically coming from myObj[i].
I can't figure out how to fix it though.
You're not initializing your array elements before using them. You would need to define a constructor for your class like this(Note that Java class names should always start with uppercase):
// With your current approach you would at least need to allocate memory for member array
public MyClass() {
this.myMethod = new int[3];
}
or
// You can also use a constructor like this
public MyClass(String f, String g, int[] methodArr) {
this.f = f;
this.g = g;
this.myMethod = methodArr;
}
Then you should be able to call it from your driver method like this:
Using No argument constructor:
for (int i = 0; i < amount; i++) {
myObj[i] = new MyClass();
myObj[i].setF(sc.next());
myObj[i].setG(sc.next());
myObj[i].myMethod[0] = sc.nextInt();
myObj[i].myMethod[1] = sc.nextInt();
myObj[i].myMethod[2] = sc.nextInt();
}
Using argument constructor:
for (int i = 0; i < amount; i++) {
int[] myMethodArr = new int[3];
String fInput = sc.next();
String gInput = sc.next();
myMethodArr[0] = sc.nextInt();
myMethodArr[1] = sc.nextInt();
myMethodArr[2] = sc.nextInt();
myObj[i] = new MyClass(fInput, gInput, myMethodArr);
}
In Java when you create an array, you are only creating an array of references. This means that your object instances are not automatically there.
The effect of this fact is that you have to create your array first, and then populate it with references to objects, which you also have to create. Here is how to do that:
myClass[] myObj= new myClass[100];
for(int i = 0; i<amount;i++){
myObj[i] = new myClass(); // here you populate the array with instances
myObj[i].setF(sc.next());
myObj[i].setG(sc.next());
myObj[i].myMethod[0]=sc.nextInt();
myObj[i].myMethod[1]=sc.nextInt();
myObj[i].myMethod[2]=sc.nextInt();
}
So, I'm trying to practice my java skills by applying it to some math homework and making a frequency distribution chart using inheritance. In my head, I envision it as a frequency distribution (parent class = FreqDist) that can have multiple "MyStatClasses" (in the form of the MyStatClass array). Each FreqDist has variables that span across all MyStatClasses which is why I put them in the parent class. However, when I call the MyStatClass constructor, my program gets a StackOverflowError. I think this is because the super(s, i) line calls back to the FreqDist constructor and starts over, causing an infinite loop. Assuming this is the case, how would I fix this?
Ideally, I'd like to access my MyStatClass array and grab values that only apply to that MyStatClass, but I cannot get it to work.
public class FreqDist {
private MyStatClass[] freqClasses;
private double[] dblValuesArray;
private int intNumberOfClasses;
private double dblMax;
private double dblMin;
private int intClassWidth;
public FreqDist(String strValues, int intNumOfClasses) {
System.out.println("This is the beginning of the FreqDist constructor...");
dblValuesArray = getDoubleValues(strValues);
intNumberOfClasses = intNumOfClasses;
dblMin = dblValuesArray[0];
dblMax = dblValuesArray[dblValuesArray.length - 1];
intClassWidth = (int)Math.ceil((dblMax - dblMin) / intNumberOfClasses);
freqClasses = new MyStatClass[intNumberOfClasses];
for (int x = 0; x < freqClasses.length; x++) {
freqClasses[x] = new MyStatClass(strValues, intNumOfClasses);
}
}
public double[] getDoubleValues(String strValues) {
String[] strValuesArray = strValues.trim().split(" ");
dblValuesArray = new double[strValuesArray.length];
for (int x = 0; x < strValuesArray.length; x++) {
dblValuesArray[x] = Double.parseDouble(strValuesArray[x]);
}
Arrays.sort(dblValuesArray);
return dblValuesArray;
}
public int getNumberOfClasses() {
return intNumberOfClasses;
}
public double getMin() {
return dblMin;
}
public double getMax() {
return dblMax;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What are the values? ");
String values = scan.nextLine();
System.out.print("How many classes? ");
int classes = scan.nextInt();
FreqDist fd = new FreqDist(values, classes);
}
}
public class MyStatClass extends FreqDist {
public MyStatClass(String s, int i) {
super(s, i);
}
}
Ok so this is mostly an issue with a flaw in your design.
From what I understand FreqDist is a class that should contain an array of MyStatClass. You want them to have the same properties so you make MyStatClass extend FreqDist. However when you call FreqDist it MyStatClass which Calls a new MyStatClass over and over and over.
One way to solve this is to create a new class that has the shared properties you want FreqDist and MyStatClass to have, and have those two classes inherit from said class. Then create separate constructors for FreqDist and MyStatClass.
A parent type should never refer to its own subtypes, as yours does. Her the parent initializes subtype instances, which require that each initialize the parent type, which initializes subtype instances, which initialize their parent type, which initializes... KABLOOEY!
public class mainTest {
public static void main(String[] args) throws Exception {
Scanner KB = new Scanner(System.in);
String VehiclesFile = "Vehicles.txt";
File file1 = new File(VehiclesFile);
Scanner infile1 = new Scanner(VehiclesFile);
Vehicle[] Vehicles = new Vehicle[0];
try {
Scanner scanner = new Scanner(file1);
int lineCount = 0;
while (scanner.hasNextLine()) {
lineCount++;
scanner.nextLine();
}
Vehicles = new Vehicle[lineCount];
scanner = new Scanner(file1);
int VehicleCount = 0;
while (scanner.hasNextLine()) {
String[] temp1 = scanner.nextLine().split(",");
// file has been read into temp1[] now to use Vehicles
// class type
Vehicles[VehicleCount] = new Vehicle();
Vehicles[VehicleCount].setregistration(temp1[0]);
Vehicles[VehicleCount].setmake(temp1[1]);
Vehicles[VehicleCount].setModel(temp1[2]);
Vehicles[VehicleCount].setyear(temp1[3]);
Vehicles[VehicleCount].setodometer(temp1[4]);
Vehicles[VehicleCount].setowner(temp1[5]);
VehicleCount++;
}
} catch (IOException e) {
// Print out the exception that occurred
System.out.println("Unable to find ");
}
//*******This is where I need to access the class to print****************
System.out.println (Vehicle.class.getClasses());
}
}
I cannot seem to understand how to reference a specific part of the class/array of class objects
The class for Vehicle is in defined with get/set so I didn't include the code.
System.out.println(Arrays.toString(Vehicles));
Make sure that the vehicle class has toString() method overriden. Otherwise it will just print out the references.
See:
How to override toString() properly in Java?
If you want to print off data from the Vehicle objects you'll have to loop through that array and call the getter methods you mentioned before.
It should be something like
for(Vehicle v : Vehicles)
{
System.out.print(v.getYear() + " " + v.getMake() + " " + v.getModel());
}
Seems to me like you're mixing up the concept of classes and objects. Class is short for classification, so a class is a type of something. An object is a single instance of a class. So it's a single item of a certain type.
What you have is an array of objects, not classes, and you want to print the information of each object. So say you have five vehicles in your array, you will have to call the function System.out.println(/*data to print*/) five times. One for each element in the array.
To omit repetition, you can use a loop:
for (int index = 0; index < Vehicles.length; ++i) {
System.out.println(Vehicle[index].getMake());
// do the same to print other attributes of the Vehicle class
}
I'm looking for a better way to organize my class.
Right now my code looks like this:
mainMethod:
-number1 input
-call method1 with number1 als value
method1:
-do "stuff" with input
-call method2 with new "stuff" as value
method2:
-do stuff
-call method3
etc...
So i start with user input in my main method and my whole class works like domino, the first method needs to be called to run the next method.
I would rather have method1 return a value and save it in some global variable in my class which can be used by method2 and so on.
Here is my Code with exactly this problem: (it calculates sqrt)
package wurzel;
import java.util.Scanner;
import wurzel.Fraction;
public class wurzel {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Eingabe:");
int in = s.nextInt();
s.close();
bisection(in);
}
private static int bisection(int N){
int counter = 0;
for(int i = 0; i < N;i++){
if((counter*counter) > N){
counter--;
break;
}
else if(counter*counter == N){
break;
}
else counter++;
}
calculateSequence(counter,N);
return counter;
}
static int[] calculateSequence(int vKomma, int look){
int m = 0;
int d = 1;
int a = vKomma;
int[] intarr = new int[4];
intarr[0] = vKomma;
for(int i = 1; i <= intarr.length; i++){
if(i == intarr.length )
break;
else{
m = (d*a) - m;
d = (look - (m*m)) / d;
a = (vKomma + m) / d;
intarr[i] = a;
}
}
calculateApproximation(intarr);
return intarr;
}
static double calculateApproximation(int[] sequence ){
Fraction result = new Fraction((sequence.length)-1);
for(int dcounter = sequence.length; dcounter > 0; dcounter--){
result = result.reciprocal().add(sequence[dcounter-1]);
}
System.out.println("Approximation als double: " +result.doubleValue());
System.out.println("Approximation als Bruch: " +result);
return result.doubleValue();
}
}
You should also seperate code into different classes. E.g. have a generic MathHelper class which has these methods in it.
This helps keep code seperate and easy to read.
You mentioned that you wanted to store some data in a global variable for the class as a whole. The way to do this is by making the class use instance methods rather than class methods. With class methods, you have to use class variables. But, when you use instance methods, you can define instance variables which can be accessed by any method within the class.
To do this, change all your methods (apart from main()) by removing the keyword static from each method. Then, define the instance variable that is global for the class. e.g. if your global variable is of type int then it would be:
private int myInstanceVariable;
This instance variable, or global variable, can be accessed by a getter and setter.
It is quite normal methods to call each other and to form long chains of calls.
So I would not worry about that. Actually in real world, in enterprise code,
you have call stack going through tens of calls. So I think global variables would
be worse practice compared to what you did.
Ok so I'm doing an assignment for my java coursets part I'm stuck at is :
"Implement an operation createparliamentMembers which will create the particular Parliament
with 80 members."
So i've already created the constructor with it's methods. This is how I wrote the operation to create the objects using the constructor.:
public static void createparliamentMembers(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
The problem is the arrays and objects only seem to exist in the operation for creating them and when I try running method of the objects created they don't work because the driver class doesn't recognize the arrays. On the other hand when I use this as just a normal part of the Driver for it runs fine and all methods of the objects work normally.
Edit: Ok so I'm still getting the same problem as before even though i initiliased them outside the createparliamentMembers();
The following code is the Driver im using to test the methods: It keeps saying there is a:
Exception in thread "main" java.lang.NullPointerException at Driver.main(Driver.java:11)
which is the code array[1].FlipCoin(); as im trying to use the method flipcoin from the created objects but it's not working.
public static void main(String [] args) {
Commands.createparliamentMembers();
array[1].FlipCoin();
}
Your arrays are only defined locally, which means they live and die with the method. When your method finishes, they get put out of memory.
The solution is to define these arrays as instance variables. By that I mean, you need to define the arrays for your class, and then use them in your method:
class someClass {
int[] myArray = new int[2];
private void someMethod() {
myArray[0] = 3;
myArray[1] = //whatever
}
}
You state in comment:
I do have a parliament class it's on it own and contains the methods and constructor for the members of the parliament. The above method was in a seprate class called Commands. I don't understand completely the "Can you add the members to a Parliament object as you create them?" The parliament isn't an object more se then a class containing a constructor and methods for parliament members i want to create.
Parliament isn't an object yet, but you should in fact create one, and in fact your instructions tell you just that: "which will create the particular Parliament with 80 members...". You will need to tell us more about your program's structure and your specific requirements, but I suggest:
First create a Parliament object in the createParliamentMembers method, and call it parliament.
Then create the members of parliament in that method.
As you create these members, add them to the Parliament object, parliament.
At the end of the method return the parliament variable.
This means that your createParliamentMembers method's signature must change so that rather than return void it should be written to return a Parliament object.
When calling the method in the main method, assign what it returns to a Parliament variable that is in the main method.
It looks like you are writing a factory method. Create a constructor for Parliament like this:
public Parliament(Member[] members, Legislator[] legislators, Leader[] leaders) {
// do whatever with what's passed in
}
Then change your method to return a Parliament object and in the method pass your initialized arrays into the Parliament constructor, like this:
// same code as your except the last line
public static Parliament createParliament(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
return new Parliament(array, leg, lead);
}