In this program I've created a class called ArrayExample and created a random number to fill its elements and a toString() method with it. Why am I getting null as my output? The code has no errors from what it seems like. :
public class arran {
public static void main(String[] args) {
ArrayExample[] no1 = new ArrayExample[5];
System.out.println(Arrays.toString(no1));
}
public class ArrayExample {
int[] array;
ArrayExample(int len) {
array = new int[len];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 100);
}
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder(array.length);
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
}
return sb.toString();
}
}
}
You're creating ArrayExample[5], which is an array of five ArrayExample objects, and not a single ArrayExample with a constructor argument of 5. It looks like your intent was to invoke the constructor ArrayExample(int len), but it's never called.
Try this, instead:
public static void main(String[] args) {
ArrayExample no1 = new ArrayExample(5); // Invokes the constructor you wrote
System.out.println(no1.toString()); // Uses the toString method your wrote
}
Make your inner class static so it can be accessed by your main method:
public static class ArrayExample {
And fix your .toString() method:
public String toString() {
return Arrays.toString(array);
}
The problem is in this code:
ArrayExample[] no1 = new ArrayExample[5];
System.out.println(Arrays.toString(no1));
This declares an array of a certain type (ArrayExample), and a certain length (5), but it doesn't do anything else. That first line results in a variable reference no1 containing five null values. That's what you see when you print it out.
[null, null, null, null, null]
Here's another example, but using Object to highlight that the code isn't doing anything other than creating an empty array and printing the null values.
Object[] no2 = new Object[5];
System.out.println(Arrays.toString(no2));
This code has the same output:
[null, null, null, null, null]
Here is code that will initialize the array (like you already were doing), then create a new instance of ArrayExample and save it at each array element. (I also moved ArrayExample out of the main class definition so that it compiles).
public class Example {
public static void main(String[] args) {
ArrayExample[] no1 = new ArrayExample[5];
no1[0] = new ArrayExample(10);
no1[1] = new ArrayExample(10);
no1[2] = new ArrayExample(10);
no1[3] = new ArrayExample(10);
no1[4] = new ArrayExample(10);
System.out.println(Arrays.toString(no1));
}
}
class ArrayExample {
// use same class contents as your original post
}
Here is output from running this updated code:
[6474373150570442153, 27524825597078735826, 58127219204026904839, 90611080549351937198, 6503557163540938849]
Another option for setting your array contents would be using this one-liner:
Arrays.setAll(no1, k -> new ArrayExample(10));
Related
Worksheet Question:
The question said to declare an array of 5 objects of the class Node in the main Class - I managed to this as shown below
But then the question continues populate the array by objects with seqNo values assigned to 1,2,3,4,5 respectively. Then traverse the array and print the list of its object using method show()
I have an error when I am trying to show the array to the user.
I am trying to display the array by this line of code:
nodObj[].show();
Below I have all the code except the Person class. Does someone have any idea if I should do a loop. When i tried if loop I got an error too. I have the display part code wrong I can't figure out what to change
My AnyClass
import java.util.Scanner;
public class AnyClass
{
public int seqNo;
/* -----------------Constructor------------*/
public AnyClass(int num)
{
seqNo = num; //initializing
}
//empty constructor
public AnyClass()
{
}
//intialized
public void initializeseqNo(int seqNum)
{
seqNum = seqNo;
}
/*-----Mehtods*/
public String getData()
{return "Sequence number " +seqNo+".";
}
public String getKey()
{
return String.valueOf(seqNo); //for search by seqNo
}
public void editData() //empty method to be overriden by future subcclasses
{
}
public void edit(){
Scanner sc = new Scanner(System.in);
seqNo = sc.nextInt();//next line for String
}
} //end of AnyClass
My Node class
public class Node
{
public AnyClass obj;
public Node(AnyClass newObj)
{
obj = newObj;
}
public void show()
{
System.out.println(obj.getData());
}
}
MainProg
class MainProg{
public static void main (String[] args) {
//-----------Construction of objects---------
Person head = new Person ("Gatt", 21445667);
Person clerk = new Person();
clerk.name = "Delia";
System.out.println ("Data of a new Head: " +head.getData());
AnyClass ac1 = new AnyClass(51);
AnyClass ac2 = new AnyClass(52);
AnyClass ac3 = new AnyClass(53);
ac1.getData();
ac2.getData();
ac3.getData();
//edit value of ac1
ac1.edit();
//print all values again
ac1.getData();
ac2.getData();
ac3.getData();
Node n = new Node(new AnyClass(3));
//print values
n.show();
Node nodObj[] = new Node[5]; //allocating memory to array
//populate array
nodObj[0] = new Node(new AnyClass(1));
nodObj[1] = new Node(new AnyClass(2));
nodObj[2] = new Node(new AnyClass(3));
nodObj[3] = new Node(new AnyClass(4));
nodObj[4] = new Node(new AnyClass(5));
//printing array
nodObj[].show(); //ERROR THIS IS WRONG!
}//end of Main()
}//end of program class
Below I have all the code except the Person class. Does someone have
any idea if I should do a loop. When i tried if loop I got an error
too. I have the display part code wrong I can't figure out what to
change
Yes, you need to loop over the array. At this level of instruction you should use a for or foreach loop.
for (int index = 0; index < nodObj.length; index++) {
nodObj[index].show();
}
Or
for (Node node : nodObj) {
node.show();
}
In the following code, I am wondering how to use the other object. Specifically how do I get the two ArrayLists to have different values within them when I am passing them into the append method.
The following code is supposed to append two Arraylists together without modifying either of them.
I understand that in order to do this, I need to create a separate instance of the Arraylist "values", thats why I used the other object, but I am wondering how do I assign separate values to each instance of the Arraylist
package com.company;
import java.util.ArrayList;
public class MergeSequence {
public ArrayList<Integer> values;
public MergeSequence(){
values = new ArrayList<Integer>();
}
public void add(int n) {
values.add(n);
}
public String toString() {
return values.toString();
}
public MergeSequence append(MergeSequence other)
{
MergeSequence result = new MergeSequence(); // Create a new result object.
// Iterate through the "local" ArrayList and add each value to the result
for (int i = 0; i < values.size(); i++)
{
int j = values.get(i);
result.add(j);
}
// Now, iterate through the "external" ArrayList and add each value to the result
for (int i = 0; i < other.values.size(); i++)
{
int j = other.values.get(i);
result.add(j);
}
result.toString();
// Then return the result. Neither source ArrayList is modified.
return result;
}
}
toString itself doesn't output anything to std-out. So after calling result.toString(); you won't see the result in the console. You need to use System.out.println(result) to output the result.
By the way, printing the values in the append method is a side effect. It would be better to print the values outside of the append. E.g.:
public static void main(String[] args) {
final MergeSequence a1 = new MergeSequence();
a1.add(1);
a1.add(2);
final MergeSequence a2 = new MergeSequence();
a2.add(3);
final MergeSequence a3 = a1.append(a2);
System.out.println(a1); // [1, 2]
System.out.println(a2); // [3]
System.out.println(a3); // [1, 2, 3]
}
Just add a main method to test
public static void main(String[] args) {
MergeSequence m1 = new MergeSequence();
m1.add(1);
m1.add(2);
MergeSequence m2 = new MergeSequence();
m2.add(3);
MergeSequence m3 = m1.append(m2);
System.out.println(m3.toString());
}
public class Alfabhto {
int[][] pinakas = new int[3][6];
String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter an alphanumeric combination");
String fail = s.nextLine();
System.out.println(pinakas[i][j]);
}
public int[][] Numbers() {
Random rand = new Random();
for (int i=0;i<3;i++)
{
for (int j=0;j<6;j++)
{
pinakas[i][j] = rand.nextInt(38)-12;
}
}
return pinakas;
}
}
First of all, I am very new at java. The main function works properly and the user is asked to give an input. Some elements aren't used here (like the gramata array) so ignore them.
The problem is: the method numbers should fill the pinakas array with random numbers and then print them. It does nothing if it's in the method. Outside it brings up errors because it can't get "pinakas" array or i and j. Any ideas?
There is several issues with that code, see comments:
// Need to import Random
import java.util.Random;
public class Alfabhto {
String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
// This neesd to be final for Numbers to access it
final int[][] pinakas = new int[3][6];
// There's no reason for Numbers to be public, or to extend Alfabhto, or in
// fact to be a class at all. Recommend making it a static method within
// Alfabhto (in which case gramata and pinakas must also be static), or an
// instance method if appropriate (in which case pinaka does not need to be
// final anymore, though you might leave it that way if you never
// intend to replace the array with a different one.
// Also recommend making that method (static or instance) a private method.
public class Numbers extends Alfabhto {
public Numbers() {
// Create this once and reuse it
Random rand = new Random();
// Note using <, not <=, on the loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
pinakas[i][j] = rand.nextInt(38) - 12;
System.out.println(pinakas[i][j]);
}
}
}
}
// Since Numbers is an inner class, we need to be able to create instances of Alfabhto
private Alfabhto() {
}
// We need something in Alfabhto to run the Numbers constructor
private void run() {
// Run the code in the Numbers constructor
new Numbers();
}
public static void main(String[] args) {
/* None of this does anything, presumably you'll use it later...
Scanner s = new Scanner(System.in);
System.out.println("Enter an alphanumeric combination");
String fail = s.nextLine();
*/
// Run our run method, which will run the code in the Numbers constructor
new Alfabhto().run();
}
}
In your main function, you never create an instance of Numbers so whatever your wrote in there is not being called. Once you create a new Numbers(), it should print something out.
I am trying to clone an array and return as an object, not an array type.
z
public IntVector clone()
{
IntVector cloneVector = new IntVector(3);
int[] newItems = new int[10];
for(int i=0 ; i<itemCount_; ++i)
{
newItems[i] = items_[i];
}
cloneVector = newItems; // is there a way to do something like this??
return cloneVector;
}
Main method looks like this
public static void main(String[] args)
{
IntVector vector = new IntVector(5);
vector.push(8);
vector.push(200);
vector.push(3);
vector.push(41);
IntVector cloneVector = vector.clone();
}
*there are two other methods which makes an array:IntVector() and puts value into array:push()
Declare a new constructor for IntVector which takes an int array and a count:
IntVector(int[] data, int n) {
items_ = data.clone();
itemCount_ = n;
}
Then you can write clone like this:
public IntVector clone() {
return new IntVector(items_, itemCount_);
}
You can make that new constructor private if you like, so only clone can use it.
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)