user2066198
user2066198

Reputation: 1

Java- How do i convert a string of numbers to an Array of letters

This is what I want to do:

I want to be able at the prompt just type in some numbers like

input

10 10 20 30

After that I would like to convert each number to a letter so my output would be like

jjte

Here is my code. Currently all I get is null.

import java.util.Scanner;
public class mainClass {
    public static void main(String[] args) {
       System.out.println("Past in code here: ");
       Scanner inputM=new Scanner(System.in);
       String  input=inputM.nextLine();
       String[] Emessage=input.split(" ");
       String[] eMessage=new String[Emessage.length];

       for(int i = 0; i < Emessage.length; i++) {
          if(Emessage[i]=="10"){eMessage[i]="a";}
          if(Emessage[i]=="20"){eMessage[i]="b";}
          if(Emessage[i]=="30"){eMessage[i]="c";}
          if(Emessage[i]==" "){eMessage[i]=" ";}           
       } 

       System.out.println(" ");

       for(int i=0;i<eMessage.length;i++){
           System.out.print(eMessage[i]);
       }
    }
}

This is a sample run: .......................

Past in code here:

10 20 30

nullnullnull

Note: nullnullnull should equal abc

Upvotes: 0

Views: 91

Answers (2)

Since String is an object ,ou can't check equality of string using == operator. you need to use equals method for checking equality as follows

if( "10".equals( Emessage[i] ) ){ eMessage[i]="a"; }

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Try

    if (Emessage[i].equals("10") {
        //code
    }

Upvotes: 3

Related Questions