I need some help understanding instances/references - java

Just want to know if what I'm trying to teach myself is right.
I'll end up with something like this in one of my programs:
public class Test {
int array[];
public static void main(String[] args){
Test test = new Test();
test.array = new int[10];
test.fillArray();
for(int i=0;i<test.array.length;i++)
System.out.println(test.array[i]);
}
public void fillArray(){
Test test = new Test();
for(int i=0;i<test.array.length;i++)
test.array[i]=i;
}
}
But I get a null pointer exceptions. I seem to run into these types of issues a decent amount.. Would proper planning of my programs help with this?
The null Pointer was because when I say new it creates a separate object that only exists inside that method correct?
Are there any other ways to fix this other than making the array static or giving it a parameter (or is it argument..?) like I did below?
public class Test {
int array[];
public static void main(String[] args){
Test test = new Test();
test.array = new int[10];
test.fillArray(test.array);
for(int i=0;i<test.array.length;i++)
System.out.println(test.array[i]);
}
public void fillArray(int a[]){
for(int i=0;i<a.length;i++)
a[i]=i;
}
}

Your first fillArray has a shadowing problem in that you are creating a new test instance and initializing it - instead initialize the field array within the current (or this) instance,
public void fillArray() {
// Test test = new Test();
for (int i = 0; i < this.array.length; i++) {
this.array[i] = i; // <-- this.array or just array[i]
}
}

Related

Program continues to run after method is finished

I have made a simple program, with two classes. The method works fine, however it continues to run after completing my method resulting in this being seen in the output and I have no idea why:
Your myArrayOne method calls itself. That's the problem with infinite recursion.
public static int myArrayOne() {
// that's the problem
return myArrayOne();
}
That is probably what are you trying to accomplish:
// void --> List<Integer>
// static
public List<Integer> myArrayOne() {
ArrayList<Integer> packOfCards = new ArrayList<Integer>();
Random rand = new Random();
for (int j = 0; j<5; j++)
{
pick = rand.nextInt(10);
packOfCards.add(pick);
}
// myArrayOne(); --> packOfCards
return packOfCards;
}
public static void main(String[] args) {
myattributes attributes = new myattributes();
List<Integer> values = attributes.myArrayOne();
}

Why do I get a syntax error in the for-loop definition in this Java program?

I'm working on the below code to create an ArrayList, shuffle it, and take the first three elements but, for some reason, on the line when I start the for loop I get a syntax error on token ";"
import java.util.ArrayList;
public class cardsShuffle {
ArrayList<String> cards = new ArrayList<>()
for (int i = 0; i < 52; i++){
cards.add(String.valueOf(i+1));
java.util.Collections.shuffle(cards);
}
public static void main(String args[]){
cardsShuffle s = new cardsShuffle();
System.out.println(s.cards.get(0));
System.out.println(s.cards.get(1));
System.out.println(s.cards.get(2));
}
You are missing the semicolon after the line "ArrayList cards = new ArrayList<>()".Just put a semicolon and your code will be error free :)
Try this
import java.util.ArrayList;
public class cardsShuffle {
public static void main(String args[]) {
ArrayList<String> cards = new ArrayList<>();
for(int i = 0; i<52;i++)
{
cards.add(String.valueOf(i + 1));
java.util.Collections.shuffle(cards);
}
cardsShuffle s = new cardsShuffle();
System.out.println(cards.get(0));
System.out.println(cards.get(1));
System.out.println(cards.get(2));
}
}
You cannot just put code into a class. It needs to be inside inside a method, constructor or initializer block or the RHS of a field initialisation (not possible for loops).
Furthermore you don't need to shuffle after adding each card. Since Collections.shuffle produces a random permutation, using it once after the loop is sufficient.
public class cardsShuffle {
// field declaration
ArrayList<String> cards;
// constructor
public cardsShuffle() {
cards = new ArrayList<>();
for (int i = 0; i < 52; i++){
cards.add(String.valueOf(i+1));
}
java.util.Collections.shuffle(cards);
}
public static void main(String args[]) {
cardsShuffle s = new cardsShuffle();
System.out.println(s.cards.get(0));
System.out.println(s.cards.get(1));
System.out.println(s.cards.get(2));
}
}
You have written the for loop outside function. All things other than deceleration should be written inside function or blocks.
import java.util.ArrayList;
public class CardsShuffle
{
public static ArrayList<String> cards = new ArrayList<>();
public static void main(String args[])
{
System.out.println(cards.get(0));
System.out.println(cards.get(1));
System.out.println(cards.get(2));
for (int i = 0; i < 52; i++)
{
cards.add(String.valueOf(i+1));
java.util.Collections.shuffle(cards);
}
}
}
The code should be something like this...always things to execute inside the function.

