Array Only Prints Certain Elements and Not Others

Will Bowen :

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.

import java.util.Arrays;
import java.util.Scanner;

public class PigLatin {
  public static void main (String[] args){
      Scanner scnr = new Scanner(System.in);
      String userWord;

      userWord = scnr.nextLine();
      userWord = userWord.toLowerCase();

      String[] wordArry = userWord.split(" ");

      print(wordArry);
  }

  public static String[] translate(String[] words){
     String[] pigLatin = new String[words.length];

     for (int i = 0; i < words.length; ++i) {
         if (isVowel(words[i].charAt(0)) == true){
             pigLatin[i] = words + "ay"; 
         }
         else if (words[i].charAt(0) == 'y') {
             pigLatin[i] = words[i].substring(findFirstVowel(words[i]), words[i].length()) + words[i].substring(0, findFirstVowel(words[i])) + "ay";
         }
         else {
             pigLatin[i] = words[i].substring(findFirstVowel(words[i]), words[i].length()) + words[i].substring(0, findFirstVowel(words[i])) + "ay";
         }
     }
     return pigLatin;
  }
  public static int findFirstVowel(String s){
      char[] vowList = {'a','e','i','o','u','y'};

        for (int i = 1; i < s.length(); ++i) {
            for (int j = 0; j < vowList.length; ++j) {
                if (s.charAt(i) == vowList[j]) {
                    return i;
                }
            }
        }
    return -1;
   }
  public static boolean isVowel(char c){
      boolean vowel = false;
      char[] vowList = {'a','e','i','o','u'};

      for (int i = 0; i < vowList.length; ++i) {
          if (c == vowList[i]) {
              vowel = true;
          }
      }
      return vowel;
  }
  public static void print(String[] words){

      String[] newArry = new String[words.length];

      for (int i = 0; i < words.length; ++i) {
          newArry[i] = words[i];
      }

      String finalPrint = Arrays.toString(translate(newArry));
      finalPrint = finalPrint.replace("[", "");
      finalPrint = finalPrint.replace(",", "");
      finalPrint = finalPrint.replace("]", "");

      System.out.println(finalPrint);

  }
}

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!

Harshal Parekh :
pigLatin[i] = words + "ay";

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

pigLatin[i] = words[i] + "ay";

Side note 1:

for (int i = 0; i < words.length; ++i) {
    newArry[i] = words[i];
}

This loop can be changed to:

System.arraycopy(words, 0, newArry, 0, words.length);

Side note 2:

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


Side note 3:

if (isVowel(words[i].charAt(0)) == true) {

This can be simplified as:

if (isVowel(words[i].charAt(0))) {

Side note 4:

for (char value : vowList) {
    if (c == value) {
        vowel = true;
        break;
    }
}

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


Final side note:

finalPrint = finalPrint.replace("[", "")
        .replace(",", "")
        .replace("]", "");

Chaining of replace calls.

Hope this helps. Good luck.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to remove certain elements from an array into a new array and leave the others only the original array?

Is there an alternative to appendRow in AppsScript that only prints certain columns while leaving others in the row untouched

Target elements excluding certain others

Initialize only certain elements of array in dzn file

How to apply rules to only certain elements in array

Permute only certain elements in an array in python

Media Queries effecting certain Elements and not others

How to plot only some cells with certain values of an array and others not with matplotlib.pyplot?

Recode only certain values and keep others as it is in R

Overflow only certain elements

What's the fastest way to only rotate certain elements in an array?

Return only elements of an array in an object that contain a certain value

How to pick only certain elements from an array in Ruby?

Write only certain elements / columns of a 2 dimensional array back to worksheet

How to access only certain elements in a 2d array in Javascript?

C printf prints two elements from array when it only should print one

How to build an array comprised of two others using only particular elements of each?

sorting and printing elements of array prints out garbage

Assembly code that prints all elements of an array

React JS: Only map certain elements of an array within JSX tag, where the elements to map are iterated

my code only prints the last value of the array

The 'for' loop only prints the first element of my array

JSON only prints last object in array

program prints only last element in array

Animating certain elements after others have finished their animation

Script not targeting certain elements by ID, works fine on others

Adding certain elements of list of lists together, keeping others intact

Assert that certain elements exists among others independent of order

Python Pandas: how to only pivot certain columns while keeping others?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive