Printing content of an Array in Java - java

This generates the array.
public word (String file)
{...
public int[] getArray()
{
int[] array = {... } ;
return array;
}
}
And I need to reference that array in another class
public static void main()
{
word numarray = new word("doc.txt");
int [] heightarray = numarray.getArray();
System.out.println(heightarray);
}
I'm not getting any errors but I get things like [I#1a6fa30c as a result.

What you are getting in the output is the hashcode of the array. In order to print the contents of the array you can you either of the below options :
Option 1 : Print the elements one by one using a loop a below :
for(int val : heightarray)
{
System.out.print(val + ",");
}
Option 2 : Use Arrays utility class for printing the array
System.out.println(Arrays.toString(heightarray));

You can print it using the Arrays.toString() method:
System.out.println(Arrays.toString(heightarray));

Related

Moving indices in an array

I am trying to write a write a program that receives an String[] and prints out the array with the first string alphabetically first. I have to use three methods like these. Here is a sample input/output:
bob, joe, aaron, zack ----> aaron, bob, joe, zack
findFirstName() is correctly finding the first String alphabetically and returning its location.
MoveToRightOne is correctly shifting each String right one while overwriting the first string alphabetically and repeating the first one (ex: bob bob joe zack).
moveName() is not working correctly. It is supposed to replace the first instance of "bob" with "aaron" but is usually off by one or two places.
Does anyone see why this might be happening in moveOne()?
public static String [] moveName(String [] names) {
String names1 [] = names.clone();
int firstPosition = findFirstName(names1);
String[] NewNames = moveToRightOne(names1, firstPosition, firstPosition+1);
String firstAlph= names1 [firstPosition];
System.out.println(names1 [firstPosition]);
NewNames [0] = firstAlph;
return NewNames;
}
public static int findFirstName(String[ ] names1 ) {
// receives an array of Strings, and returns the location (i.e. index) of the first
// name (alphabetically)
String first=names1[0];
int firstPosition = 0;
for (int i=0; i<names1.length; i++) {
int result =names1[i].compareToIgnoreCase(first);
if (result < 0) {
first= names1[i];
firstPosition = i;
}
}
return firstPosition;
}
public static String[] moveToRightOne (String[] names, int startSpot, int endSpot) {
for (int i = (startSpot - 1); i >= 0; i--) {
names[i+1] = names[i];
}
return names;
}
moveToRightOne does not make a copy of the names array that you pass in. Instead, it modifies it directly. That means when you say
String[] NewNames = moveToRightOne(names1, firstPosition, firstPosition+1);
the strings will be shifted in names1, and after that, NewNames and names1 will just be references to the same array. I think your intent is to make NewNames be an array with the strings shifted, and leave names1 alone, but that isn't what's happening. That means that the following statement is going to return the wrong string:
String firstAlph= names1 [firstPosition];
(Or, since names1 is already a clone of names, maybe what you want is to use names instead of names1 when trying to access elements from the not-yet-shifted array.)
Your moveToRightOne function was broken, so you were not actually using all the parameters passed in. Also, you should grab the first name alphabetically before you actually overwrite it using that function.
public class Shift {
public static void moveName(String [] names) {
int firstPosition = findFirstName(names);
// Store the name at that position
String firstName = names[firstPosition];
moveToRightOne(names, 0, firstPosition);
names [0] = firstName;
}
public static int findFirstName(String[] names1) {
// receives an array of Strings, and returns the location (i.e. index)
// of the first name (alphabetically)
String first=names1[0];
int firstPosition = 0;
for (int i=0; i<names1.length; i++) {
int result =names1[i].compareToIgnoreCase(first);
if (result < 0) {
first= names1[i];
firstPosition = i;
}
}
return firstPosition;
}
public static void moveToRightOne (String[] names, int startSpot, int endSpot) {
for (int i = (endSpot - 1); i >= startSpot; i--) {
names[i+1] = names[i];
}
}
public static void main(String[] args) {
String[] original = new String[] { "bob", "joe", "aaron", "zac"};
for (String s: original) System.out.println(s);
System.out.println();
moveName(original);
for (String s: original) System.out.println(s);
}
}
Are you sure the moveToRightOne is correct? (if firstPosition is 0 you will get no changes as the for loop will not execute)
Just a quick Thought:
If you are looking do a sort manually (I assume this is for a class). I will also assume you are trying to implement insertion sort algorithm (otherwise Arrays.sort() is your friend). The way you are approaching it, it looks like you will be making multiple passes through the array to achieve a sort. if you want to do that switch to bubble sort instead.
The description of the insertion sort code will look something like this:
Start looping through your array, compare that the element at index is greater than element at index + 1. if not true move to the next element. if true compare the smaller element (call it A) to all previous elements until it is greater than the next previous element (lets call it B). Save a copy of A Shift all elements after B to the right (by 1) until you get to the A's old position . insert the copy of A into position just after B. Continue from the old A's index. Rinse/repeat until the end of the array
you may want to simplify your code in that case (and always check for edge conditions like 0 and Array.length)
HTH
Please use Arrays.sort() for sorting instead.This is not exact solution for the problem, but an alternate way for it.
import java.util.Arrays;
public class Test{
Public static void main(String args[]){
String str[]= {'Mike','Adam','Peter','Brian'};
System.out.println("str"+str[0]); // Mike
Arrays.sort(str);
System.out.println("str"+str[0]); //Adam
}
}

