I need to create some kind of translator. I have a HashMap with pairs of Russian and English words as keys and values respectively. When I input a phrase in Russian I need to get English translation or nulls/not found for the words which are not in the dictionary.
So I have such methods for translation:
public boolean isInDictionary(String word){
if(dictionary.containsKey(word)){
return true;
}
return false;
}
public String translateSentence(String sentence){
StringBuilder result = new StringBuilder();
String[] splittedStrings = sentence.split( "\n" );
List<String> list = new ArrayList<>();
for(String s : splittedStrings){
result.append(translateCheck(s));
}
return result.toString();
}
public String getWord(String word){
return dictionary.get(word);
}
Here is how I call these methods:
Scanner scanner = new Scanner(System.in);
Translator translator = new Translator();
System.out.println("Input the phrase to translate:");
String input = scanner.nextLine();
System.out.println(translator.translateSentence(input));
When I input distinct word in Russian I get a translation for that, while when I input a phrase consisting of different words I get null.
So what am I doing wrong? I would be grateful for some help!
Something like this:
public boolean isInDictionary(String word) {
return dictionary.containsKey(word); //note the removal of the if as it already returns a boolean
}
public String translateSentence(String sentence) {
StringBuilder result = new StringBuilder();
String[] splittedStrings = sentence.trim().split(" "); // the actual change
List<String> list = new ArrayList<>();
for (String s : splittedStrings) {
result.append(translateCheck(s));
}
return result.toString();
}
public String getWord(String word) {
return dictionary.get(word);
}
You are splitting the sentence by lines instead of words, probably you wanted to use sentence.split(" ") instead of sentence.split("\n").
Related
as it mentioned in the title, I have this code
String a = flett("AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU");
public static String flett(String... s){
StringBuilder merge = new StringBuilder();
for (int i = 0; i < s.length; i++) {
merge.append(s.charAt(i));
}
return merge;
}
I got an error at chartAt(i) ?
how for example I can call every character in the array s and save them into merge or call an specific character like the first character from each one and save them into merge ?
s[i].charAt(j);
where i - the index of an array, j - the index of a letter within a String.
A Java 8 method that collects the first letter of each array's element might look like
public String flett(String... s) {
return Arrays.stream(s)
.map(i -> i.length() > 0 ? String.valueOf(i.charAt(0)) : "")
.collect(Collectors.joining());
}
For the array "AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU", it results in "ALGORIT".
You have to use a variable amount of String parameters, then concatenate all first characters of non empty Strings of the parameters and return the concatenated object:
public static void main(String[] args) {
String s = flett("AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU", "HOLA", "MMMMH");
System.out.println(s);
}
// Please note the parameter, it takes a various amount of Strings
public static String flett(String ... values) {
// create something that concatenates Strings (other options possible)
StringBuilder sb = new StringBuilder();
// the parameters are now an array of Strings, which you can "foreach"
for (String s : values) {
// check for empty ones and skip those
if (!s.equals("")) {
// append the first character of a valid parameter
sb.append(s.charAt(0));
}
}
return sb.toString();
}
Be surprised by the output…
This method get some Strings and Create String from the first character of each String.
public static String flett(String... s) {
StringBuilder res = new StringBuilder(s.length);
for (String a : s) {
if (!a.isEmpty()) {
res.append(a.charAt(0));
}
}
return res.toString();
}
I wish you can help me I want to do is I have two variables of type string
String text = "HELLO HOW ARE YOU";
String value = "abc";
I want to do is see if any character of the variable values in text and contains tested but I only detects a single character but not
if(text.toUpperCase().contains(value.toUpperCase()))throw new Exception("NOT LETTERS");
You could use the List API...
String text = "HELLO HOW ARE YOU";
String value = "abc";
List<String> left = new ArrayList<>(Arrays.asList(text.toUpperCase().split("")));
List<String> right = new ArrayList<>(Arrays.asList(value.toUpperCase().split("")));
boolean hasAny = left.removeAll(right);
Basically this creates a List of each word then removes all the matches from the second in the first. A return value of true means the first List was modified, meaning it had matching values. You might even be able to compare the difference in size to determine how many matches there were.
You could also use Java 8's Stream API...
String text = "HELLO HOW ARE YOU";
String value = "abc";
List<String> left = new ArrayList<>(Arrays.asList(text.toUpperCase().split("")));
List<String> right = new ArrayList<>(Arrays.asList(value.toUpperCase().split("")));
boolean anyMatch = left.stream().anyMatch((String t) -> {
return right.contains(t);
});
Again, this will simply return true if the first List contains ANY of the values in the second List
Now, if you wanted to know which values actually matched, you might be able to use something like...
Set<String> collect = right.stream().filter((String t) -> {
return left.contains(t);
}).collect(Collectors.toSet());
System.out.println(collect);
Which in you example, would print
[A]
You can try like this:
public static boolean findLetters() {
String text = "HELLO HOW ARE YOU";
String value = "abc";
for (int i = 0; i < value.length(); i++) {
if (text.indexOf(value.toUpperCase().charAt(i)) == -1) {
return false;
}
}
return true;
}
Not sure if I understand the question quite well, but you may try this:
String text = "HELLO HOW ARE YOU";
String value = "abc";
for(char c : value.toUpperCase().toCharArray()) {
if (text.indexOf(c) != -1) {
throw new Exception("NOT LETTERS");
}
}
I have input string array containing value like
1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0
What could be the best way to obtain values out of above input which contains 1950/00/00,
1953/00/00, 1958/00/00 , 1960/00/00 and 1962/0 in individual string objects?
Use the method String.split(regex):
String input = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0";
String[] parts = input.split(";");
for (String part : parts) {
System.out.println(part);
}
The split() method splits the string based on the given regular expression or delimiter, and returns the tokens in the form of array. Below example shows splitting string with (;)
public class MyStrSplit {
public static void main(String a[]){
String str = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0";
String[] tokens = str.split(";");
for(String s:tokens){
System.out.println(s);
}
}
}
Another choice to split string by regular expression:
public class SpitByRegx
{
public static void main(String[] args)
{
String input = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0";
Pattern pattern = Pattern.compile("([0-9/]+);?");
Matcher m = pattern.matcher(input);
while(m.find())
{
System.out.println(m.group(1));
}
}
}
I have a string array that contains some information.
Example:
String [] testStringArray;
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
This is exactly how the information is. Now my problem is I want to make each element a seperate element in an array and I want to split it based on the \n character.
So I want
newArray[0]=Jim,35
newArray[1]=Alex,45
newArray[2]=Mark,21
newArray[3]=Ana,18
etc etc. I am aware of the split method but won't this just split each array element into a completely new array instead of combining them?
If anyone could help, it would be appreciated. Thanks
Something like this:
// Splits the given array of Strings on the given regex and returns
// the result in a single array.
public static String[] splitContent(String regex, String... input) {
List<String> list = new ArrayList<>();
for (String str : input) {
for (String split : str.split(regex)) {
list.add(split);
}
}
return list.toArray(new String[list.size()]);
}
you can call it this way:
String[] testStringArray = ...;
String[] newArray = splitContent("\n", testStringArray);
Because of the use of varargs you can also call it like this:
String[] newArray = splitContent("\n", str1, str2, str3, str4);
where strX are String variables. You can use any amount you want. So either pass an array of Strings, or any amount of Strings you like.
If you don't need the old array anymore, you can also use it like this:
String[] yourArray = ...;
yourArray = splitContent("\n", yourArray);
String[] testStringArray = new String[2];
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21";
testStringArray[1]= "Jiam,35\nAleax,45\nMarak,21";
for(String s : testStringArray) {
String[] temp = s.split("\n");
for(String t : temp) {
result.add(t);
}
}
String[] res = result.toArray(new String[result.size()]);
Try This is working Code >>
String[] testStringArray = new String[2]; // size of array
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21"; // store value
testStringArray[1]= "Ana,18\nMegan,44";
for(String s : testStringArray) {
String[] temp = s.split("\n"); // split from \n
for(String t : temp) {
result.add(t); // add value in result
System.out.print(t);
}
}
result.toArray(new String[result.size()]);
you can first merge the strings into one string and then use the split method for the merged string.
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
StringBuffer sb = new StringBuffer();
for(String s : testStringArray){
s = s.trim();
sb.append(s);
if (!s.endWith("\n")){
sb.append("\n");
}
}
String[] array = sb.toString().split("\n");
Try this. It is simple and readable.
ArrayList<String> newArray = new ArrayList<String>();
for (String s : testStringArray) {
newArray.addAll(Arrays.asList(s.split("\\n"));
}
Firstly, you can't write what you just did. You made a String array, which can only contain Strings. Furthermore the String has to be in markers "" like "some text here".
Furthermore, there can only be ONE String at one place in the array like:
newArray[0] = "Jim";
newArray[1] = "Alex";
And NOT like:
newArray[0] = Jim;
And CERTAINLY NOT like:
// Here you're trying to put 2 things in 1 place in the array-index
newArray[0] = Jim, 35;
If you wan't to combine 2 things, like an name and age you have to use 2D array - or probably better in your case ArrayList.
Make a new class with following object:
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
And afterwards go to your class where you want to use the original array, and write:
ArrayList<Person> someNameOfTheArrayList = new ArrayList<Person>();
someNameOfTheArrayList.add(new Person("Jim", 32));
someNameOfTheArrayList.add(new Person("Alex", 22));
Consider the following String :
5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+
Here is how I want to split string, split it with + so I get this result :
myArray[0] = "5|12345|value1|value2|value3|value4";
myArray[1] = "5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4";
if string has doesn't contain char "?" split it with "|" and continue to part II, if string does contain "?" split it and for each part split it with "|" and continue to part II.
Here is part II :
myObject.setAttribute1(newString[0]);
...
myObject.setAttribute4(newString[3]);
Here what I've got so far :
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
public void mapObject(String input){
String[] myArray = null;
if (input.contains("+")) {
myArray = input.split("+");
} else {
myArray = new String[1];
myArray[0] = input;
}
for (int i = 0; i < myArray.length; i++) {
String[] secondaryArray = null;
String[] myObjectAttribute = null;
if (myArray[i].contains("?")) {
secondaryArray = temporaryString.myArray[i].split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
} else {
myObjectAttribute = myArray[i].toString().split("\\|");
}
myObject.setAttribute1(myObjectAttribute[0]);
...
myObject.setAttribute4(myObjectAttribute[3]);
System.out.println(myObject.toString());
}
Problem :
When I split myArray, going trough for with myArray[0], everything set up nice as it should.
Then comes the myArray[1], its split into two parts then the second part overrides the value of the first(how do I know that?). I've overridden toString() method of myObject, when I finish I print the set values so I know that it overrides it, does anybody know how can I fix this?
I'm not quite sure what the intention is here, but in this snippet of code
secondaryArray = temporaryString.split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
if secondaryArray has two elements after the split operation, you are iterating over each half and re-assigning myObjectAttribute to the output of string.split("\|") each time. It doesn't matter what is in the first element of secondaryArray, as after this code runs myObjectAttribute is going to contain the result of split("\\|") on the last element in the array.
Also, there is no point in calling .toString() on a String object as you do in temporaryString = myArray[i].toString().
The code doesn't seem to be able to handle the possible expansion of strings in the secondary case. To make the code clearer, I would use a List rather than array.
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
private void split(List<String> input, List<String> output, String split) {
for (String s: input) {
if (s.contains(split))
{
output.addAll(Arrays.asList(s.split(Pattern.quote(split)));
}
else
output.add(s);
}
}
public void mapObject(String input) {
List<String> inputSrings = new ArrayList<String>();
List<String> splitPlus = new ArrayList<String>();
inputStrings.add(input);
split(inputStrings, splitPlus);
List<String> splitQuest = new ArrayList<String>();
split(splitPlus, splitQuest, "?");
for (String s: splitQuest) {
// you can now set the attributes from the values in the list
// splitPipe
String[] attributes = s.split("\\|");
myObject.setAttribute1(attributes[0]);
....
myObject.setAttribute4(attributes[3]);
System.out.println(myObject);
}
}