Overload method to reverse an int or an array [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I'm new to programming. I'm sure the answer for this question is out there, but I have no idea what to search for.
Ok, I'll go right to it.
Here's my code:
int[] arr;
arr = new int[5];
arr[0] = 20;
arr[1] = 50;
arr[2] = 40;
arr[3] = 60;
arr[4] = 100;
System.out.println(arr);
This compiles and works fine. It's just the output from CMD that I'm dizzy about.
This is the output: [I#3e25a5.
I want the output to represent the exact same numbers from the list (arr) instead. How do I make that happen?

Every object has a toString() method, and the default method is to display the object's class name representation, then # followed by its hashcode. So what you're seeing is the default toString() representation of an int array. To print the data in the array, you can use:
System.out.println(java.util.Arrays.toString(arr));
Or, you can loop through the array with a for loop as others have posted in this thread.

System.out.println(Arrays.toString(arr));
The current output is classtype#hashcode.
Incase you need to print arrays with more than one dimension use:
Arrays.deepToString(arr);
Also remember to override toString() method for user-defined classes so that you get a representation of the objet as you choose and not the default represention which is classtype#hashcode

It's the default string representation of array (the weird text).
You'll just have to loop through it:
for(int i : arr){
System.out.println(i);
}

To print the values use.
for(int i=0; i<arr.length; i++)
System.out.println(arr[i]);

Like this:
for (int i = 0; i < arr.length; ++i)
{
System.out.println(arr[i]);
}
That "weird number" is the reference for the array you printed out. It's the default behavior built into the java.lang.Object toString() method.
You should override it in your own objects if seeing the reference isn't sufficient.

It prints it's .toString() method you should print each element
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}
or
for(Integer i : arr) {
System.out.println(i);
}

BTW You can write
int[] arr = { 20, 40, 60, 40, 60, 100 };
System.out.println(Arrays.toString(array));
or even
System.out.println(Arrays.toString(new int[] { 20, 40, 60, 40, 60, 100 }));
or
System.out.println(Arrays.asList(20, 40, 60, 40, 60, 100));

for (int i = 0; i < arr.length; ++i)
{
System.out.println(arr[i]);
}

Use Arrays.toString() and PrintStream.printf(String format, Object... args).
System.out.printf("%s%n", Arrays.toString(arr));

You printed the reference and not the values at the reference... One day it will all become clear with C.

Related

Changing Array to ArrayList [duplicate]

This question already has answers here:
How to convert int[] into List<Integer> in Java?
(21 answers)
Closed 5 years ago.
I am trying to find duplicate element in an array. I have already solved it using traversing the array. But now i want to convert array to arraylist and use contains keyword of arraylist.
I am not able to convert array to arraylist and use the contains keyword. please look in following code:
public void findDuplicate2() {
int arr[] = { 1, 2, 3, 4, 5, 3, 7, 5 };
ArrayList<int[]> arrlist = new ArrayList<>(Arrays.asList(arr));
for (i = 0; i < len; i++) {
if (arrlist.contains(arr[i]))
System.out.println(arr[i]);
else
System.out.println("no duplicate" + arr[i]);
}
}
There are a number of problems with your code:
You are creating an ArrayList<int[]>, that is, an array list of arrays of int. This list contains one array, namely the one you started out from. I don’t think this was what you intended. My guess is you wanted an ArrayList<Integer> containing the numbers from the array. khelwood’s link should help you out.
You haven’t declared i nor len. I suggest you use for (int i = 0; i < arr.length; i++).
arrlist.contains(arr[i]) always returns false since a list of arrays cannot contain a number (the numbers inside the array are not searched). It’s a design problem with ArrayList that you can ask for whether it contains an element of the wrong type (there are historical reasons for this). If you change the arraylist to ArrayList<Integer> as I suggested above, it will work, though.
Once you get the above to work, arrlist.contains(arr[i]) will always return true since each number from the array will be in the array list, also the ones that are not duplicates.
Here your arrlist variable is of type int[]. Here your arrlist size is 1(the entire input array as single entry).
So, you can only check the existence of any integer array in the list by using contains method of arrlist. if (arrlist.contains(arr)) //returns true in your case
An easier way to find dublicates is this one:
public void findDuplicate2(){
int arr[] = {1,2,3,4,5,3,7,5};
for (int i = 0; i < arr.length; i++) {
boolean dublicate = false;
for (int j = 0; j < arr.length; j++) {
if(arr[i] == arr[j] && i != j){
System.out.println(arr[i]);
dublicate = true;
break;
}
}
if(!dublicate)
System.out.println("No dublicate " + arr[i]);
}
}
In your code the arraylist contains one element, the array arr. You can check this with
System.out.println(arrlist.get(0));
System.out.println(arrlist.get(1));
The right way would be to transfer each element of arr to arraylist...

How to loop inside array?

[ASK]
How to loop inside array? this is right?
weather_data = new Weather[]
{
for (i= 0; i < listOfMenu.size(); i++) {
new Weather(R.drawable.dring1, listOfMenu.get(0)),
}
};
String[] elements = { "a", "a", "a", "a" };
for( int i = 0; i < elements.length - 1; i++)
{
String element = elements[i];
String nextElement = elements[i+1];
}
Short answer, you can't.
Long answer is that it isn't apart of the Java syntax. You have the code to loop through it right there, all you have to do is move it outside. Check out this handy snippet:
Weather[] weather_data = new Weather[listOfMenu.size()];
for (i= 0; i <= listOfMenu.size()-1; i++) {
weather_data[i] = new Weather(R.drawable.dring1, listOfMenu.get(i));
}
It's simple, let me show you.
To enter inside a array and go around with this array you use a simple for, as you did:
for ( parameter : arrayName)
instruction
If by example you want to print the values that are inside the array, you should do like this:
int[] arrayNum = {87, 68, 52, 5, 49, 83, 45, 12, 64}; /
for(int i : arrayNum)
System.out.printf("Array Elements" + arrayNum[i]);
}
I didn't quite understand what you are trying to do, but my answer was a direct response to your question.

