Rajafa
Rajafa

Reputation: 23

Print output on the same line

I'm making a translator in Java to translate a fake language that I came up with for fun. I input an English word and it returns it's equivalent word in the other language. It's successfully translating everything, but each new word is on a separate line and I just want the output on one line. I'm still new to Java but here is my code:

import java.io.*;
import java.util.*;

public class Translator {

    private static Scanner scan;

    public static void main(String[] args) {

            HashMap <String, String> XanthiumLang = new HashMap <String, String>();
            XanthiumLang.put("hello", "fohran");
            XanthiumLang.put("the", "krif");
            XanthiumLang.put("of", "ney");
            XanthiumLang.put("to", "dov");
            XanthiumLang.put("and", "ahrk");

            Scanner scan = new Scanner(System.in);
            String sentence = scan.nextLine();
            String[] result = sentence.split(" ");
            for(int i = 0; i < result.length; i++){
            if(XanthiumLang.containsKey(result[i])){
                result[i] = XanthiumLang.get(result[i]);
                   }
                 System.out.println(result[i]);
               }
        }
 }

I only have a few words in the code as of right now and they are stored in a hashmap. Anyways like I said the output of each word is on a separate line, not on just one line. Any ideas or changes to my code would be helpful!

Upvotes: 2

Views: 14545

Answers (1)

UnknownOctopus
UnknownOctopus

Reputation: 2277

Use System.out.print();. Doing so will print the entire array on one line. System.out.println(); will print the result on a new line each time (hence the ln at the end).

import java.io.*;
import java.util.*;

public class Translator {

  private static Scanner scan;

  public static void main(String[] args) {

    HashMap <String, String> XanthiumLang = new HashMap <String, String>();
    XanthiumLang.put("hello", "fohran");
    XanthiumLang.put("the", "krif");
    XanthiumLang.put("of", "ney");
    XanthiumLang.put("to", "dov");
    XanthiumLang.put("and", "ahrk");

    Scanner scan = new Scanner(System.in);
    String sentence = scan.nextLine();
    String[] result = sentence.split(" ");
      for(int i = 0; i < result.length; i++){
         if(XanthiumLang.containsKey(result[i])){
           result[i] = XanthiumLang.get(result[i]);
         }
         System.out.print(result[i]);
       }
     }
   }

More on the different formats here.

Upvotes: 2

Related Questions