Printing array error - java

This is probably a simple fix, but I am just not seeing it. I am trying to figure out, how do I get my printOut() method to print properly from the main Project5PartA? Do I need get, set, and return methods? Also, is my while loop even necessary in the Tester class?
The program compiles and keeps running to infinity, so I guess the while loop is wrong. But it also only prints out [Ljava.lang.String;#7c1c8c58 continuously on each line.
The classes that extend the main are irrelevant and part of the project. Apologies if this was posted wrong and thanks for any help.
The output of the whole program would be similar to:
Bark, bark.
Meow, meow.
Roooaaar.
Dog says woof, woof.
Cat says meow, meow.
Tester Class:
public class Tester {
String[] animalArray = {"Dog", "Cat", "tRex", "Cow", "Pig", "Snake",
"Goat", "Owl", "Chicken", "Frog"};
String[] noiseArray = {"Woof, woof", "Meow, meow", "Roooaaar", "Mooo",
"Oink, oink", "Hissss", "Baaa", "Hoot, hoot", "Bock, bock",
"Ribbit, ribbit"};
String[] printArray = new String[10];
public String printOut() {
while (true) {
for (int i = 0; i < 10; i++) {
String value = (animalArray[i] + " says " + noiseArray[i] + ".");
printArray[i] = value;
System.out.println();
System.out.println(printArray);
break;
}
}
}
}

Use Arrays.toString() to print the contents of an array. Don't actually print the array itself.
System.out.println(printArray); // Prints [Ljava.lang.String;#7c1c8c58
System.out.println(Arrays.toString(printArray0); // Prints [Dog says Woof, woof...]
If you do use Arrays.toString(), print the array outside the loops.
You could also just print each part of the array with System.out.println(printArray[i]) inside the loop.
public String printOut() {
while (true) {
for (int i = 0; i < 10; i++) {
String value = (animalArray[i] + " says " + noiseArray[i] + ".");
printArray[i] = value;
System.out.println();
System.out.println(printArray[i]); // This works
break;
}
}
System.out.println(Arrays.toString(printArray); // Also works
}

Because printArray is array and doesn't have a toString() method you will have to print out each element seperatly or use Arrays.toString(printArray) method.
Something like this will get you a growing array if it's in the while loop. Place it outside the while loop:
System.out.println(Arrays.toString(printArray));
Or in the while loop:
System.out.println(printArray[i]);

You don't need the while loop unless you really want your program to run forever.
You should change your print statement as follows. (You were printing the array object, not the array contents.)
System.out.println(printArray[i]);

Related

Can't figure out why I am getting null values

The program is supposed to print out the amount of times each name has been selected (this is indicated by number of asterisks (*). I have most of the code working but for some reason the output contains two null values for each name and I am not sure how to fix the problem. Also if you have the time, I'm also struggling to find out which name has the most amount of asterisks. Here's an example output:
1: nullnull************************ Conner
2: nullnull********************************** John
etc...
(it does this for all 10 names)
public class RandomStudentsLab {
public static void main(String[] args){
//create an array with 10 students
String [] StudentList = new String[10];
String [] StarString = new String[10];
String [] FinalString = new String[10];
//add 10 names to the student list
StudentList[0] = "Conner";
StudentList[1] = "John";
StudentList[2] = "Alex";
StudentList[3] = "Robert";
StudentList[4] = "James";
StudentList[5] = "Carl";
StudentList[6] = "Sarah";
StudentList[7] = "Bob";
StudentList[8] = "Ethan";
StudentList[9] = "Chris";
//loop 250 times selecting each student randomly
for(int i=0; i<250; i++){
int randomNum = (int)((Math.random()*10));
for(int x=0; x<10; x++){
if(randomNum == x){
StarString[x] += "*";
}
}
}
for(int z=0; z<10; z++){
System.out.println((z+1)+": "+(FinalString[z] += StarString[z] + " "+StudentList[z]));
}
}
}
Elements in FinalString and StarString arrays are still not initialized. So with += operator its calling toString on the null element and prefix "null" to each string.
As mentioned by Karthik in his answer you never initialized (as in you never assigned values) the FinalString array. That is what is causing your error.
You can easily tell since your System.out.println() is printing:
Number : nullnull Stars Name
So clearly your issue is with FinalString, it is the only variable not printing correctly.
System.out.println((z+1)+": "+(FinalString[z] += StarString[z] + " "+StudentList[z]));
You are making the same mistake with the StarString array. You are lucky enough to get away with it in this case since you end up adding variables to StarString in your loop.
However, NOT initialising ANY variable is >>horrible<< practice. You never know what was previously stored in memory, this could lead to your variables being assigned some 'alien' data that was leftover on the memory by some other program. Secondly, and this is the issue in your question, if you forget to initialise you can run into null errors and such.
So as a matter of good coding practice always initialise your variables to something. Even if you are using the variable two lines later - it doesn't matter. When you create your variable assign it a value:
If it's an integer then 0 or -1. It's better if it's a value that won't occur in your program, so if you have an error in your code you can spot it easily because your integer will be -1 instead of x y z.
If it's a string then name it 'banana' or 'peanuts' or whatever.
If it's an object make sure you initialise all of the attributes
And so on...
P.S. Not sure if I came accross as harsh, but it's absolutely not my intention. Good coding practices are simply important and will be extremely helpful in the future.
Best of luck!
EDIT:
Little update to reflect your comment on another answer.
When you create FinalString here String [] FinalString = new String[10]; your are not assigning any values to it, unlike what you did with the names.
So when your code gets to the final for loop here:
for(int z=0; z<10; z++){
System.out.println((z+1)+": "+(FinalString[z] += StarString[z] + " "+StudentList[z]));
}
}
}
And you try to do a System.out.println() for FinalString[z], well FinalString[z] still does not have a value. At no point in your code did you write
FinalString[0] = "Banana";
So obviously it will print null instead.

Changing the value inside an Array List?

for(int i = 0; i <= gameWord.length()-1; i++)
{
if(guessLetter.charAt(0) == (gameWord.charAt(i)))
{
hideword[i] = guessLetter.charAt(0);
}
else if(guessLetter.charAt(0) != (gameWord.charAt(i)))
{
System.out.print("_" + " ");
}
}
I am making a hangman game and I have created an array list called hideword. Hideword prints an underscore for each letter that is in the word used for the game. I am trying to right a method that will swap the underscore with a letter the user guesses. However this code
hideword[i] = guessLetter.charAt(0);
Doesn't work. It gives me "array required, but java.util.ArrayList found
Anyone help?
Then, hideword must be an arraylist. Use hideword.set(index, character) for assignment instead of accessing it like an array.
An ArrayList is not an array, it's a List implementation (however, its implementation is backed by an array - hence the name).
Declare hideword as an array of char:
private char[] hideword;
and initialize it before use:
hideword = new char[gameword.length];
You code, without changing its basic intention, can be simplified greatly:
There's no need to subtract 1 from the length, just change the comparison operator
There's no need to have your if in the else - we already know it's not equal because we're in the else block
Rather than do useless print, assign an underscore to the array slot
Do one print at the end
Like this:
for (int i = 0; i < gameWord.length(); i++) {
if (guessLetter.charAt(0) == (gameWord.charAt(i))) {
hideword[i] = guessLetter.charAt(0);
} else {
hideword[i] = '_';
}
}
// print hideword
You code would be simpler still if hideword didn't exist and you simply System.out.print() each character as you test it instead.

Returning Words Within a String Array

I created a method to output a String. Using the split method and a for loop, I added each word in my sentence into a String array, replacxing the last two letters of each word with "ed". Now, my return statement should return each of the words. When I used System.out.print, it worked. When I use a return and call it in my main method, I get this output: "[Ljava.lang.String;#1b6235b"
The error seems so simple but I just don't know where I'm going worng. Any help would be appreciated.
Here is my method:
public String[] processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
// System.out.print(words[i]);
}
}
return words;
}
You are printing arrays but arrays don't have a proper implementation of toString() method by default.
What you see is
"[Ljava.lang.String;#1b6235b"
This is [Ljava.lang.String; is the name for String[].class, the java.lang.Class representing the class of array of String followed by its hashCode.
In order to print the array you should use Arrays.toString(..)
System.out.println(Arrays.toString(myArray));
A good idea however, it returns my Strings in an Array format. My aim
is to return them back into sentence format. So for example, if my
input is, "Hey my name is Fred", it would output as, "Hed ed naed ed
Fred". Sorry, I forgot to add that it also seperates it with commas
when using Arrays.toString
Then you should modify your processInfo() returning a String or creating a new method that convert your String[] to a String.
Example :
//you use like this
String [] processInfoArray = processInfo();
System.out.println(myToString(processInfoArray));
// and in another part you code something like this
public static String myToString(String[] array){
if(array == null || array.length == 0)
return "";
StringBuilder sb = new StringBuilder();
for(int i=0;i<array.length-1;i++){
sb.append(array[i]).append(" ");
}
return sb.append(array[array.length -1]).toString();
}
As much as I can get from your question and comment is that your aim is to return them back into sentence format. So for example, if your input is, "Hey my name is Fred", it would output as, "Hed ed naed ed Fred".
In that case you should return a String, and not an array. I have modified your method a bit to do so. Let me know if you wanted something else.
public String processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
sentence = "";
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
sentence += " " + words[i];
// System.out.print(words[i]);
}
}
return sentence.trim();
}
Your commented out call to System.out.print is printing each element of the array from inside the loop. Your method is returning a String[]. When you try to print an array, you will get the java representation of the array as you are seeing. You either need to change your method to build and return a string with all the array entries concatenated together, or your calling code needs to loop through the returned array and print each entry.

