Skip to content
Advertisement

Array Only Prints Certain Elements and Not Others

I am currently in a Intro to Computer Language class and everyone few lessons I have to develop some minimal programs (we are given 5 different prompts and have to pick three of them to complete). Due to time, I moved on and completed a different program, but I still want to understand what is going wrong with this one. It is supposed to translate a given phrase into Pig Latin using for loops and different methods (as broken down in their template, which I cannot change, though I know there is a more efficient way). I can get the words in the phrases to translate, but when I print out the array (either by converting it to a string or running a for loop to print each element out separately) some of the elements only print the reference code. Could someone tell me what’s going on? Below is the code and then a sample of a few print outs.

JavaScript

Here are some of the printed responses:

Input: the rain in spain stays mainly in the plain Output: ethay ainray [Ljava.lang.String;@17c68925ay ainspay aysstay ainlymay [Ljava.lang.String;@17c68925ay ethay ainplay Expected: ethay ainray inay ainspay aysstay ainlymay inay ethay ainplay

Input: you should have stayed with the soup question OutPut: ouyay ouldshay avehay ayedstay ithway ethay oupsay uestionqay This print’s out correctly

Input: the stuff that dreams are made of Output: ethay uffstay atthay eamsdray [Ljava.lang.String;@17c68925ay ademay [Ljava.lang.String;@17c68925ay Expected: ethay uffstay atthay eamsdray areay ademay ofay

I cannot find an answer as to why this is happening. Please let me know if you need any additional information. Thanks!

Advertisement

Answer

JavaScript

This line. You are appending string to an array. Change it to:

JavaScript

Side note 1:

JavaScript

This loop can be changed to:

JavaScript

Side note 2:

Splitting on "\s+" is better. It also takes care of multiple spaces.


Side note 3:

JavaScript

This can be simplified as:

JavaScript

Side note 4:

JavaScript

Using break for slightly better performance. Also, using foreach loop.


Final side note:

JavaScript

Chaining of replace calls.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement