I'm trying to write a program to decode Adobe key code into text, however the string array that I'm using doesn't seem to change values when passing through if statements within my for loop. Here is the code (I haven't implemented the print out section as I could not get my test of the the array switching values to work):
import java.util.Scanner;
public class Decode {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("Enter collected data:");
String data = input.nextLine();
input.close();
String[] splitdata = data.split("\\s+");
int datalength=splitdata.length;
for (int i=0; i<datalength; i++){
if (splitdata[i]=="1")
splitdata[i]="\n";
if (splitdata[i]=="8")
splitdata[i]="**backspace**";
if (splitdata[i]=="9")
splitdata[i]="**tab**";
if (splitdata[i]=="13")
splitdata[i]="**enter**";
if (splitdata[i]=="16")
splitdata[i]="**shift**";
if (splitdata[i]=="17")
splitdata[i]="**control**";
if (splitdata[i]=="19")
splitdata[i]="**pause/break**";
if (splitdata[i]=="20")
splitdata[i]="**capslock**";
if (splitdata[i]=="27")
splitdata[i]="**esc**";
if (splitdata[i]=="32")
splitdata[i]="\\s+";
if (splitdata[i]=="33")
splitdata[i]="*page up**";
if (splitdata[i]=="34")
splitdata[i]="**page down**";
if (splitdata[i]=="35")
splitdata[i]="**end**";
if (splitdata[i]=="36")
splitdata[i]="**home**";
if (splitdata[i]=="37")
splitdata[i]="**left**";
if (splitdata[i]=="38")
splitdata[i]="**up**";
if (splitdata[i]=="39")
splitdata[i]="**right**";
if (splitdata[i]=="40")
splitdata[i]="**down**";
if (splitdata[i]=="45")
splitdata[i]="**insert**";
if (splitdata[i]=="46")
splitdata[i]="**delete**";
if (splitdata[i]=="48")
splitdata[i]="0";
if (splitdata[i]=="49")
splitdata[i]="1";
if (splitdata[i]=="50")
splitdata[i]="2";
if (splitdata[i]=="51")
splitdata[i]="3";
if (splitdata[i]=="52")
splitdata[i]="4";
if (splitdata[i]=="53")
splitdata[i]="5";
if (splitdata[i]=="54")
splitdata[i]="6";
if (splitdata[i]=="55")
splitdata[i]="7";
if (splitdata[i]=="56")
splitdata[i]="8";
if (splitdata[i]=="57")
splitdata[i]="9";
if (splitdata[i]=="S-65")
splitdata[i]="a";
if (splitdata[i]=="S-66")
splitdata[i]="b";
if (splitdata[i]=="S-67")
splitdata[i]="c";
if (splitdata[i]=="S-68")
splitdata[i]="d";
if (splitdata[i]=="S-69")
splitdata[i]="e";
if (splitdata[i]=="S-70")
splitdata[i]="f";
if (splitdata[i]=="S-71")
splitdata[i]="g";
if (splitdata[i]=="S-72")
splitdata[i]="h";
if (splitdata[i]=="S-73")
splitdata[i]="i";
if (splitdata[i]=="S-74")
splitdata[i]="j";
if (splitdata[i]=="S-75")
splitdata[i]="k";
if (splitdata[i]=="S-76")
splitdata[i]="l";
if (splitdata[i]=="S-77")
splitdata[i]="m";
if (splitdata[i]=="S-78")
splitdata[i]="n";
if (splitdata[i]=="S-79")
splitdata[i]="o";
if (splitdata[i]=="S-80")
splitdata[i]="p";
if (splitdata[i]=="S-81")
splitdata[i]="q";
if (splitdata[i]=="S-82")
splitdata[i]="r";
if (splitdata[i]=="S-83")
splitdata[i]="s";
if (splitdata[i]=="S-84")
splitdata[i]="t";
if (splitdata[i]=="S-85")
splitdata[i]="u";
if (splitdata[i]=="S-86")
splitdata[i]="v";
if (splitdata[i]=="S-87")
splitdata[i]="w";
if (splitdata[i]=="S-88")
splitdata[i]="x";
if (splitdata[i]=="S-89")
splitdata[i]="y";
if (splitdata[i]=="S-90")
splitdata[i]="z";
if (splitdata[i]=="96")
splitdata[i]="0";
if (splitdata[i]=="97")
splitdata[i]="1";
if (splitdata[i]=="98")
splitdata[i]="2";
if (splitdata[i]=="99")
splitdata[i]="3";
if (splitdata[i]=="100")
splitdata[i]="4";
if (splitdata[i]=="101")
splitdata[i]="5";
if (splitdata[i]=="102")
splitdata[i]="6";
if (splitdata[i]=="103")
splitdata[i]="7";
if (splitdata[i]=="104")
splitdata[i]="8";
if (splitdata[i]=="105")
splitdata[i]="9";
if (splitdata[i]=="106")
splitdata[i]="*";
if (splitdata[i]=="107")
splitdata[i]="+";
if (splitdata[i]=="109")
splitdata[i]="-";
if (splitdata[i]=="110")
splitdata[i]=".";
if (splitdata[i]=="111")
splitdata[i]="/";
if (splitdata[i]=="112")
splitdata[i]="**F1**";
if (splitdata[i]=="113")
splitdata[i]="**F2**";
if (splitdata[i]=="114")
splitdata[i]="**F3**";
if (splitdata[i]=="115")
splitdata[i]="**F4**";
if (splitdata[i]=="116")
splitdata[i]="**F5**";
if (splitdata[i]=="117")
splitdata[i]="**F6**";
if (splitdata[i]=="118")
splitdata[i]="**F7**";
if (splitdata[i]=="119")
splitdata[i]="**F8**";
if (splitdata[i]=="120")
splitdata[i]="**F9**";
if (splitdata[i]=="122")
splitdata[i]="**F11**";
if (splitdata[i]=="123")
splitdata[i]="**F12**";
if (splitdata[i]=="124")
splitdata[i]="**F13**";
if (splitdata[i]=="125")
splitdata[i]="**F14**";
if (splitdata[i]=="126")
splitdata[i]="**F15**";
if (splitdata[i]=="144")
splitdata[i]="**NumLock**";
if (splitdata[i]=="145")
splitdata[i]="**ScrLock**";
if (splitdata[i]=="186")
splitdata[i]=";";
if (splitdata[i]=="187")
splitdata[i]="=";
if (splitdata[i]=="188")
splitdata[i]=",";
if (splitdata[i]=="189")
splitdata[i]="-";
if (splitdata[i]=="190")
splitdata[i]=".";
if (splitdata[i]=="191")
splitdata[i]="/";
if (splitdata[i]=="192")
splitdata[i]="`";
if (splitdata[i]=="219")
splitdata[i]="[";
if (splitdata[i]=="220")
splitdata[i]="**backslash**";
if (splitdata[i]=="221")
splitdata[i]="]";
if (splitdata[i]=="222")
splitdata[i]="'";
}
System.out.println(splitdata[0]);
}
}
For example if I type 8 I should get a print that reads backspace, however it simply outputs 8. I'm sure it's a simple mistake that I've overlooked, but I'm pretty new to java so any help would be greatly appreciated.
Try this example:
import java.util.Scanner;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.println ("Enter collected data:");
String data = input.nextLine();
input.close();
String[] splitdata = data.split("\\s+");
int datalength=splitdata.length;
for (int i=0; i<datalength; i++)
{
if (splitdata[i].equals("1") )
splitdata[i]="**newline**";
else if (splitdata[i].equals("8") )
splitdata[i]="**backspace**";
else if (splitdata[i].equals("9") )
splitdata[i]="**tab**";
else if (splitdata[i].equals("13") )
splitdata[i]="**enter**";
else if (splitdata[i].equals("16") )
splitdata[i]="**shift**";
else
System.out.println("oops!, no match for: " + splitdata[i]);
}
for(String s: splitdata)
{
System.out.println(s);
}
}
}
Apart from this, if you are allowed to collections then I would
suggest you to use HashMap instead atleast you can rid of this ugly
if-else
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I am doing a project for school, and I am trying to make it to where you can set up a name for yourself while going through a series of questions asked by the computer. I want the user to be able to change their name right after assigning it if they do not like what they put down or they typed something wrong.
Right now the program assigns the name the user wants correctly the first time, but when it goes back through the loop to change it to something else the string is left blank.
Console Output
'''
import java.util.*;
public class JavaInputProdject
{
public static void main(String args[])
{
int i=0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old=false;
boolean aAge=true;
String user="User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n"+un);
do
{
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \""+ user +"\"(true/false)");
System.out.print(un);
if(bob.nextBoolean()==true)
{
boo = true;
un = user + "> ";
}
else
{
if(i>=3)
{
System.out.println("Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n"+un);
bob.next();
i++;
}
} while(boo==false);
}
}
'''
You need to replace the line bob.next() (near the end of the do-while loop) with bob.nextLine().
I believe that bob.next() does not consume the newline that is entered as a result of hitting the <ENTER> key after the bob.nextBoolean() call. Hence the user = bob.nextLine(); line (at the start of the do-while loop) is consuming that newline on the second and subsequent loop iterations. So replacing bob.next() with bob.nextLine() will resolve the problem.
For the sake of completeness, here is the corrected code:
import java.util.Scanner;
public class JavaInputProdject {
public static void main(String[] args) {
int i = 0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old = false;
boolean aAge = true;
String user = "User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n" + un);
do {
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \"" + user + "\"(true/false)");
System.out.print(un);
if (bob.nextBoolean()) {
boo = true;
un = user + "> ";
}
else {
if (i >= 3) {
System.out.println(
"Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n" + un);
bob.nextLine();
i++;
}
} while (boo == false);
}
}
Refer to Scanner is skipping nextLine() after using next() or nextFoo()?
when you want to get correct username based on false flag you doesnt init a value to user.
you should write something like this with bob.nextLine :
System.out.print("Bob> Please type in a new Username\n"+un);
user = bob.nextLine();
i++;
currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The overall project is creating a system manager for airports. It keeps track of airports, flights, seating sections, seats and other relevent info for each of those catagories. The initial system is set up by importing from a file that's formatted a certain way. I'm having problems parsing the file properly to set up the initial system. the data is parsed from the file and used as method parameters to create the objects: Airport, Airline, Flight, FlightSection, and Seat.
the formatting is:
[list-of-airport-codes] {list-of-airlines}
list-of-airport-codes ::= comma-separated strings
list-of-airlines ::= airline-name1[flightinfo-list1], airline-name2[flightinfo-list2], airlinename3[flightinfo-list3], …
flightinfo-list ::= flightID1|flightdate1|originAirportCode1|destinationAirportCode1[flightsectionlist1], flightID2|flightdate2|originAirportCode2|destinationAirportCode2[flightsection-list2], …
flightdate ::= year, month, day-of-month, hours, minutes
flightsection-list ::= sectionclass: seat-price: layout: number-of-rows, …
sectionclass ::= F, B, E (for first class, business class, economy class)
layout ::= S, M, W (different known seating layouts)
example:
[DEN,NYC,SEA,LAX]{AMER[AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],
AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3], …], UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3], UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2], …], FRONT[…], USAIR[…]}
I tried brute forcing it using a combination of delimiters and while loops. The code successfully creates the Airports, first Airline and Flighsections, but when it gets to creating the second airline it crashes, because i'm not looping properly, and having a hard time getting it right. My code for it as of now, is a mess, and if you're willing to look at it, I would appreciate any constructive input. My question is what would be a better way to approach this? A different design approach? Maybe a smarter way to use the delimiters?
Thanks in advance for your help!!
here's what i've tried.
private void readFile(File file){
System.out.println("reading file");
Scanner tempScan;
String result;
String temp = "";
scan.useDelimiter("\\[|\\{");
try{
// AIRPORTS
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|\\]");
while(tempScan.hasNext()){
temp = tempScan.next();
sysMan.createAirport(temp);
}
tempScan.close();
/* AIRLINE
* FLIGHT
* FLIGHTSECTION
*/
do{
// AIRLINE (loop<flight & fsection>)
result = scan.next();
sysMan.createAirline(result);
// FLIGHT
result = scan.next();
tempScan = new Scanner(result);
do{
tempScan.useDelimiter(",|\\|");
ArrayList flightInfo = new ArrayList();
while(tempScan.hasNext()){
if(tempScan.hasNextInt()){
flightInfo.add(tempScan.nextInt());
} else {
flightInfo.add(tempScan.next());
}
}
tempScan.close();
sysMan.createFlight(sysMan.getLastAddedAirline(),(String)flightInfo.get(0), (int)flightInfo.get(1), (int)flightInfo.get(2), (int)flightInfo.get(3), (int)flightInfo.get(4), (int)flightInfo.get(5), (String)flightInfo.get(6), (String)flightInfo.get(7));
// FLIGHTSECTION (loop<itself>)
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|:|\\]");
ArrayList sectInfo = new ArrayList();
int i = 1;
while(!temp.contains("|")){
if(tempScan.hasNextInt()){
sectInfo.add(tempScan.nextInt());
} else {
temp = tempScan.next();
if(temp.equals(""))
break;
char c = temp.charAt(0);
sectInfo.add(c);
}
if(i == 4){
sysMan.createSection(sysMan.getLastAddedAirline(), sysMan.getLastAddedFlightID(), (char)sectInfo.get(0), (int)sectInfo.get(1), (char)sectInfo.get(2), (int)sectInfo.get(3));
i = 1;
sectInfo = null;
sectInfo = new ArrayList();
continue;
}
i++;
}
}while(!temp.equals("\\s+"));
}while(!temp.contains("\\s+"));
}catch(NullPointerException e){
System.err.println(e);
}
}
I'd rather chunk it down by regexp mathing the outer bounds, have a look, I took it a couple of levels broken.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tokeni {
static String yolo = "[DEN,NYC,SEA,LAX]{AMER["
+ "AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],"
+ "AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3]],"
+ "UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3],"
+ "UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2]]}";
public static void main(String[] args) {
Matcher airportCodesMatcher = Pattern.compile("\\[(.*?)\\]").matcher(yolo);
airportCodesMatcher.find();
String[] airportCodes = airportCodesMatcher.group(1).split(",");
Matcher airLinesMatcher = Pattern.compile("\\{(.*?)\\}").matcher(yolo);
airLinesMatcher.find();
String airLinesStr = airLinesMatcher.group(1);
System.out.println(airLinesStr);
Pattern airLinePattern = Pattern.compile("\\D+\\[(.*?)\\]\\]");
Matcher airLineMatcher = airLinePattern.matcher(airLinesStr);
while( airLineMatcher.find() ) {
String airLineStr = airLineMatcher.group(0).trim();
if(airLineStr.startsWith(",")) {
airLineStr = airLineStr.substring(1, airLineStr.length()).trim();
}
System.out.println(airLineStr);
Matcher airLineNameMatcher = Pattern.compile("[A-Z]+").matcher(airLineStr);
airLineNameMatcher.find();
String airLineName = airLineNameMatcher.group(0).trim();
System.out.println(airLineName);
airLineStr = airLineStr.substring(airLineStr.indexOf("[")+1, airLineStr.length());
Matcher airLineInfoMatcher = Pattern.compile("\\D+(.*?)\\]").matcher(airLineStr);
while(airLineInfoMatcher.find()) {
String airLineInfoStr = airLineInfoMatcher.group(0).trim();
if(airLineInfoStr.startsWith(",")) {
airLineInfoStr = airLineInfoStr.substring(1, airLineInfoStr.length()).trim();
}
System.out.println(airLineInfoStr);
}
}
}
}
I am have trouble creating an array or object(with multiple fields) and sending it to an array-list. Any help would be greatly appreciated. I have spent hours looking through every video on YouTube with the words object and array-list in them and have been unable to find much help.
The program needs to prompt the user to pick a option (1. AddItem) then prompt the user for the name and format (dvd, vhs) and save multiple objects with these variables in an array-list. I either keep having the location where it is saved in memory returned to me or instead of multiple objects one large object is created.
Library:
import java.util.Scanner;
import java.util.ArrayList;
public class Library {
static ArrayList<Object> items = new ArrayList<Object>();
static int menuOption;
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
String title, format;
boolean right = false;
do{
displayMenu();
if (menuOption == 1){
System.out.println("Enter Title: ");
title = scan.next();
System.out.println("Enter format: ");
format = scan.next();
addNewItem(title, format);
} else {System.out.println(items);
}
} while (!right);
}
static int displayMenu(){
System.out.println("Menu: ");
System.out.println("1. Add New Item");
menuOption = scan.nextInt();
return menuOption;
}
static void addNewItem(String title, String format){
MediaItem b = new MediaItem();
b.setTitle(title);
b.setFormat(format);
items.add(b);
}
}
MediaItem:
public class MediaItem {
String title;
String format;
MediaItem(){
title = null;
format = null
}
MediaItem(String title, String format){
title = new String();
format = new String();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
The program will run if you:
1 - Change the line
static ArrayList<Object> items = new ArrayList<Object>();
to
static ArrayList<MediaItem> items = new ArrayList<MediaItem>();
2 - Change the line
System.out.println( items );
to
for ( MediaItem mi : items )
{
System.out.println( mi.getTitle() + ", " + mi.getFormat() );
}
3 - Insert a ";" at the end of the line
format = null
I did it here and it worked.
I either keep having the location where it is saved in memory returned to me
I am guessing you ran into this when you tried to either use System.out.println() to print a MediaItem, or you otherwise tried to automatically convert an object to a string. Whatever approach you took when you were seeing the memory addresses is probably the right way to do it, your problem was only in your displaying of the data.
Consider:
MediaItem item = ...;
System.out.println(item);
By default, Java doesn't know how to convert arbitrary objects to strings when you do stuff like that, and so it just spits out the class name and memory address. You either need to print the fields separately (e.g. Java knows how to display a String already), like:
System.out.println("Title: " + item.getTitle() + " Format: " + item.getFormat());
Or you can override toString() (declared in Object) to provide a custom string conversion:
class MediaItem {
...
#Override public String toString () {
return "Title: " + title + " Format: " + format;
}
}
And then you can print it directly:
System.out.println(item);
It is the default base implementation of Object.toString() that produces those strings with the memory address in them.
Based on your description, I'm guessing you had a roughly working implementation but ran into this issue and ended up changing around (and breaking) a bunch of other unrelated things to try and fix it.
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);
}
}
Two things:
You need to use assign the string returned from replace to sent again, or sent will be unchanged`.
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]);
The replace method returns a new String with the replaced text:
//sent.replace((wordUK)[i],(wordUSA)[i]);
sent = sent.replace((wordUK)[i],(wordUSA)[i]);
Two problems:
First, you should assign the replaced string back to sent.
Second, you should use replaceAll instead of replace.
There's a whole framework of functionality devoted to this in Java called internationalizaion (i18n)
While the sample below is primarily for generation origianlly I thought I'd point it out because you could probably devise how to run it in reverse as well.
Here's a snippet that shows the proper way to go about this:
http://docs.oracle.com/javase/tutorial/i18n/intro/after.html
(all code below is theirs and not my own)
Note that to run this you'll need the resource files from the site or the versions I have provided below from the site
import java.util.*;
public class I18NSample {
static public void main(String[] args) {
String language;
String country;
if (args.length != 2) {
language = new String("en");
country = new String("US");
} else {
language = new String(args[0]);
country = new String(args[1]);
}
Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
System.out.println(messages.getString("greetings"));
System.out.println(messages.getString("inquiry"));
System.out.println(messages.getString("farewell"));
}
}
MessagesBundle.properties:
greetings = Hello.
farewell = Goodbye.
inquiry = How are you?
MessagesBundle_en_US.properties:
greetings = Hello.
farewell = Goodbye.
inquiry = How are you?
MessagesBundle_fr_FR.properties:
greetings = Bonjour.
farewell = Au revoir.
inquiry = Comment allez-vous?