How to loop through an array and check for duplicates?

I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.

return a series of print statements within a for loop

I have a class which contains an array list of which the user will enter its elements. I think I can successfully add elements to this array list but I cannot tell as I cannot output the array list. I want to call the method viewNYC in the main programme and for it to display a list of its elements in cmd prompt. Can any one help?
import java.util.*;
class Hotels{
public static ArrayList NYC = new ArrayList();
public static String[] NYCArray = (String[])NYC.toArray(new String[NYC.size()]);
public static void addNYC(String hotel){
String NYChotel = hotel;
NYC.add(NYChotel);
}
public static void viewNYC(){ //Will be called in main programme
for(int i=0; i< NYCArray.length; i++){
return System.out.println(i+1 + ") \t" + NYCArray[i]);
}
}
}
The return type of viewNYC is void. Remove the return keyword in your for loop:
for (int i = 0; i < NYCArray.length; i++) {
System.out.println(i + 1 + ") \t" + NYCArray[i]); // no "return"
}
Is your program compiling becuse it should through a compile error(Void methods cannot return a value) at
return System.out.println(i+1 + ") \t" + NYCArray[i]);
because
System.out.println()
doesnot return anything. If you want to print an array use
System.out.println(Arrays.deepToString(NYCArray));
First of all, remove the return statement from the sysout:
System.out.println(i + 1 + ") \t" + NYCArray[i]);
in addition, if I read your code I can see that you have a static String[] NYCArray which will not be updated in your code example.
So if you addNYC a hotel, it will not be visible in NYCArray, this update should be done at the end of the addNYC
(Create a new Array with the new size of the ArrayList and set the content to your ArrayList's content)
You are indeed adding elements to NYC, but those changes will not be reflected in NYCArray.
The line:
public static String[] NYCArray = (String[])NYC.toArray(new String[NYC.size()]);
will declare NYCArray as an array of Strings, and set its initial value to an array "copy" of NYC. However, the line will only run once, and at that point NYC is still empty!
If you want to print the contents of NYC, do something like:
System.out.println(Arrays.toString(NYC.toArray()));
Unless you have a very good reason for keeping it, I would get rid of NYCArray entirely.

Categories

Resources