Bubble Sorting string in an array

I'm trying to bubble sort string data that was input into an array in descending and ascending order.
The following is the code so far:
import java.util.*;
public class nextLineArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String names[]=new String[12];
System.out.println("Enter the 12 names: ");
//Load Array
for(int i = 0; i < 12; i++)
{
names[i] = input.nextLine();
}
//Print initial list
System.out.println("List of names via input:"+ names);
//Print descending order list
String descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): "+descSort);
}
public static String bubbleSortDesc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i+1]);
if(result>0)
{
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
}
When I try to return the sorted array to the main method it gives me the following error on the return line:
Incompatible Types
Our online instructor just started us out with using multiple methods and arrays at the same time and it is quite confusing...please excuse me if any of my mistakes appear to be obvious.
Edit: I have fixed the initial problem thanks to Alexandre Santos in the comments, I am now running into a problem when executing the program after inputting the data, instead of printing the strings in the array it prints out
[Ljava.lang.String;#6d782f7c
Take a look at the method
public static String bubbleSortDesc(String[] names)
The return of that method is supposed to be a String (only one), but you are returning the parameter "names", which is an array of strings. The "[]" after the String identifies it as an array.
I am not going to do your homework for you, so a hint: check if the return type of the method bubbleSortDesc should be one String or an array of Strings.
Good luck.
There are 2 points to fix. First you should return String array
public static String[] bubbleSortDesc(String[] names)
and therefore you should define it like this:
String descSort[];
public static String bubbleSortDesc(String[] names)
should be
public static String[] bubbleSortDesc(String[] names)
and also declare descSort as String array.
Also you are just printing the array objects. This will not print the list for you. You have iterate over the array.
Include this in you code:
for (String name:names)
{
System.out.println(name);
}
Do the same for descSort too....
You can fix your print command by changing it to the following:
System.out.println("Names listed sorted in descending order (via BubbleSort): "+ java.util.Arrays.deepToString(descSort));
If you want the nitty gritty, descSort is a String[]. In Java when you convert String[] into a String it gives you that crazy string representation. You have to instead converte each entry in the array to a String individually. Fortunately the deepToString method will do that for you.

Insertion Sort using an array list java

I have no idea how to get my new list to print
import java.util.ArrayList;
import java.util.List;
public class InsertionSort {
public static int insertion(List<String> sorted) {
sorted = new ArrayList<String>();
String list[] = {"Banana","Pear","Apple","Peach","Orange"};
String temp="";
int f = list.length;
for(int i=0;i<f;i++){
for(int j=i+1;j<f;j++){
if(list[i].compareToIgnoreCase(list[j])>0){
temp = list[i];
list[i]=list[j];
list[j]=temp;
}
}
}
System.out.print(list);
return list[].InsertionSort;
I keep getting this error for the line above
1 error found:
InsertionSort.java [line: 22]
Error: class expected
}
}
You want to use the for-each loop, it will look like so :
for ( String i : list){
System.out.print(i);
}
You can't print out the array like you did here:
System.out.print(list); // DOES NOT WORK
Because println takes in a variety of parameters, but not an array( although one version takes an array of chars ). See the API
But if you said,...
System.out.print(list[1]);
for example, it would compile..
You have other issues to fix though..
return list[].InsertionSort //what's mean is code?
if you want to print list you can like this:
for(String str:list) //this list is list<String>
{
System.out.println(str);
}

Reading ints from a txt file and storing to an array

I am trying to read integers from a text file and store them into an array. The text file reads:
4
-9
-5
4
8
25
10
0
-1
4
3
-2
-1
10
8
5
8
Yet when I run my code I get [I#41616dd6 in the console window...
public static void main(String[] args) throws IOException
{
FileReader file = new FileReader("Integers.txt");
int[] integers = new int [100];
int i=0;
try {
Scanner input = new Scanner(file);
while(input.hasNext())
{
integers[i] = input.nextInt();
i++;
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(integers);
}
You're printing out the virtual memory address of the array instead of the actual array items:
You can print out the actual array items, one by one, like this:
// This construct is called a for-each loop
for(int item: integers) {
System.out.println(item);
}
#akuhn points out correctly that Java has a built in helper for this:
System.out.println(Arrays.toString(integers));
Note that you'll need to add:
import java.util.Arrays
in your imports for this to work.
Unfortunately, Java’s designers missed to add a proper string representations for arrays.
Instead use
System.out.println(Arrays.toString(integers));
You need to import java.util.Arrays; to make this work.
instead of this
System.out.println(integers);
try this
System.out.println(integers[0] + " : " + integers[1]);
you need to print actual values in integers[] array not array itself
If using an int array is not a restriction, then i would suggest use List. You can use it like this :
List<Integer> integers = new ArrayList<Integer>();
Scanner input = new Scanner(file);
while(input.hasNext()){
integers.add(scanner.nextInt());
}
System.out.println(integers);
Output : [1,2,-1,23]
Whenever you pass any object to System.out.println(), it prints the toString() for that object. If its not overridden, it prints the memory address of that object.
System.out.println(integers);
is trying to print toString() representation of integer array which is nothing but the JVM address of this array.
To print the actual numbers in the array, you either need to iterate through the array or convert the array to java.util.ArrayList.(which has the toString() method implemented.)
This should help you to read Integer from a file and store it in array
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
public class filetoarray {
public static ArrayList<Integer> read(File f)
{
ArrayList<Integer> array=new ArrayList<Integer>();
try
{
Scanner sc=new Scanner(f);
while(sc.hasNextLine())
{
array.add(sc.nextLine());
}
}
catch(Exception e)
{
System.out.printf("ERROR : %s", e);
}
return array;
}
public static void main(String[] args) {
File file1=new File("file1.txt");//your file path here
ArrayList<Integer> array1;
array1=read(file1);
System.out.println(array1);
}
}

how can we access individual int value from LinkedHashset<set<Integer>? Through string is it possible

I want to remove duplicates e.g.{ {1,2,3}, {2,3,1},{3,2,1},{2,1,3} } are duplicates of {2,3,1} or any one from given 4 sets.for this i converted 2D Integer array into LinkedHashSet which removed duplicates but when i am converting back to array (due to need in algorithm) i am unable to access individual elements.is it possible? if not, what is the other way.if yes what is problem in the code.given below.please resolve.
my own other thinking: as i think through string is it possible?
e.g { {2,3,1},{-3,-2,-4},........... } insert in Set making ArrayList of each 3 element set e.g.{2,3,1},{-3,-2,-4},{3 element}, .....and then parseInt to access individual element as {2},{3},{1},{-3},{-2},{-4},... will it work?
import java.util.*;
class demo
{
Integer[][] orderedpair3k={{1,2,3},{1,3,-2},{2,3,-1},{1,2,3},{1,-3,-2},{2,-3,-1},{1,-2,-3},{1,3,2},{-2,3,-1},{1,-2,3},{1,-3,2},{-2,-3,-1}};
Set<Set<Integer>> r = new LinkedHashSet<Set<Integer>>();
Object[][] a;
public void init_clauses()
{
removeDuplicate();
System.out.println(r);
backToArray();
for(int i=0;i<a.length;i++)
System.out.println(a[0][i]);
}
public void removeDuplicate()
{
int i=orderedpair3k.length;
for(int j=0;j<i;j++)
r.add(new LinkedHashSet<Integer>(Arrays.asList(orderedpair3k[j])));
}
public void backToArray()
{
ArrayList<Set<Integer>> arr=new ArrayList<Set<Integer>>(r);
a = new Object[arr.size()][3];
for(int i=0;i<a.length;i++)
a[i]=arr.toArray(new Object[i]);
}
}
public class sat
{
public static void main(String[] arg){
demo S = new demo();
S.init_clauses();}
}
//in the above code i am unable to access individual element because in the array Set is inserted as Object even i tried using ((Integer)a[i][j]).intValue() i think this is due to Arrays.asList(orderedpair3k[j]) how this problem can be resolve?
Seems quite straightforward:
Integer[][] result = new Integer[r.size()][3];
int c = o;
for (Set<Integer> s : r)
result[c++] = s.toArray(new Integer[3]);

Categories

Resources