Printing an int array is printing out random numbers and letters [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I'm new to programming. I'm sure the answer for this question is out there, but I have no idea what to search for.
Ok, I'll go right to it.
Here's my code:
int[] arr;
arr = new int[5];
arr[0] = 20;
arr[1] = 50;
arr[2] = 40;
arr[3] = 60;
arr[4] = 100;
System.out.println(arr);
This compiles and works fine. It's just the output from CMD that I'm dizzy about.
This is the output: [I#3e25a5.
I want the output to represent the exact same numbers from the list (arr) instead. How do I make that happen?
Every object has a toString() method, and the default method is to display the object's class name representation, then # followed by its hashcode. So what you're seeing is the default toString() representation of an int array. To print the data in the array, you can use:
System.out.println(java.util.Arrays.toString(arr));
Or, you can loop through the array with a for loop as others have posted in this thread.
System.out.println(Arrays.toString(arr));
The current output is classtype#hashcode.
Incase you need to print arrays with more than one dimension use:
Arrays.deepToString(arr);
Also remember to override toString() method for user-defined classes so that you get a representation of the objet as you choose and not the default represention which is classtype#hashcode
It's the default string representation of array (the weird text).
You'll just have to loop through it:
for(int i : arr){
System.out.println(i);
}
To print the values use.
for(int i=0; i<arr.length; i++)
System.out.println(arr[i]);
Like this:
for (int i = 0; i < arr.length; ++i)
{
System.out.println(arr[i]);
}
That "weird number" is the reference for the array you printed out. It's the default behavior built into the java.lang.Object toString() method.
You should override it in your own objects if seeing the reference isn't sufficient.
It prints it's .toString() method you should print each element
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}
or
for(Integer i : arr) {
System.out.println(i);
}
BTW You can write
int[] arr = { 20, 40, 60, 40, 60, 100 };
System.out.println(Arrays.toString(array));
or even
System.out.println(Arrays.toString(new int[] { 20, 40, 60, 40, 60, 100 }));
or
System.out.println(Arrays.asList(20, 40, 60, 40, 60, 100));
for (int i = 0; i < arr.length; ++i)
{
System.out.println(arr[i]);
}
Use Arrays.toString() and PrintStream.printf(String format, Object... args).
System.out.printf("%s%n", Arrays.toString(arr));
You printed the reference and not the values at the reference... One day it will all become clear with C.

Why when initializing byte array with the same value gives different value/bytes? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I'm new to programming. I'm sure the answer for this question is out there, but I have no idea what to search for.
Ok, I'll go right to it.
Here's my code:
int[] arr;
arr = new int[5];
arr[0] = 20;
arr[1] = 50;
arr[2] = 40;
arr[3] = 60;
arr[4] = 100;
System.out.println(arr);
This compiles and works fine. It's just the output from CMD that I'm dizzy about.
This is the output: [I#3e25a5.
I want the output to represent the exact same numbers from the list (arr) instead. How do I make that happen?
Every object has a toString() method, and the default method is to display the object's class name representation, then # followed by its hashcode. So what you're seeing is the default toString() representation of an int array. To print the data in the array, you can use:
System.out.println(java.util.Arrays.toString(arr));
Or, you can loop through the array with a for loop as others have posted in this thread.
System.out.println(Arrays.toString(arr));
The current output is classtype#hashcode.
Incase you need to print arrays with more than one dimension use:
Arrays.deepToString(arr);
Also remember to override toString() method for user-defined classes so that you get a representation of the objet as you choose and not the default represention which is classtype#hashcode
It's the default string representation of array (the weird text).
You'll just have to loop through it:
for(int i : arr){
System.out.println(i);
}
To print the values use.
for(int i=0; i<arr.length; i++)
System.out.println(arr[i]);
Like this:
for (int i = 0; i < arr.length; ++i)
{
System.out.println(arr[i]);
}
That "weird number" is the reference for the array you printed out. It's the default behavior built into the java.lang.Object toString() method.
You should override it in your own objects if seeing the reference isn't sufficient.
It prints it's .toString() method you should print each element
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}
or
for(Integer i : arr) {
System.out.println(i);
}
BTW You can write
int[] arr = { 20, 40, 60, 40, 60, 100 };
System.out.println(Arrays.toString(array));
or even
System.out.println(Arrays.toString(new int[] { 20, 40, 60, 40, 60, 100 }));
or
System.out.println(Arrays.asList(20, 40, 60, 40, 60, 100));
for (int i = 0; i < arr.length; ++i)
{
System.out.println(arr[i]);
}
Use Arrays.toString() and PrintStream.printf(String format, Object... args).
System.out.printf("%s%n", Arrays.toString(arr));
You printed the reference and not the values at the reference... One day it will all become clear with C.

char array to int array

I'm trying to convert a string to an array of integers so I could then perform math operations on them. I'm having trouble with the following bit of code:
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = (int[])list[i];
}
System.out.println(num);
This is giving me an "inconvertible types" error, required: int[] found: char
I have also tried some other ways like Character.getNumericValue and just assigning it directly, without any modification. In those situations, it always outputs the same garbage "[I#41ed8741", no matter what method of conversion I use or (!) what the value of the string actually is. Does it have something to do with unicode conversion?
There are a number of issues with your solution. The first is the loop condition i > raw.length() is wrong - your loops is never executed - thecondition should be i < raw.length()
The second is the cast. You're attempting to cast to an integer array. In fact since the result is a char you don't have to cast to an int - a conversion will be done automatically. But the converted number isn't what you think it is. It's not the integer value you expect it to be but is in fact the ASCII value of the char. So you need to subtract the ASCII value of zero to get the integer value you're expecting.
The third is how you're trying to print the resultant integer array. You need to loop through each element of the array and print it out.
String raw = "1233983543587325318";
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = raw.charAt(i) - '0';
}
for (int i : num) {
System.out.println(i);
}
Two ways in Java 8:
String raw = "1233983543587325318";
final int[] ints1 = raw.chars()
.map(x -> x - '0')
.toArray();
System.out.println(Arrays.toString(ints1));
final int[] ints2 = Stream.of(raw.split(""))
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(ints2));
The second solution is probably quite inefficient as it uses a regular expression and creates string instances for every digit.
Everyone have correctly identified the invalid cast in your code. You do not need that cast at all: Java will convert char to int implicitly:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Character.digit(list[i], 10);
}
System.out.println(Arrays.toString(num));
You shouldn't be casting each element to an integer array int[] but to an integer int:
for (int i = 0; i > raw.length(); i++)
{
num[i] = (int)list[i];
}
System.out.println(num);
this line:
num[i] = (int[])list[i];
should be:
num[i] = (int)list[i];
You can't cast list[i] to int[], but to int. Each index of the array is just an int, not an array of ints.
So it should be just
num[i] = (int)list[i];
For future references. char to int conversion is not implicitly, even with cast. You have to do something like that:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[list.length];
for (int i = 0; i < list.length; i++){
num[i] = list[i] - '0';
}
System.out.println(Arrays.toString(num));
This class here: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html should hep you out. It can parse the integers from a string. It would be a bit easier than using arrays.
Everyone is right about the conversion problem. It looks like you actually tried a correct version but the output was garbeled. This is because system.out.println(num) doesn't do what you want it to in this case:) Use system.out.println(java.util.Arrays.toString(num)) instead, and see this thread for more details.
String raw = "1233983543587325318";
char[] c = raw.toCharArray();
int[] a = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
a[i] = (int)c[i] - 48;
}
You can try like this,
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Integer.parseInt(String.valueOf(list[i]));
}
for (int i: num) {
System.out.print(i);
}
Simple and modern solution
int[] result = new int[raw.length()];
Arrays.setAll(result, i -> Character.getNumericValue(raw.charAt(i)));
Line num[i] = (int[])list[i];
It should be num[i] = (int) list[i];
You are looping through the array so you are casting each individual item in the array.
The reason you got "garbage" is you were printing the int values in the num[] array.
char values are not a direct match for int values.
char values in java use UTF-16 Unicode.
For example the "3" char translates to 51 int
To print out the final int[] back to char use this loop
for(int i:num)
System.out.print((char) i);
I don't see anyone else mentioning the obvious:
We can skip the char array and go directly from String to int array.
Since java 8 we have CharSequence.chars which will return an IntStream so to get an int array, of the char to int values, from a string.
String raw = "1233983543587325318";
int[] num = raw.chars().toArray();
// num ==> int[19] { 49, 50, 51, 51, 57, 56, 51, 53, 52, 51, 53, 56, 55, 51, 50, 53, 51, 49, 56 }
There are also some math reduce functions on Intstream like sum, average, etc. if this is your end goal then we can skip the int array too.
String raw = "1233983543587325318";
int sum = raw.chars().sum();
// sum ==> 995
nJoy!

Categories