What is the best way to called non-static method from static method in java?

I know there are a lot of questions about this topic.
I have two procedures to call arrPrint method.
1st Procedure:
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
Test test = new Test();
test.arrPrint(arr);
}
public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
2nd Procedure :
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
arrPrint(arr);
}
public static void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
Which procedure is best and why?
Instance methods run on instances of a class, so to execute an instance method you need an instance of a class. Therefore, if you want to call an instance method from within a static method, you need some access to an instance, either a global variable or passed as argument. Otherwise, you will get a compilation error.
2nd procedure is used if you want to use the method arrPrint in another class.
public class A{
public int[] intArray;
public A(int[] intArray) {
this.intArray = intArray;
}
public int[] getIntArray() {
return intArray;
}
}
public class Pourtest {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
A a = new A(arr);
arrPrint(a.getIntArray());
}
public static void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)System.out.println(arr[i]);
}
}
"Instance method" means the method needs to be executed on an instance of the class. The point of objects is that instances can have their own dedicated data, which the instance methods act on, so trying to call an instance method without an object instance doesn't make sense. If you rewrite your example to:
public class Test {
int[] arr = new int[] {1,2,3,4,5};
public static void main(String args[]) {
Test test = new Test();
test.arrPrint();
}
public void arrPrint() {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
then this becomes a little simpler. The instance of Test has its own data, which the instance method can access and do something with.
Look at JDK classes like String or ArrayList and see how they're designed. They encapsulate data and allow it to be accessed through instance methods.
On the other hand static methods can't see instance data, because they don't belong to an object instance. If an instance method doesn't touch any instance data, some static analysis tools like sonarqube will recommend that the instance method be changed to a static method. Since your method operates on data that is passed in and the object created to call it as an instance method is unnecessary, it's better for it to be a static method.

How to call java method on main class

I'm a beginner in Java and I have a very simple problem. I'm trying to finish an activity and I forgot how to call a method on the main class.
I keep getting an error whenever I try ways to call the computeSum method on the main class.
Error: Error: Main method not found in class array.Array, please define the main method as: public static void main(String[] args)
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
}
public int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
Suppose if your class is there in com.arr package. you can specify the qualified name of the class at the time of creating object. Because Array class is already available in java.util package. It is better to create object to your Array class along with package name.
public static void main(String[] args){
com.arr.Array a1 = new com.arr.Array();
int[] numberArray = {1,7,9,0,45,2,89,47,3,-1,90,10,100};
a1.computeSum(numberArray);
}
computeSum() it's an instance method. we have to create Object to your class for calling the instance methods.
You can try this
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
int[] nums = {1,2,3,4,5};
int sum=computeSum(nums);
System.out.println(sum);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
You need to create an instance to invoke member method of a class.
public static void main(String[] args ){
Array myArray = new Array();
int[] values = new int[] {1,2,3,4};
myArray.computeSum(values);
}
You can read about instance methods and static methods.
computeSum() is an instance method, which means it would need an object of Class Array to be called, example:
public static void main(String[] args){
Array array = new Array();
int[] nums = {1,2,3};
array.computeSum(nums);
}
Alternatively, you could make it a static method to use it without making an object, which is not recommended, but incase you want, this is how you can do it:
public class Array{
public static void main(String[] args ){
int[] nums = {1,2,3};
int sum = computeSum(nums);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
First you need to understand the difference between static classes/members and instance classes/members.
Your main method is static - as is standard for the entry method of a program - meaning it is available immediately without any binding to an instance of the Array object.
Your computeSum method is an instance method. Meaning that you need an instance of the object Array, to use it, and it will execute in that object's context.
Your choices:
1)
Make computeSum static:
public static void main(String[] args) {
computeSum({1,2,3}); // or Array.computeSum() outside of Array
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
2)
Make an instance of the Array object:
public static void main(String[] args){
Array myArray = new Array();
myArray().computeSum({1,2,3});
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
Static code - not ran in the context of an object's instance - can not reference members that are not static, this makes sense as, how would it know what object instance of that member you are referencing (myArray1.computeSum()? or myArray2.computeSum()? It doesn't even know these two instances of the myArray object exist).
Hope this helps. :)
Or you could use reflection just for a change ;)
https://docs.oracle.com/javase/tutorial/reflect/
Firstly your method have an attribute which is "int[] nums " to call the method you need to set a value to your attribute .
NOTE that you don't have to give the same name to your attribute while calling.
for example : 1 - int[] Myattribute = {1,2,3};
int sum = computeSum(Myattribute );
put this line incide your Main it ill work

