so I'm having a small problem in java. I have something like
"Victor Fleming"
"Gone With"
"With The"
"The Wind."
So what the sentence should actually look like is
"Victor Fleming"
"Gone with the wind."
Therefore I'm looking to form a single sentence, by words that are adjacent and the same. If no adjacent same word is detected then the sentence will be separated as in "Victor Fleming" case where Fleming is not the same with Gone, so a new sentence is starting. What I've written so far:
List<String> separatedText = new ArrayList<>();
int i = 0;
while (i < mergedTextByHeightColor.size()) {
if ((i < (mergedTextByHeightColor.size() - 3)) && !(mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
separatedText.add(mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1));
i = i + 2;
}
String concatStr = "";
while ((i < (mergedTextByHeightColor.size() - 3)) && (mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
if (concatStr.contains(mergedTextByHeightColor.get(i))) {
concatStr = mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
} else {
concatStr = mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
}
i = i + 3;
}
separatedText.add(concatStr);
}
We can store the sentences in a String array, then loop through each one.
Inside the loop, we check whether the last word of the last item (by splitting it into an array with .split(" "), then getting the last element) is equal to the first word of the current item. If it is, we first remove the first word of the current item, then append it to a StringBuilder.
If it isn't, then we append the StringBuilder's value to the list, append the current element, and move on.
String[] sentences = {"Victor Fleming", "Gone With", "With The", "The Wind."};
List<String> newsentences = new ArrayList<>();
StringBuilder str = new StringBuilder();
for(int i = 0; i < sentences.length; i++) {
String cur = sentences[i];
if(i != 0) {
String[] a = sentences[i-1].split(" ");
String[] b = cur.split(" ");
String last = a[a.length-1];
String first = b[0];
if(last.equalsIgnoreCase(first)) {
str.append(cur.substring(first.length()));
}else {
newsentences.add(str.toString());
str = new StringBuilder();
str.append(cur);
}
}else {
str.append(cur);
}
}
newsentences.add(str.toString());
System.out.println(Arrays.toString(newsentences.toArray()));
Output:
[Victor Fleming, Gone With The Wind.]
I am currently writing . a test to compare leaderboards entries in a betting table, Firstly i have to compare the result picks or the player (which is working) and then i have to compare each players points (which is working) but if both of these attributes are the same i have to assert the player higher on the table is higher alphabetically. I have created the variables username_player and previous_user to do this but cant figure out how to do it, Im trying to put it in the else if section (which i think is correct). There doesn't seem to be an assert option to do this?
public void test_player_leaderboard_entry() {
int size = playerRows.size();
Integer previous_total = 0;
Integer previous_points = 0;
String previous_user = null;
for (int i = 0; i < size; i++) {
//Position
String position_first_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-position-value='" + i + "']")).getText();
//Points
String points_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-points-value='" + i + "']")).getText();
//Username
String username_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-player-value='" + i + "']")).getText();
//Row Number
Integer row = i + 1;
Integer point_player = Integer.parseInt(points_player);
Integer total_of_won_and_looking_good = 0;
//PICKS
for (int pick_number = 1; pick_number < 5; pick_number++) {
String pick_status = Drivers.getDriver().findElement(By.xpath("//*[#id='root']/div/main/section[2]/section/div/ol/a[" + row + "]/li/div[3]/div[" + pick_number + "]/div")).getAttribute("data-qa-pick-state");
//System.out.println(pick_status);
if (Integer.parseInt(pick_status) == 2 || Integer.parseInt(pick_status) == 1) {
total_of_won_and_looking_good = total_of_won_and_looking_good + 1;
}
} if(previous_total.equals(total_of_won_and_looking_good)) {
Assert.assertTrue(previous_points > point_player);
System.out.println("Picks are the same, points are higher ");
} else if (previous_total.equals(total_of_won_and_looking_good)&& previous_points.equals(point_player)) {
Assert.assertTrue(previous_user.compareTo(username_player) < 0);
}
previous_total = total_of_won_and_looking_good;
previous_points = point_player;
previous_user = username_player;
System.out.println("On row number " + row + " we find " + username_player + " in position " + position_first_player + " with " + total_of_won_and_looking_good + " correct picks and " + points_player + " points!");
}
}
}
You can use the compareTo method.
Try using an assertion for previous_user.compareTo(username_player) <0
You can use compareTo method on Strings which compares them lexicographically. So you can do something like
Assert.assertTrue(previous_user.compareTo(username_player) < 0)
Edit:
Maybe you can try it like this but I am not entirely sure that is what you want:
if(previous_total.equals(total_of_won_and_looking_good)) {
Assert.assertTrue(previous_points > point_player);
System.out.println("Picks are the same, points are higher ");
} else if (previous_points.equals(point_player)) {
Assert.assertTrue(previous_user.compareTo(username_player) < 0);
}
public class NumberToWords2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 30001;
numberToWords(n);
}
public static String numberToWords(int n){
String temp = Integer.toString(n);
int[] myArr = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
myArr[i] = temp.charAt(i) - '0';
}
if(myArr.length == 1){
System.out.println(oneDigits(n));
}
else if(myArr.length == 2){
System.out.println(twoDigits(n));
}
else if(myArr.length == 3){
System.out.println(threeDigits(n));
}
else if(myArr.length == 4){
System.out.println(fourDigits(n));
}
else if(myArr.length == 5){
System.out.println(fiveDigits(n));
}
return "Invalid Input";
}
///// Methods to return the equivalent English words. Logic and "And" "Thousands" etc /////
private static String fiveDigits(int n) {
// TODO Auto-generated method stub
//Check for 20000, 30000, 40000 etc
if(n%1000 == 0){
return twoDigits(n/1000) + " Thousand";
}
//Numbers starting with 1
if(n/10000 == 1){
//Handle numbers like 10001, 10002, 70024, 80099 etc
if(n%1000 < 100){
return ones(n/1000) + " Thousand And " + twoDigits(n%1000);
}
else{
return ones(n/1000) + " Thousand " + threeDigits(n%1000);
}
}
else{
if(n%1000 < 100){
return twoDigits(n/1000) + " Thousand And " + twoDigits(n%1000);
}else{
return twoDigits(n/1000) + " Thousand " + threeDigits(n%1000);
}
}
}
private static String fourDigits(int n) {
// TODO Auto-generated method stub
//Check for 2000, 3000, 4000 etc
if(n%1000 == 0){
return ones(n/1000) + " Thousand";
}
//Handle numbers like 1001, 1002, 7024, 8099 etc
else if(n%1000 < 100){
return ones(n/1000) + " Thousand And " + twoDigits(n%1000);
}
//Normal Case
else{
return ones(n/1000) + " Thousand " + threeDigits(n%1000);
}
}
private static String threeDigits(int n) {
// TODO Auto-generated method stub
//Check for 200, 300, 400 etc
if(n%100 == 0){
return ones(n/100) + " Hundred";
}
//Normal Case
else{
return ones(n/100) + " Hundred And " + twoDigits(n%100);
}
}
private static String twoDigits(int n) {
// TODO Auto-generated method stub
//Check for 11, 12, 13, 14 etc OR Handle Single digit so can reuse code
if(n/10 == 1 || n/10 == 0)
return ones(n);
//Check for 20, 30, 40 etc. Cannot print zero at the back
else if(n%10 == 0){
return tens(n/10);
}
//Normal Case
else{
return tens(n/10) + " " + ones(n%10);
}
}
private static String oneDigits(int n) {
// TODO Auto-generated method stub
return ones(n);
}
///// Return number words only /////
private static String ones(int num){
Map<Integer, String> h = new HashMap<Integer, String>();
h.put(0 , "Zero");
h.put(1 , "One");
h.put(2 , "Two");
h.put(3 , "Three");
h.put(4 , "Four");
h.put(5 , "Five");
h.put(6 , "Six");
h.put(7 , "Seven");
h.put(8 , "Eight");
h.put(9 , "Nine");
h.put(10, "Ten");
h.put(11 , "Eleven");
h.put(12 , "Twelve");
h.put(13 , "Thirteen");
h.put(14 , "Fourteen");
h.put(15 , "Fifteen");
h.put(16 , "Sixteen");
h.put(17 , "Seventeen");
h.put(18 , "Eighteen");
h.put(19 , "Nineteen");
return h.get(num);
}
private static String tens(int num){
Map<Integer, String> h = new HashMap<Integer, String>();
h.put(2 , "Twenty");
h.put(3 , "Thirty");
h.put(4 , "Fourty");
h.put(5 , "Fifty");
h.put(6 , "Sixty");
h.put(7 , "Seventy");
h.put(8 , "Eighty");
h.put(9 , "Ninety");
return h.get(num);
}
}
Im trying to learn ways of improving my code writing using lesser and more elegant ways to do conditional if else statements. Is there any way I can improve on this code to make it much shorter and readable like professionals?
I hope it help you
int numOfDigits = n/1000;
String result = String.valueOf(numOfDigits == 1? ones(numOfDigits) : twoDigits(numOfDigits));
String resultString = result + " Thousand " + twoDigits(n%1000);
if(n%1000 < 100){
resultString = result + " Thousand And " + threeDigits(n%1000);
}
return resultString;
You can use two ternary operators to make it a single expression.
For readability, you could also store the values of n / 1000 and n % 1000 in local variable to avoid repetition.
int q = n / 1000;
int r = n % 1000;
return (q / 10 == 1 ? ones(q) : twoDigits(q)) + " Thousand "
+ (r < 100 ? "And " + twoDigits(r) : threeDigits(r));
You can get simpler code by refactoring your logic and building the result piece by piece:
String result = "";
if (n/10000 == 1) {
//Handle numbers like 10001, 10002, 70024, 80099 etc
result += ones(n/1000) + " Thousand";
} else {
result += twoDigits(n/1000) + " Thousand";
}
if (n%1000 < 100) {
result += " And " + twoDigits(n%1000);
} else {
result += " " + threeDigits(n%1000);
}
return result;
I guess you could short hand it like below.
if(n/10000 == 1 && n%1000 < 100) {
return ones(n/1000) + " Thousand And " + twoDigits(n%1000);
}else if(n%1000 < 100) {
return twoDigits(n/1000) + " Thousand And " + twoDigits(n%1000);
}else{
return twoDigits(n/1000) + " Thousand " + threeDigits(n%1000);
}
You can save the calculations, provide meaningful names and indent the code properly like below:
int nOverThousand = n / 1000;
int nPercThousand = n % 1000;
int twoDigitsTerm = twoDigits(nPercThousand);
int threeDigitsTerm = threeDigits(nPercThousand);
if(nOverThousand / 10 == 1){
//Handle numbers like 10001, 10002, 70024, 80099 etc
int term1 = ones(nOverThousand);
return (nPercThousand < 100) ?
(term1 + " Thousand And " + twoDigitsTerm) :
(term1 + " Thousand " + threeDigitsTerm);
}
else{
int term1 = twoDigits(nOverThousand);
return (nPercThousand < 100) ?
(term1 + " Thousand And " + twoDigitsTerm) :
(term1 + " Thousand " + threeDigitsTerm);
}
Note that,
Readability is retained. Meaningful names makes it more readable.
You save on computations.
The code looks compact relatively.
Don't know if you'd consider this better, but here's a suggestion: (completely untested, but you get the idea)
String baseStr;
if(n/10000 == 1) {
//Handle numbers like 10001, 10002, 70024, 80099 etc
baseStr = ones(n/1000);
} else {
baseStr = twoDigits(n/1000);
}
return baseStr + " Thousand " + ((n%1000 < 100) ? "And " twoDigits(n%1000) : + threeDigits(n%1000));
I am trying to write a program that asks the user for a letter (R,G,B) and then after five output the result. There cannot be 2 letters in a row. I get indexoutofbounds when I enter the third letter and the double letter check does not work.
package absolutejava;
import java.util.Scanner;
import java.util.*;
public class RGB {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int count = 0;
boolean isColor = false;
String finalString = "";
int i = 0;
int j = 1;
String temp = "";
for (count = 0; count < 5;) {
System.out.println("Enter a color. Use R for red, G for green, and B for blue.");
temp = kb.nextLine();
if ((temp.equals("R") || temp.equals("G") || temp.equals("B"))) {
isColor = true;
temp += temp;
} else {
isColor = false;
System.out.println("Invald Color, please choose again");
}
if (isColor == true && j < 6 && i < 5) {
count++;
if (temp.length() > 2 && temp.length() <= 5 && finalString.substring(i, j).equals(temp.substring(i - 1, j - 1))) {
System.out.println("Two colors cannot be next to each other ");
isColor = false;
count--;
} else if (temp.length() == 5) {
finalString = finalString + temp.substring(i);
//debugging line
System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length());
i++;
j++;
} else {
finalString = finalString + temp.substring(i, j);
//debugging line
System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length());
i++;
j++;
}
}
}
System.out.println(finalString);
}
}
The following line is definitely wrong:
temp += temp;
You're replacing temp with the current input every iteration, so this will have no effect. Even if that wasn't the case, you'd just be adding the same string to itself - e.g. "A" would become "AA."
I assume you meant
finalString += temp;
or something to that effect.
In general, it seems like you're mixing up temp and final in a few places.
One more thing: don't explicitly compare to true and false, it's unnecessary and is generally considered poor style.
My problem is probably ridiculously easy and I'm just missing something. My program crashes due to a null value of cell 1 during its first iteration. i troubleshot a bit myself and realized on iteration 1 the array length is 1 then after all other iterations the length is 2. this initial improper length causes a complete crash. Any ideas?
`import java.util.Scanner;
import java.io.*;
/* Takes in all of users personal information, and weather data. Then proceeds to determine status of day + averages of the data values provided, then reports to user*/
public class ClimateSummary
{
public static void main (String [] args) throws FileNotFoundException
{
Scanner sc = new Scanner (new File(args[0]));
String name = sc.nextLine();
String birthCity = sc.next();
String birthState = sc.next();
String loc = sc.next();
int birthDay = sc.nextInt();
String birthMonth = sc.next();
int birthYear = sc.nextInt();
int highTemp = 0;
double avgTemp;
double avgPrecip;
int coldDays = 0;
int hotDays = 0;
int rainyDays = 0;
int niceDays = 0;
int miserableDays = 0;
double totalTemp = 0;
double totalPrecip = 0;
int i = 0;
while(i <= 5)
{
String storage = sc.nextLine();
String[] inputStorage = storage.split(" "); //couldnt find scanf equiv in c for java so using array to store multiple values.
System.out.println(inputStorage[0]);
int tempTemp = Integer.parseInt(inputStorage[0]);
double tempPrecip = Double.parseDouble(inputStorage[1]);
totalTemp = totalTemp + tempTemp;
totalPrecip = totalPrecip + tempPrecip;
if(highTemp < tempTemp)
{
highTemp = tempTemp;
}
if(tempTemp >= 60.0)
{
hotDays++;
}else{
coldDays++;
}
if(tempPrecip > 0.1)
{
rainyDays++;
}
if(tempTemp >= 60.0 || tempTemp <= 80.0 || tempPrecip == 0.0)
{
niceDays++;
}else if(tempTemp < 32.0 || tempTemp > 90.0 || tempPrecip > 2.0)
{
miserableDays++;
}else{
}
i++;
}
avgTemp = totalTemp/5;
avgPrecip = totalPrecip/5;
System.out.println("Name: " + name);
System.out.println("Place of birth: " + birthCity + "," + birthState);
System.out.println("Data collected at: " + loc);
System.out.println("Date of birth: " + birthMonth + " " + birthDay +", " + birthYear);
System.out.println("");
System.out.println("The highest temperature during this tine was " + highTemp + " degrees Farenheit");
System.out.println("The average temperature was " + avgTemp + " degrees Farenheit");
System.out.println("The average amount of precipitation was " + avgPrecip + " inches");
System.out.println("Number of hots days = " + hotDays);
System.out.println("Number of cold days = " + coldDays);
System.out.println("Number of rainy days = " + rainyDays);
System.out.println("Number of nice days = " + niceDays);
System.out.println("Number of miserable days = " + miserableDays);
System.out.println("Goodbye and have a nice day!");
}
Eric Thomas
Columbus
Nebraska
Columbus
18
February
1990
54 0
44 2.2
64 0.06
26 0.5
34 0.02
If your file contains null values then you should handle it separately.... using something like this:
if (name == null) {
//do something
}
else {
// do something else;
}
A good discussion on nulls can be seen here...How to check for null value in java
Also, after splitting a string, you need to check if the array (which is the output) has values at the indices that you are using.
For example:
String name = "A/B/C";
String[] nameArray = name.split("/");
In the above case, nameArray[3] will throw an error.