I wish to declare an array as a class variable but with dimensions input from the user.
class whatever
{
int array[][]=new int [n][n]; //this is a wrong definition
public void method()
{
//method content
}
}
Here n is the required input.
You can pass n as an argument to the constructor of your class1. Something like
class Whatever {
int[][] array;
public Whatever(int n) {
this.array = new int[n][n];
}
public void method()
{
//method content
}
}
1 And, by convention, Java class names should start with a capital letter.
You can pass array size trough constructor as a parameter and do like this.
class YourClass {
int[][] array;
public YourClass(int size){
array=new int[size][size];
}
public YourClass(int coloumnSize,int rowSize){
array=new int[rowSize][coloumnSize];
}
}
Hope it will help you.
Related
Please see image below:
How can I modify the syntax so as to be able to assign specific values to specific cells in the array?
You cannot assign values in the class body, unless you write it in initialiser block or constructor. So write in the block as mentioned below or assign in constructor.
public class Maze{
private int maze[][] = new int[5][5];
//Changing the value using initializer block
{
maze[1][1] = 1;
}
//Changing the value using constructor
public Maze(){
maze[1][1]=5;
}
public int[][] getMaze() {
return maze;
}
public void setMaze(int[][] maze) {
this.maze= maze;
}
public static void main(String args[]) {
Maze maze = new Maze();
int maze[][] = maze.getMaze();
//Changing the value after creating object
maze[1][2] = 5;
}
}
One simple way to assign values is by writing a custom method with Maze class and using it in your main method. For ex:
private void updateMaze(int val, int i, int j) {
maze[i][j] = val;
}
Depending on the use case, different access modifier can be used.
I want to take user input for merge sorting so i'm using the array ar[] in the method but it gives error "cannot find symbol " for ar[]..
import java.util.*;
import java.io.*;
class Test
{
int Merge()
{
int q,p,r,i,l,m,j,t,k,w,x,s,u;
w=q-p+1;
x=r-q;
int[] L=new int [w+1];
int b=1;
for(s=1;s<=w+1;s++)
{
L[b]=s;
b++;
}
int[] R=new int [x+1];
int c=1;
for(t=1;u<=x+1;u++)
{
R[c]=u;
c++;
}
for(i=1;i<=w;i++)
{
L[i]=ar[p+i-1];
}
for(j=1;j<=x;j++)
{
R[j]=ar[q+j];
}
L[w+1]=1000;
R[x+1]=1001;
i=1;
j=1;
for(k=p;k<=r;k++)
{
if(L[i]<=R[j])
{
ar[k]=L[i];
i=i+1;
}
else
{
ar[k]=R[j];
j=j+1;
}
}
System.out.println("sorted array"+ar[k]);
}
public static void main(String ar[])
{
int a0=Integer.parseInt (ar[0]);
int a1=Integer.parseInt (ar[1]);
int a2=Integer.parseInt (ar[2]);
int a3=Integer.parseInt (ar[3]);
int a4=Integer.parseInt (ar[4]);
int a5=Integer.parseInt (ar[5]);
int a6=Integer.parseInt (ar[6]);
int a7=Integer.parseInt (ar[7]);
int a8=Integer.parseInt (ar[8]);
int a9=Integer.parseInt (ar[9]);
int p=a0,r=a9,q;
if(p<r)
q=(p+r)/2;
Test T=new Test();
T.Merge();
}
}
ar is visible only in the scope of main method, it's unknown in other methods. In order to see it in other methods, you need to have a class member that will hold its value.
You have an ar local variable in the main method, but you don't have it in the Merge method. Local variables, and method parameter is just another kind of local variable, are... well, local to the method where they are declared. That means that such a variable is undefined in another method.
For example, you can have
class Test {
final int[] ar;
Test(int[] ar) { this.ar = ar; }
public static void main(String[] ar) {
....
final Test t = new Test(ar);
t.Merge();
}
}
ar is will be visible in main method only, you need to create a new array in main method. Copy values read into new array and pass this array as input to merge method.
How do I make a constructor to set the length of a global array?
I have already tried several ways to do it, none successful.
Example:
public Class{
public Class(int length){
double[] array = new double[length]; <- this is not global
L = length;
}
int L;
double[] array = new double[L]; <- this does not work
}
I need an array with a length determined by Constructor.
I think it's as simple as this:
public class MyClass{
double[] array;
public MyClass(int length){
array = new double[length];
}
}
I've also made the code actually compile :) You were missing some keywords etc.
If you want to access length in your code, use array.length rather than storing it redundantly in a separate field.
Also calling your class Class is a bad choice, even as an example, because it clashes with java.lang.Class.
Declare the array as member variable. Then initialize it in the constructor.
public class A{
private double[] array;
public Class(int length){
array = new double[length];
L = length;
}
}
You could initialize it in second way. But then you need to use a fixed length
public class A{
private double[] array = new double[100]; // use fixed length
public Class(int length){
array = new double[length];
L = length;
}
}
I don't know what you are trying to achieve but why you don't simply do it this way:
public class Class{
public Class(int length){
this.array = new double[length]; // <- this is not global
}
double[] array;
}
public class aClass{
//define the variable name here, but wait to initialize it in the constructor
public double[] array;
public aClass(int length){
array = new double[length];
}
}
You can do it
public class Test {
double[] array;
public Test (int length){
array = new double[length]; <- this is not global
}
I have a problem with my code, in that it keeps saying that the constructor is undefined. I already read somewhere that I need to declare the constructor with no arguments. I just don't know how to do that.
If someone could help, I am new at java and programming. My code is below:
import java.util.*;//import library
class Input
{
public Input (int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
}
public Input enter(int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
return this;
}
}
class Show
{
public Show (int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
}
public Show print(int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
return this;
}
}
public class Assignment2
{
public static void main(String[] args)
{
//declaring variables
int startV,endingV;
int size=0;
System.out.print("Give the size of the array:");//Print message on screen
size = new Scanner(System.in).nextInt();//asking for the size of array
double[] array= new double[size]; //creation of array
System.out.print("Give the starting value of the array:");
startV = new Scanner(System.in).nextInt();//asking for the starting value of array
System.out.print("Give the ending value of the array:");
endingV = new Scanner(System.in).nextInt();//asking for the last value of array
//calling the functions from the other classes
Input enter= new Input(size,startV,endingV);
Show print= new Show(size,array);
}
}
You're close:
You have a method:
public Method enter(int size,int startV,int endingV) {
to make it a constructor it's signature must be
public Method (int size,int startV,int endingV) {
and you then have to delete the return this; statement.
Remember, constructors don't have a return type and their name is identical to the name of the class. With this information, you'll also be able to fix the Method1 constructor.
Also, please respect the Java naming conventions and have variables start with a lower-case letter to improve the readability of your code.
You need to create a
public Method(size,startV,endingV)
not
public Method enter = (size, startV, endingV)
The first is a constructor the second is a method
For class Method
the default constructor will be
public Method(){}
For class Method1
the default constructor will be
public Method1(){}
in your classes there are no constructors as the
constructor name must be will the same as class name.
enter(int size,int startV,int endingV)
and
print(int size,double[] array)
can be two methods in your classes.
also your two constructor can be -
public Method(int size,int startV,int endingV){ /..../}
and
public Method1(int size,double[] array){ /..../}
Your constructor must have the same name than your class and has no return type. So for your class Method, your constructor will simply be :
public Method(int size, int startV, int endingV)
{
// code...
}
Please also note that constructors exist to initialize your instances of objects, if you want to create a method that does a specific calcul, then yes, you'll have to do :
public int enter(int size, int startV, int endingV)
{
int result = 0;
// code to calculate, for example result = size + startV + endingV ...
return result;
}
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)