Java: Array List Printing object reference instead of array [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I'm am very much a rookie when it comes to coding. What I'm trying to accomplish is to load grades from a txt file and put them into an existing array.
I have actually solved this. and In the program the array does retain the values. But when I got to print them I get the object reference aka [I#5c647e05 rather than the array. Below is my code.
public static void main(String[] args) {
int[] list = new int[15];
Scanner in = null; // create a scanner object
loadGrades(in, list);
System.out.println(list);
}
public static void loadGrades(Scanner in, int[] list) {
int grades; // int variable
try { // try
in = new Scanner(new FileReader("Proj5Data.txt"));// change filename
} catch (FileNotFoundException ex) { // catch
System.out.println("File not found");
System.exit(1);
}
for (int i = 0; i < list.length; i++) {
grades = in.nextInt(); // var
list[i] = grades ;// put the int in the array at the counter value
}
in.close();
}
Print results as:
[I#5c647e05
BUILD SUCCESSFUL (total time: 0 seconds)

When you print an array behind the scenes the method toString() is being called and it doesn't print the content of the array (which is too bad IMO). But you can easily get over it using the library Arrays:
System.out.println(Arrays.toString(list));

You can't print the contents of a list like that in Java. You need to loop over the contents of the array and print them individually.
for(int i : list){
System.out.println(i);
}

System.out.println(list) uses a .toString() method to resolve what to print.
You can either use Arrays.toString(list) or print it one by one.

So All the methods you guys gave me did indeed work. But I ended up just using printf to print them out. Thanks for the help though.

Related

how to make an array function return a value [duplicate]

This question already has answers here:
How can I convert List<Integer> to int[] in Java? [duplicate]
(16 answers)
Closed 2 years ago.
So to summarize my problem, I want the function int[] get_marks() to be able to return the array, but I don't know how to get my ArrayList marks to convert into an array which I can use the return thing for. I need the arraylist to be converted because I need to be able to find the frequency and mode of the array (parts of the code I have not started because I can't figure out how to convert the arraylist).
Below is my comment less code so far.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
class Main {
public static int[] get_marks(){
Scanner input = new Scanner(System.in);
ArrayList<Integer> marks = new ArrayList<>();
final int FLAG = -1;
int entries = 0;
System.out.println("Enter your marks. Type -1 when done.");
while (entries != FLAG){
entries = input.nextInt();
if (entries >=0 && entries <= 100){
marks.add(entries);
} else if (entries == FLAG) {
break;
} else {
System.out.println("Invalid entry. Marks must be between 0-100.");
}
}
input.close();
System.out.println("Your Marks are: " + marks);
}
public static void main(String[] args) {
get_marks();
System.out.println();
}
}
There's no reason not to simply return an ArrayList<Integer> or even better a List<Integer>. If you insist on returning an int[], your question is a duplicate of this.
Why not just return the ArrayList marks?
public static ArrayList<Integer> get_marks(){return marks}
Also, you could make the method return void. Is there any reason you need it to return a value in main?
To elaborate, if you make it void, it will just do all the calculations and culminate in System.out.println("Your Marks are: " + marks);. Given your code, is that not what you want? If so, make get_marks() return void:
public static void get_marks() {//run the code, print the marks, etc.}
Why do you need the get_marks() method? You may not have posted all your code, but if this is all your code, just get rid of get_marks() and put it all in main(). If all main() does is call get_marks(), consolidate the methods.

Print all strings of array [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
Very new to Java and programming in general. trying to figure out how to print the contents of my array
public class GameClass {
public static void main(String args[]) {
String [] gameList = new String [] {"Call of Duty", "Skyrim", "Overwatch", "GTA", "Castlevania", "Resident Evil", "HALO", "Battlefield", "Gears of War", "Fallout"};
System.out.println(gameList[]);
}
}
You can use the util package for one line printing
System.out.println(java.util.Arrays.toString(gameList));
Should do the trick.
for(int i = 0 ; i <gameList.length; i ++)
System.out.print(gameList[i]+" ");
Just iterate each element and print:
for(String s : gameList){
System.out.println(s);
}
You can print out your array of games by using the following loop:
for(String game : gameList){
System.out.println(game);
}
This runs through each item in your gameList array and prints it.

Loop Array Making Me Loopy

So i have been at this same example problem for a week now. I know that it may
seem easy, but i am finding that the more i look at it or alter it, the more
confused i get. I feel like i am making this a lot more difficult than it
needs to be. The array that i loaded displays correctly in the Try-Catch section, but i need to display it in its own method, which i call listOfAges(). What would this look like? Any responses are appreciated, please help.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray;
int ageCount = 0;
int age;
String filename = "ageData.dat";
anArray = new int[50];
/* The file has 50 numbers which represent an employee's age */
try {
Scanner infile = new Scanner(new FileInputStream(filename));
while (infile.hasNext()) {
age = infile.nextInt();
ageCount += 1;
System.out.println(ageCount + ". " + age + "\n");
/*
* When i run just this, the output is correct...
*
* But i don't want the output here, i just want to gather
* the information from the file and place it at the bottom inside
* the method displayAges().*/
}
infile.close();
} catch (IOException ex) {
ageCount = -1;
ex.printStackTrace();
}
public void listOfAges() {
System.out.print(" I want to display the data gathered from ageData.dat in this method ");
System.out.print(" Also, i receive this error message when i try: 'Illegal modifier for parameter listOfAges; only final is permitted' ")
}
}
}
First, you have to store your values in your array:
while (infile.hasNext()) {
age = infile.nextInt();
anArray[ageCount] = age;
ageCount += 1;
}
Your next problem is that you defined your listOfAges() method inside your main() method. The definition must be outside. You also need to pass your array as an argument to your method so that you can iterate over the array values to print them:
public void listOfAges(int[] ages) {
// use a loop here to print all your array contents
}
So I'm assuming you want to display each element in the array in your method. Your first problem is that the main method is static and you're trying to call a method that isn't static (listOfAges). Change this by simply adding the word static to the method to make it static. You also put this method in the main method. You'll need to move it outside of the brackets.
Second, to display the content you need to loop through it but the array you're holding the data in needs to be outside of the main method. Instead of having
int[] anArray;
In the main method, delete that and move it above the declaration of the main method. You'll also need to make it a static variable.
static int[] anArray;
Finally in the listOfAges, add the code to loop through it.
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray.length + ". " + anArray[i]);
}
I'm not 100% sure what you're asking but here:
At
} infile.close(); } catch (IOException ex) { ageCount = -1; ex.printStackTrace(); }
In your While.infile loop you're closing your while loop on the } infile.close() instead of opening a new one. So just change it to { infile.close (); } instead...
Since I'm not sure what you're exactly asking this will be the best answer I can give youx , hope I helped.

