What does this java output mean? - java

public class Arrys {
private int[] nums;
//Step 3
public Arrys (int arrySize) {
nums = new int[arrySize];
}
public int [] getNums (){
return nums;
}
}
Test class:
public class TestArrys
{
public static void main(String args[])
{
//Step 4
Arrys arry = new Arrys(10);
System.out.println("\nStep4 ");
for(int index = 0; index < arry.getNums().length; index++) {
System.out.print(arry.getNums());
}
}
}
It's incredibly simple, that is why I think I'm doing something fundamentally wrong. All I want is to display the value of the array.
This is what I get back. I am totally lost, there is nothing in my book that explains this nor does googling it help.
Step4
[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440

You're trying to print the array itself out several times. This code:
for(int index = 0; index < arry.getNums().length; index++) {
System.out.print(arry.getNums());
}
should (potentially) be this:
for(int index = 0; index < arry.getNums().length; index++) {
// println instead of print to get one value per line
// Note the [index] bit to get a single value
System.out.println(arry.getNums()[index]);
}
Or rather more simply:
for (int value : arry.getNums()) {
System.out.println(value);
}
When you call toString() on an array, it returns something like [I#1ac88440 where the [ indicates that it's an array, I indicates the array element type is int, and #xxxxxxxx is the address in memory. It's diagnostic, but not really helpful in most cases.
Use Arrays.toString to get a more useful representation.

Try
System.out.println(java.util.Arrays.toString(arry.getNums()));
instead of the loop.
By default, printing out an array will not give you a very useful string. To get the kind of output you're hoping for, you could loop through the array and print out each element yourself... or you could let java.util.Arrays do the dirty work.

It returns array:
public int [] getNums ()
This loop prints array reference getNums().length times...
for(int index = 0; index < arry.getNums().length; index++) {
System.out.print(arry.getNums());
}
Try this:
int [] nums = arry.getNums();
for(int index = 0; index < nums.length; index++) {
System.out.print(arry.nums[index]);
}

Related

How to change values of an array inside a class

I have a question about my code.
class Zillion
{
private int[] d;
public Zillion(int size)
{
d = new int[size];
}
public void timesTen()
{
for(int i = 0; i<d.length;i++)
{
d[i] = d[i + 1];
}
d[d.length]=0;
}
public String toString()
{
String num;
num= "";
for(int i = 0; i<d.length; i++)
{
num = num + d[i];
}
return num;
}
}
Here in my class Zillion, I am trying to multiply a number that is represent by an array by 10. So what I did was I move the elements at each index to the left and change the value at the last index to 0. For instance,
0 1 4 8 will be come 1 4 8 0.
I am not sure whether my logic will work but that was my first start.
First, I am trying to change the values at each index of the array with an assigned size and here is my driver file.
class Driver
{
public static void main(String[] args)
{
Zillion z = new Zillion(5);
System.out.println(z); // 00000
for (int j = 0; j <= 5; j += 1)
{
z[j]=j;
}
System.out.println(z);
}
}
However, Java throws me an error and says: "Error:(32, 14) java: array required, but Zillion found".
I took C++ and I believe I could change array values like z[j] = j but I guess it is different in Java.
Is there a way I can change the values of the specific index I want? The reason why I used the for loop is because I could not think of any method that I can use to assign the values at each index I want. Is that possible that in the Driver file I create an array, say, 0148 and call my "timesTen" method to give me what I want?
Thank you!
You need to expose the array d of zillion class using a gettor method.
public getArray(){ return d;}
Instead of z[j]=j; you need to use z.getArray()[j] = j
Also your timesTen method will cause arrayindex out of bounds exception in the line
d[d.length]=0;
Java array is not dynamically growing so, Index should be lesser than array size.
You can't index a class, only arrays.
Define a method in Zillion
class Zillion {
public void set(int index, int value) {
// TODO implement
}
}
In your loop, call z.set(j, j)
Note: j <= 5 will cause an out of bound exception
I believe I could change array values like z[j] = j
You could - if z would be an array! But, as the error message also states, it is an object of type Zillion:
Zillion z = new Zillion(5);
You are using instance z of Zillion class, use array instead of it.
//Create getter method in Zillion Class
public int[] getD() {
return d;
}
//And access that array in Driver Class
int[] array = z.getD();
for (int j = 0; j < 5; j += 1) {
array[j] = j;
}
Moreover, you are going to face an
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
because of the statement d[d.length] = 0; in your timesTen() implementation. You have to replace that line with:
d[d.length-1] = 0;
This is not an answer to your question, because you have already received valuable ones, but I hope it could help you.

Java passing 2 dimension array to method

public static void main{
String [][] book = new String[100][6];
for(int i = 0; i < 1; i++) {
for(int j = 0; j < 5; j++) {
book[i][j] = i;
}
}
arrayMethod(book);
}
public static void arrayMethod(String[][] array){
System.out.println(Arrays.asList(array));
}
arrayMethod method output is [[Ljava.lang.String;#639facbc, [Ljava.lang.String;#8059dbd, [Ljava.lang.String;#28b6e768, [Ljava.lang.String;#1271ba, ....
Problem is that in arrayMethod I can't acces 2 dimension array data, where can be problem?
It's doing exactly what you want: you're pretending the (first-level) array is a List (of Array) and then printing the toString() of those, which looks something like [Ljava.lang.String#pointer. You probably want this instead:
System.out.println(Arrays.deepToString(array));
as Alya'a Gamal said, if you want to put an int inside an array of String you need to parse it : book[i][j] = Integer.toString(i);.
Then if you want to display your array, you need to run thought it, like this for example :
public static void arrayMethod(String[][] array){
for(int i = 0; i < array.length;i++) {
for(int j = 0; j < array[i].length;j++)
System.out.println(array[i][j]); // a stringBuilder would be better than to print inside the loop
}
}
You can use Arrays.toString to print 1-D string array, but you CANNOT use Arrays.toString to print the 2-D array directly.
There are 2 ways for you to print the 2D string array in console.
Way#1 ==>
System.out.println(Arrays.deepToString(array));
Way#2 ==>
for(String[] arr: array)
{
System.out.println(Arrays.toString(arr));
}
I see three issues here :
(1). The signature of the main method looks odd. It would raise a compile issue.
public static void main(String args[])
{
// Your code here
}
(2). In the following code :
for(int i = 0; i < 1; i++) {
for(int j = 0; j < 5; j++) {
book[i][j] = i;
}
}
book[i][j] =i; // Here you are trying to insert an int in place where a String is required.
This will again lead to a compile time issue.
You can correct it as follows:
book[i][j] = Integer.toString(i);
(3).
Use the following static method in the Arrays class to print the elements of 2D array on the console.
System.out.println(Arrays.deepToString(array));
Hope this helps.
+1 for isolating the problem.

copying integer parameter into an array element

Write a method called fillIntArray that takes two parameters – an integer array and an integer. The method must copy the integer parameter into each element of the integer array. The method does not have a return value.
Below is my current code, the test method applies random array lengths and variables for the integer, but I'm struggling with the concept of inputting data into an array. I understand pulling info but unsure of how to write the code to input it.
Can someone please indicate effective ways of writing this code?
public class Q8 {
void fillIntArray(int [] array, int x) {
for(int i = 0; i < x; ++i) {
array[i] = +x;
}
}
}
That code demonstrates knowledge of how to insert data into an array. But a few hints:
Your loop should go from 0 to array.length, not 0 to x.
It's a good idea to use x in the assignment statement, not +x. This makes the code more clear, and prevents bozos like me from thinking it will make the code not work.
Try following code. You should iterate over the whole array and put value x in each location.
public class Q8 {
void fillIntArray(int [] array, int x) {
for(int i = 0; i < array.length; ++i) {
array[i] = x;
}
}
}
The fasted way:
void fillIntArray(int[] array, int val) {
for (int i = 0, len = array.length; i < len; i++)
array[i] = val;
}

Covert 2D array to 1D array storing the 2D array position (col, row) and the value in a 1D array

I have managed to convert it to output the values from the 2D array, but have no idea how to get the position.
Here is my code:
public static int[] convert(int [][]twodarray)
{
int[] onedarray = new int[twodarray.length * twodarray.length];
for(int i = 0; i < twodarray.length; i ++)
{
for(int s = 0; s < twodarray.length; s ++)
{
onedarray[(i * twodarray.length) + s] = twodarray[i][s];
}
}
return onedarray;
}
public static int [] printonedarray(int [] onedarray)
{
System.out.print("onedarray: ");
for(int i = 0; i < onedarray.length; i++)
{
System.out.print(onedarray[i] + "\t");
}
System.out.println();
return onedarray;
}
assuming that your 2-d array is not a jagged array, than the original cordinates for A[i] should be A[i/x][i%x] where x is the original length of the least significant column your 2/d array
Okay, I am not really sure if I get you correclty. But I understand it this way:
You have a 2 dim. array and want to convert it to a 1 dim. array.
Therefore you want to ready the first coloumn and the first line.
Then you want to add this value at the forst position of the 1 dim. array.
Then you read the next row and want to add this value and so on.
If I am right I suggest an arrayList for your 1 dim array. Because you don't know how deep the coloumns are. And ArrayLists are dynamic. You can simply add an element and don't need to give a position.
Your code suggestion was pretty good and I just converted it to an ArrayList.
import java.util.ArrayList;
public class test
{
public static ArrayList<Integer> convert(int [][]twodarray)
{
ArrayList<Integer> onedarray = new ArrayList<Integer> ();
for(int i = 0; i < twodarray.length; i ++)
{
for(int s = 0; s < twodarray[i].length; s ++)
{
onedarray.add(twodarray[i][s]);
}
}
return onedarray;
}
public static ArrayList<Integer> printonedarray(ArrayList<Integer> onedarray)
{
System.out.print("onedarray: ");
for(int i = 0; i < onedarray.size(); i++)
{
System.out.print(onedarray.get(i) + "\t");
}
System.out.println();
return onedarray;
}
}
If I missed your question I am sorry for a "wrong" answer.
I hope it will help you!

Printing distinct integers in an array

I'm trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.
I'm getting an error on the else if line in the function checkDuplicate.
Here's my code so far:
import javax.swing.JOptionPane;
public static void main(String[] args) {
int[] array = new int[10];
for (int i=0; i<array.length;i++) {
array[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter"
+ "an integer:"));
}
checkDuplicate (array);
}
public static int checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
return 1;
}
}
The simplest way would be to add all of the elements to a Set<Integer> and then just print the contents of the Set.
First of all, the "else if" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "if (condition) ...").
Second, you cannot decide inside the inner loop, if a value should be printed: The way your code works you write a value array[i] for each value array[j] that is different from array[i]!
Third: the inner loop needs only to go from 0 to the outer index i-1: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.
A proper implementation of CheckDuplicate() would be:
public static void checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
}
But of course, some kind of Set would be much more efficient for bigger arrays...
EDIT: Of course, mmyers (see comments) is right by saying, that since CheckDuplicate() doesn't return any value, it should have return type void (instead of int). I corrected this in the above code...
Put them in a set ordered by insertion time, then convert back to an array if necessary.
new LinkedHashSet<Integer>(array).toArray()
Try throwing all of the integers into a Set. Duplicates will not ever be added to the Set and you will be left will a set of unique integers.
What you want can be accomplished using Java collection API, but not exactly as an one-liner, due to fact collection methods work with Objects and not primitives. J2SE lacks methods that convert, say, int[] to Integer[], but Apache Commons Lang library contains such useful methods, like ArrayUtils.toObject() and ArrayUtils.toPrimitive().
Using them, method to remove duplicated elements from an integer array looks something like this:
public static int[] removeDuplicates(int... array) {
Integer[] ints = ArrayUtils.toObject(array);
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(ints));
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
If your application is likely to include more of array/collection manipulation, I suggest you take a look at that library, instead of implementing things from scratch. But, if you're doing it for learning purposes, code away!
It would probably be better to add each number to a Set implementation rather than an array. Sets are specifically for storing collections of elements where you want to filter out duplicates.
Either use a Set as other people have suggested or use an List compatible class. With a list compatible class just use the Contains method to check if it already exists in the array.
import java.util.Scanner;
public class PrintDistinctNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int [] numberArray = createArray();
System.out.println("The number u entered are: ");
displayArray(numberArray);
getDistinctNumbers(numberArray);
}
public static int[] createArray() {
Scanner input = new Scanner(System.in);
int [] numberCollection = new int [10];
System.out.println("Enter 10 numbers");
for(int i = 0; i < numberCollection.length; i++){
numberCollection[i] = input.nextInt();
}
return numberCollection;
}
public static void displayArray(int[] numberArray) {
for(int i = 0; i < numberArray.length; i++){
System.out.print(numberArray[i]+" ");
}
}
public static void getDistinctNumbers(int[] numberArray) {
boolean isDistinct = true;
int temp = 0;
int [] distinctArrayNumbers = new int [10];
for ( int i = 0; i < numberArray.length; i++){
isDistinct = true;
temp = numberArray[i];
for( int j = 0; j < distinctArrayNumbers.length; j++){
if( numberArray[i] == distinctArrayNumbers[j] ){
isDistinct = false;
}
}
if(isDistinct){
distinctArrayNumbers[temp]=numberArray[i];
temp++;
}
}
displayDistinctArray(distinctArrayNumbers);
}
public static void displayDistinctArray(int[] distinctArrayNumbers) {
for( int i = 0; i < distinctArrayNumbers.length; i++){
if(distinctArrayNumbers[i] != 0){
System.out.println(distinctArrayNumbers[i]);
}
}
}
}

Categories