How to instantiate a new public Java class if a parameter is required?

I need an array to be public (accessible to other methods in the class) but the array needs an input value "T" to create it. How do I instantiate a "global" variable that requires user input?
My code is as follows:
public class PercolationStats {
**private double myarray[];**
public PercolationStats(int N, int T) {
**double myarray = new double[T];**
for (i=0;i<T;i++) {
Percolation percExperiment as new Percolation(N);
//do more stuff, make calls to percExperiment.publicmethods
myarray[i] = percExperiment.returnvalue;
}
}
public static void main(String[] args) {
int N = StdIn.readInt();
int T = StdIn.readInt();
PercolationStats percstats = new PercolationStats(N, T);
//do more stuff, including finding mean and stddev of myarray[]
StdOut.println(output);
}
Another example in pseudocode:
class PercolationStats {
Constructor(N, T) {
new Percolation(N) //x"T" times
}
Main {
new PercolationStats(N, T) //call constructor
}
}
class Percolation {
Constructor(N) {
**new WQF(N)** //another class that creates an array with size dependent on N
}
Main {
**make calls to WQF.publicmethods**
}
}
In the second example, it seems to me that I need to have the new instance of class WQF made in the constructor of the Percolation in order to accept the parameter N. However, WQF would not be accessible to the Main method of Percolation.
Help!
Don't include the type declaration in your constructor. You are creating a local variable that masks the field. It should look like this:
public class PercolationStats {
public double myarray[];
public PercolationStats(int n, int y) {
myarray = new double[t];
for (i=0; i<t; i++) {
Percolation percExperiment = new Percolation(n);
//do more stuff, make calls to percExperiment.publicmethods
myarray[i] = percExperiment.returnvalue;
}
}
public static void main(String[] args) {
int n = StdIn.readInt();
int t = StdIn.readInt();
PercolationStats percstats = new PercolationStats(n, t);
//do more stuff, including finding mean and stddev of myarray[]
StdOut.println(output);
}
}
There's certainly no problem using a variable as the length when creating a new array.
Tedd Hopp's answer corrects the bug in your code.
I'd just like to point out that myarray is NOT a global variable.
Java doesn't have global variables,
the closest it has is static variables, and
myarray isn't one of those either. It is an instance variable, as you have declared it.
(And an instance variable is the right way to implement this ... IMO)

Categories