I get a compile time error when accessing an ArrayList with a new method

I am attempting to access an ArrayList that was created in a different method within the same class. The scanner method pulls in data from a text file. The text file data appears this way: 123 12 1 43, with line breaks...
Currently, my method works to pull in the data, but does not compile after that method ends. I originally had the entire code within the same method and it worked fine. But I'd like to return the largest value by creating a new method within this class, and then create a tester class that will access this new method. Here is my existing code. Or if there is a better solution. I'm all ears.
public class DataAnalyzer {
public DataAnalyzer(File data) throws FileNotFoundException
{
List<Integer> rawFileData = new ArrayList<>();
FileReader file = new FileReader("info.txt");
try (Scanner in = new Scanner(file)) {
while(in.hasNext())
{
rawFileData.add(in.nextInt());
}
}
}
public int getLargest(rawFileData){
int largest = rawFileData.get(0);
for (int i = 1; i < rawFileData.size(); i++){
if (rawFileData.get(i) > largest)
{
largest = rawFileData.get(i);
}
}
for (Integer element : rawFileData){
if (element == largest)
{
System.out.print("This is the Largest Value: ");
System.out.print(element);
}
}
}
}
Your main issue is with your method declaration. It needs a type parameter:
public int getLargest(List<Integer> rawFileData)
Note the List<Integer>.
Now, there is already a method for this in the Collections utility class. You would do well to look over that link in detail - there are many useful methods there. To get the highest element from a Collection of Objects that have a natural order (such a Integer). For example
int largest = Collections.max(rawFileData)
So your method can be reduced to:
public int getLargest(List<Integer> rawFileData)
return Collections.max(rawFileData);
}
You need to think over your logic much more carefully before you begin to write code, for example, your first loop is good:
int largest = rawFileData.get(0);
for (int i = 1; i < rawFileData.size(); i++){
if (rawFileData.get(i) > largest)
{
largest = rawFileData.get(i);
}
}
You do exactly what any programmer would do. But then, instead of returning the largest when you find it, you for some reason loop again:
for (Integer element : rawFileData){
if (element == largest)
{
System.out.print("This is the Largest Value: ");
System.out.print(element);
}
}
Ask yourself what does this do? You have a List of, say, apples. You look at each one and compare them - finding the largest apple. You now have the largest apple in the List. You then loop over the List again looking for an apple that matches the apple you have already found. Why do this?
Further, you never return from the method. Your method is declared as returning an int; but you never do.
The missing type in your method definition is the problem here.
Change the method definition from
public int getLargest(rawFileData) {
....
}
to
public void getLargest(List<Integer> rawFileData) {
....
}
And the second for loop in the method is unnecessary. The largest integer is already stored in the variable "largest" and you can print it after the first for loop.

