I am new to java,I have created array which accepts 8 values. It's working fine,also accepting values but it's not displaying correct output on console,please help me what the problem can be ??
Here's my code,
import java.util.*;
public class array2
{
public static void main(String []args)
{
Scanner scan=new Scanner(System.in);
int[] nums=new int[8];
for(int count=0;count<8;count++)
{
nums[count]=scan.nextInt();
}
System.out.println(nums);
}
}
Use System.out.println(Arrays.toString(nums)); (import java.util.Arrays to do this)
If you just say System.out.println(nums);, it will only print the object reference to the array and not the actual array elements. This is because array objects do not override the toString() method, so they get printed using the default toString() method from Object class, which just prints the [class name]#[hashcode] of the object instance.
Printing an array like that is not possible in Java, you probably got something like "[I"...
Try looping:
for (int n=0; n<nums.length; ++n)
System.out.println(nums[n]);
This is because you are printing the array object instead of elements
Use this
for(int i : nums){
System.out.println(i);
}
The [ symbol in the output indicates that the object being printed
is an array.
Alternatively, you can do
System.out.println(Arrays.toString(nums));. This gives String representation of the array.
Display array in a loop:
for(int count=0; count<8; count++)
{
System.out.println(nums[count])
}
You are printing array reference, not their elements.
You need to use Arrays.toString(int[]), to create string that will contain the expected from. Currently you are printing string representation of array itself.
nums[count]=scan.nextInt() will only print the memory location of the array and not the array contents. To print the array contents you need to loop as you did when you insert them. I would try:
for(int count=0;count<8;count++){
System.out.println(nums[count]);
}
Hope that helps
Related
I'm writing a method to calculate the distance between 2 towns in a given array by adding all the entries between the indexes of the two towns in the second array, but I can't invoke indexOf on the first array to determine where the addition should start. Eclipse is giving me the error "Cannot invoke indexOf on array type String[]" which seems pretty straight forward, but I do not understand why that won't work.
Please note the program is definitely not complete.
public class Exercise_3 {
public static void main(String[] args){
//Sets the array
String [] towns={"Halifax","Enfield","Elmsdale","Truro","Springfield","Sackville","Moncton"};
int[] distances={25,5,75,40,145,55,0};
distance(towns, distances, "Enfield","Truro");
}
public static int distance(String[] towns,int[] distances, String word1, String word2){
int distance=0;
//Loop checks to see if the towns are in the array
for(int i=0; i<towns.length; i++){
if(word1!=towns[i] || word2!=towns[i] ){
distance=-1;
}
//Loop is executed if the towns are in the array, this loop should return the distance
else{
for(int j=0; j<towns.length; j++){
*int distance1=towns.indexOf(word1);*
}
}
}
return distance;
}
}
No, arrays do not have any methods you can invoke. If you want to find the index of an given element, you can replace String[] by ArrayList<String>, which has an indexOf method to find elements.
It doesn't work because Java is not JavaScript.
The latter offers an array prototype that actually exposes the function indexOf, while the former does not.
Arrays in JavaScript are completely different from their counterparts in Java.
Anyway, you can be interested in the ArrayList class in Java (see here for further details) that is more similar to what you are looking for.
How about this (from this post)?
There are a couple of ways to accomplish this using the Arrays utility class.
If the array is not sorted:
java.util.Arrays.asList(theArray).indexOf(o)
If the array is sorted, you can make use of a binary search for performance:
java.util.Arrays.binarySearch(theArray, o)
I hope this helps you. If it doesn't, please downvote.
I'm doing an assignment for my intro to programming class and it's a bubble sort. The code may be flawed, but I'm not looking for someone to solve that problem. What my problem is, is that I'm trying to print it. I've been given the condition that the method had to be defined by a void method by the line "public static void sort(int[] array)". So, if I tried import Arrays, and used System.out.println(Arrays.toString(sort(array))); in my main method, it wouldn't work because I get a compiler error saying that void does not apply. If I tried to put it into a loop at the main method, it tells me that there are incompatible types. What is found is a void, what is required is an int[], but the original condition of the assignment is to use a void method. So, with that being said, should I change the method from void to int[] for testing purposes and submit the assignment as a void, or is there a way to print the output of this code with the void and I'm just missing it?
public static void sort(int[] array)
{
int[] y = new int[array.length];
for(int i = 0; i<=array.length-1; i++)
{
for(int j = i+1; i<=array.length-1; j++)
{
if(array[i] < array[j]){
y[i] = array[j];
}
if(array[i] >= array[j]){
y[i] = array[i];
}
}
for(int k = 0; k<y.length; k++){
System.out.println(y[k]);
}
}
} //end of sort method
The problem is that you create an new local array inside your sort method which you obviously cannot return because of the restriction of you assignment.
int[] y = new int[array.length];
Your method will not be valid, since the array passed will remain unchanged. You need to do the sorting in place, i.e. without creating a new array. So that if you pass it from your main method, it gets sorted and you can print it there.
Bubble sort should use a swap method, so you just need one temporary variable.
In order to print the array, in your main method you'll need
//code that initializes the array or whatever
sort(myArray);
System.out.println(Arrays.toString(myArray)); //print the array modified by the previous method call
Also note what #A4L said about your local array. Work with the array you pass as parameter to your method, don't create a new one.
Arrays.sort() modifies the array you pass in. So if you iterate over the array object and print the elements AFTER your call to Arrays.sort(), it will print for you.
Since you have a void sort method, you want it to sort the array as a side effect. That is, modify the values in the int[] array reference you passed as a method parameter. Then you can print it from main.
I am using 2 classes and a bunch of methods to store something in an array then writing it to a file. After I write something to a file, instead of being of the var double,
this is my code:
public void storeArray(Quest1 a, Quest2 b, String filename) throws FileNotFoundException{
PrintWriter k = new PrintWriter(filename);
for(int i = 0; i < a.getDays(); i++)
{
k.println(b.storeArr(a));
}
k.close();
System.out.println("Written.");
}
Quest 1 is a class, Quest 2 is a class and String filename is just getting passed through.
After doing all that and putting the Quest3 object in my main menu.
I run the program, input all my values etc which get put into an array in the class Quest 2 and then I write them to a file.
I open that file to check if it has worked and i get this:
[D#264532ba
How do I fix that to get my double variables in the file?
Print out Arrays.toString instead of just print out the array (which invokes its toString inherited from Object):
k.println(Arrays.toString(b.storeArr(a)));
Or if you want some custom format, you can use StringUtils.join from Apache Commons. Or, perhaps just write a loop if you cannot use any dependencies.
The thing you output is the toString of the array, which is its type ([D) + # + its hash code (264532ba).
Arrays use the default implementation of toString() and that's why the output of the array is:
[D#264532ba
You have two options to print an array's content:
Iterate over each element.
Use Arrays.toString(array).
Explanation of the weird output
Let me explain the following code:
double[] array = new double[10];
System.out.println(array);
array is an object, hence you are calling println(Object) of PrintStream (System.out), which calls toString() on the passed object internally. The array's toString() is similar to Object's toString():
getClass().getName() + "#" + Integer.toHexString(hashCode());
So the output would be something like:
[D#756a7c99
where [ represnts the depth of the array, and D refers to double. 756a7c99 is the value returned from hashCode() as a hex number.
Read also Class.getName() JavaDoc.
if storeArr returns an Array, you could use Arrays.toString(b.storeArr(a))
This here:
k.println(b.storeArr(a));
You are printing b.storeArr(a) which is an array object.
Just do this:
PrintWriter k = new PrintWriter(filename);
for(int i = 0; i < a.getDays(); i++)
{
b.storeArr(a);
k.println(Arrays.toString(b));
}
Below is an example program from some notes on how to use the for loop in Java. I don't understand how the line element:arrayname works. Can someone briefly explain it, or provide a link to a page that does?
public class foreachloop {
public static void main (String [] args) {
int [] smallprimes= new int [3];
smallprimes[0]=2;
smallprimes[1]=3;
smallprimes[2]=5;
// for each loop
for (int element:smallprimes) {
System.out.println("smallprimes="+element);
}
}
}
It's another way to say: for each element in the array smallprimes.
It's equivalent to
for (int i=0; i< smallprimes.length; i++)
{
int element=smallprimes[i];
System.out.println("smallprimes="+element);
}
This is the so called enhanced for statement. It iterates over smallprimes and it turn assignes each element to the variable element.
See the Java Tutorial for details.
for(declaration : expression)
The two pieces of the for statement are:
declaration The newly declared block variable, of a type compatible with
the elements of the array you are accessing. This variable will be available
within the for block, and its value will be the same as the current array
element.
expression This must evaluate to the array you want to loop through.
This could be an array variable or a method call that returns an array. The
array can be any type: primitives, objects, even arrays of arrays.
That is not a constructor. for (int i : smallPrimes) declares an int i variable, scoped in the for loop.
The i variable is updated at the beginning of each iteration with a value from the array.
Since there are not constructors in your code snippet it seems you are confused with terminology.
There is public static method main() here. This method is an entry point to any java program. It is called by JVM on startup.
The first line creates 3 elements int array smallprimes. This actually allocates memory for 3 sequential int values. Then you put values to those array elements. Then you iterate over the array using for operator (not function!) and print the array elements.
I have several arrays in a class
I want to implement toString() to print all values.
How to do this?
public String var1[];
public int var2[];
public String var3[][];
public int var4[];
public int var5[][];
public String toString() {
for(String s : var1) {
System.out.println(s.toString());
}
return null;
}
That prints all var1[] content but how to print all?? Do I have to put a loop for every one of them?
You can use the Arrays.toString() static helper method as follows:
String lines[] = getInputArray();
System.out.println(java.util.Arrays.toString(lines));
I think what you are looking for is Arrays.deepToString()
Refer to this link for more details. It takes an array and calls toString() on every element.
First of all, it depends on the size of your arrays. You did not mention any size for each of it. Of course, we can use for each. The second question obviously, how to want to print them all in the screen. that is the matter.
In case, if you go with normal for loop [ex: for(int i=0;i<ar.length();i++)] in this case. You have to go by individual loop for each array.
If your array size is same for all. You can simply use one loop to iterate all of them to print it off.
Hint: don't forget to handle the ArrayOutofBound exception. You would need that :P
String someArray = new String[] {"1", "2"};
String toString = Arrays.asList(someArray).toString();
The code above will print out the toString in a more readable format:
[1, 2]
If you are using JDK 1.5, you can use:
String[] strings = { "ABC", "DEF" };
String s = Arrays.toString(strings);