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.
Related
I need to create a random maze of 1s and 0s, and it does not have to be possible to solve. The program I am writing needs to be able to search through this maze and tell me whether not it is possible to get from the beginning to end. 0s are fine to go through, but 1s are like walls. Currently I am just trying to create the random array, and what I have so far compiles, but it returns this: [[I#4ea20232. So far I have this:
import java.util.Random;
public class SearchMaze{
public static void main(String [] args){
int n = 8;
int m = 7;
int[][] maze = new int[n][m];
Random rand = new Random();
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
maze[i][j] = rand.nextInt(2);
System.out.println(maze);
}
}
I am trying to get something like this:
1000000
1111100
0000001
1110111
1010101
1010101
0000110
1110000
I can't seem to find why something like this wouldn't work.
The problem is that the toString of an array returns useless information. Using a list will not help much because it will print everything on one line with commas. Try to use nested loops to output the data.
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
System.out.print(maze[i][j]);
}
System.out.print('\n');
}
When you print an object like System.out.println(a);, you're really calling the toString() method of that object. Thus you're really calling System.out.println(a.toString());.
The toString() method of Arrays isn't particularly useful, so by doing System.out.println(maze) you're not going to see anything informative.
Fortunately, the Arrays class has helper methods that can reduce your problem to a single line. Try using:
System.out.println(Arrays.deepToString(maze));
Given that your maze is 2d, you can use some replaceAll calls to format it like your post:
System.out.println(Arrays.deepToString(maze)
.replaceAll("],\\s\\[", "\n")
.replaceAll(",\\s|]|\\[", "")
);
Instead filling the maze with random values, you need to start will all 1s and fill it with random paths e.g. going north or east for a given length.
Just like the loops you have you need to print them this way too.
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
System.out.print(maze[i][j]);
}
System.out.println();
}
Not the answer to your problem, as it has already been answered, but how do you know where to begin and where to end?
Anyway, I came here to steer you towards the A* algorithm - it's a path finding algorithm that would be great for this type of application.
I think a better solution would be to create an object for the maze:
public class Maze {
public Maze(final int[][] maze) {
this.maze = maze;
}
#Override
public String toString() {
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[i].length; j++) {
builder.append(maze[i][j]);
}
builder.append("\r\n");
}
return builder.toString();
}
private final int[][] maze;
}
I am trying to reverse all the strings in an array in java, but seem to over write all of them with the first.
private static void palindrome(String[] s) {
int flag=0;
String reverse;
for(int i=0;i<n;i++) // n is declared globally as number of strings
{
reverse="";
for (int j=s[i].length()-1;i>=0;i--)
reverse=reverse+s[i].charAt(j);
if(s[i].equals(reverse))
{
System.out.println(s[i]);
flag=1;
}
}
if(flag==0)
System.out.println("There are no palindromic strings");
}
This line looks wrong:
for (int j = s[i].length()-1; i >= 0; i--)
It should be:
for (int j = s[i].length()-1; j >= 0; j--)
In other words: the indexes in the inner loop are mistaken, they should be using j instead of i. As a side comment - here's a simpler way to reverse a string:
reverse = new StringBuilder(s[i]).reverse().toString();
Try these steps:
String[] strDays = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday"};
List<String> list = Arrays.asList(strDays);
Collections.reverse(list);
strDays = (String[]) list.toArray();
Looks like you used i instead of j in the inner loop.
for (int j=s[i].length()-1;j>=0;j--)
reverse=reverse+s[i].charAt(j);
I'd advise you to break even this small problem into chunks.
Write a separate method that reverses a single String. Get that working and tested. Only then should you iterate over a collection or array and apply it to each member.
You'd have an easier time debugging this if you did it in smaller steps. The fact that your string reversing method was borked would have been apparent right away.
You shouldn't write stuff to System.out like that from methods.
public static String reverse(String s) {
StringBuilder reversed = new StringBuilder(s.length());
// reverse one string here
return reversed.toString();
}
public static String [] reverseAll(String [] originals) {
String [] reversed = new String[originals.length];
for (int i = 0; i < originals.length; ++i) {
reversed[i] = reverse(originals[i]);
}
return reversed;
}
Your inner loop should be:
for (int j=s[i].length()-1; j>=0; j--){
reverse=reverse+s[i].charAt(j);
// ... //
}
for (int j=s[i].length()-1; j >=0; j-- )
### ###
you need to correct your inner loop. Instead of i you need to use loop variable j.
Why are you using this:
for (int j=s[i].length()-1;i>=0;i--)
You should use this instead:
for (int j=s[i].length()-1;j>=0;j--)
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!
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]);
}
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]);
}
}
}
}