Sorting a randomized array in Java

I am trying to make an app for sorting a randomized array
I made some code and I can not see what is wrong with it that it returns wrong values
Notes: I am trying to learn programming. So don't suggest whole different ways of solving the problem. I just want to see what is wrong with this code so I can get better.
What RandomArrayCreator.create() returns is just an array of numbers in randomized order.
public class ArraySorter
{
public static void main(String[] args)
{
int[] siyahi = RandomArrayCreator.create();
int[] siralanmish = new int[siyahi.length];
for (int i=0;i<siyahi.length;i++)
{
for (int j=0;j<siyahi.length;j++)
{
for (int k=j+1;k<siyahi.length;k++)
{
if (siyahi[k]<siyahi[j]) j=k;
}
siralanmish[i]=siyahi[j];
siyahi[j]=siyahi.length+1;
}
System.out.println(siralanmish[i]);
}
}
}
I know you did not want suggestions but I'm going to offer one anyway.
Hopefully this will help guide you along the way, but still allow you to come up with your own solution.
Sort smallest to biggest.
did I have swap an element?
while I swapped an element
assume I did not swap an element
for element i in the array
is i > i+1?
if yes
swap the elements
I did swap an element
else
do nothing
Given that you mentioned you wanted to learn how to improve your current program, here are minimalist changes that will have your code produce a sorted array.
A few notes on the changes:
1.
if (siyahi[k]<siyahi[j]) j=k;
This I assume is for trying to swap the values at each indexes. Instead you are assigning the value of k to j which will cause problems with the entire for loop. I replaced this with the following:
if (siyahi[k]<siyahi[j])
{
int temp = siyahi[j];
siyahi[j] = siyahi[k];
siyahi[k] = temp;
}
This creates a temporary variable to store one of the values so that you can swap the value at each index without losing one of your values.
2.
siralanmish[i]=siyahi[j];
This was replaced with:
siralanmish[j]=siyahi[j];
This allows you to directly copy the values from the same index from the source array to the target array.
3.
siyahi[j]=siyahi.length+1;
This code will just fill up your array with the value of length+1 for your original array and you will lose your other values.
Your code with the fixes are below:
public class ArraySorter
{
public static void main(String[] args)
{
int[] siyahi = RandomArrayCreator.create();
int[] siralanmish = new int[siyahi.length];
for (int i=0;i<siyahi.length;i++)
{
for (int j=0;j<siyahi.length;j++)
{
for (int k=j+1;k<siyahi.length;k++)
{
if (siyahi[k]<siyahi[j])
{
int temp = siyahi[j];
siyahi[j] = siyahi[k];
siyahi[k] = temp;
}
}
siralanmish[j]=siyahi[j];
}
System.out.println(siralanmish[i]);
}
}

Categories