Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace words with Parallel arrays

Tags:

java

Hello i am new to this forum. I am fairly new to Java. I am trying to convert USA to UK words so that when i input a sentence containing any of the USA words, the output will be will be the sentence but replaced with UK words. This is my attempt:

import javax.swing.JOptionPane;
public class PArraystest
{
    public static void main(String [] arg)
    {
    String[] wordUSA = {"Cell", "Elevator", "Fries", "Gasoline", "Faucet"};
    String[] wordUK = {"Mobile", "Lift", "Chips", "Petrol", "Tap"};
        String changeUK = "";
        String sent;
        sent = JOptionPane.showInputDialog("What name do you want to search for?");
        for (int i = 0; i < wordUSA.length; i++)
        { 
            if (sent.contains(wordUSA[i]))
        {

                sent.replace((wordUK)[i],(wordUSA)[i]);
            //break;
        }
        }
            //if (changeUK.equals(""))
            //System.out.println(" was not found.");
            //else
            System.out.println(sent);   
            }
        }
like image 241
ph1 Avatar asked Mar 14 '26 19:03

ph1


1 Answers

Two things:

  1. You need to use assign the string returned from replace to sent again, or sent will be unchanged`.

  2. The replace method is public String replace(char oldChar, char newChar), so the oldChar US word should come first, followed by the UK word.

This is the correct line: sent = sent.replace(wordUSA[i],wordUK[i]);

like image 124
Corey Wu Avatar answered Mar 16 '26 09:03

Corey Wu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!