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 static void stats(){
System.out.println("\nName : " +characterName+ " " +characterClass);
System.out.println("Level : " + Level); //Output the value of Level
do {
int []statValues = new int[]{Str, Dex, Con, Int, Wis, Cha};
String[] stats = new String[]{"Str", "Dex", "Con", "Int", "Wis", "Cha"};
int amount;
for (int i = 0; i<statValues.length;i++) {
statValues[i] = rollDice();
amount = statValues[i];
System.out.print(stats[i]+ " : " +statValues[i]);
if (amount == 10 || amount == 11) {
Bonus = 0;
System.out.print(" [ " + Bonus + "]\n");
}
//Bonus value for integers less than 10
else if (amount < 10) {
Bonus = 0;
bonusCounter = amount;
while (bonusCounter < 10) {
if (bonusCounter % 2 == 1) {
Bonus = Bonus + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[-" + Bonus + "]\n");
}
//Bonus value for integers greater than 10
else {
Bonus = 0;
bonusCounter = 11;
while (bonusCounter <= amount) {
if (bonusCounter % 2 == 0) {
Bonus = Bonus + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[+" + Bonus + "]\n");
}
}
System.out.println("Type \"yes\" to re-roll or press any key to terminate the program");
reRoll = sc.next();
}
while (reRoll.equals("yes"));
}
}
This is just a part of a code. Here i need to calculate the bonus for the Con stat using the variable conBonus. Because in the main method i need to calculate the hitpoints and for that the bonus value used is the bonus in conBonus.
Below is the class where the main method is given.
public class Game {
public static void main(String[] args) {
Character.level();
Character.Class();
Character.stats();
int hitPoints;
hitPoints = Character.Level*((int)((Math.random()*Character.hitDice)+1)+Character.conBonus);
System.out.println("HP : [" +hitPoints+ "]");
}
Will passing the bonus amounts to an array work. If so how can i pass it?
Here is how to store Bonus for each category:
First, change Bonus from an int to an array:
static int[] Bonus;
And in main, create a size of 6:
Bonus = new int[6];
Now to calculate hitPoints, use the array (notice that "Con" is array value 2, or the third element of the array: { "Str", "Dex", "Con", "Int", "Wis", "Cha" }
hitPoints = Character.Level * ((int) ((Math.random() * Character.hitDice) + 1) + Character.Bonus[2]);
Here is the new stats method, which uses the new Bonus array:
public static void stats() {
do {
System.out.println("\nName : " + characterName + " " + characterClass);
System.out.println("Level : " + Level); // Output the value of Level
int []statValues = new int[]{Str, Dex, Con, Int, Wis, Cha};
String[] stats = new String[] { "Str", "Dex", "Con", "Int", "Wis", "Cha" };
int amount;
for (int i = 0; i < statValues.length; i++) {
statValues[i] = rollDice();
amount = statValues[i];
System.out.print(stats[i] + " : " + statValues[i]);
if (amount == 10 || amount == 11) {
Bonus[i] = 0;
System.out.print(" [ " + Bonus[i] + "]\n");
}
// Bonus value for integers less than 10
else if (amount < 10) {
Bonus[i] = 0;
bonusCounter = amount;
while (bonusCounter < 10) {
if (bonusCounter % 2 == 1) {
Bonus[i] = Bonus[i] + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[-" + Bonus[i] + "]\n");
}
// Bonus value for integers greater than 10
else {
Bonus[i] = 0;
bonusCounter = 11;
while (bonusCounter <= amount) {
if (bonusCounter % 2 == 0) {
Bonus[i] = Bonus[i] + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[+" + Bonus[i] + "]\n");
}
}
System.out.println("Type \"yes\" to re-roll or press any key to terminate the program");
reRoll = sc.next();
} while (reRoll.equals("yes"));
}
This is my Android Java code . I don't understand why it is not working like java code . it is example of prime number . Suppose we want to find prime number between 1 to 5 . So I expect the result 2, 3, 5 . But I only got the result 5 . In my Java code I got the correct result . I mean 2, 3, 5 . Please help me figure out this problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prime);
Button btn = (Button)this.findViewById(R.id.click_btn);
btn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
TextView resp = (TextView) findViewById(R.id.response);
// Get number from EditText
EditText startnumber = (EditText) findViewById(R.id.first_number);
EditText endnumber = (EditText) findViewById(R.id.second_number);
// get the Strings from the EditTexts
String number1 = startnumber.getText().toString();
String number2 = endnumber.getText().toString();
// Convert Strings to int
int x1number = Integer.parseInt(number1);
int x2number = Integer.parseInt(number2);
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
//resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( str + String.valueOf(i));
}
}
}
});
}
public static boolean isPrime(int n){
if( n <= 1) {
return false;
}
for( int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
Here is my Java code .
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package primenumberstwo;
import java.util.Scanner;
/**
*
* #author vubon
*/
public class PrimeNumberstwo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
System.out.println("Enter your first number: ");
int start = s.nextInt();
System.out.println("Enter your second number: ");
int end = s.nextInt();
System.out.println("List of prime numbers bettween " + start + " and " + end);
for(int i = start; i <= end; i++){
if(isPrime(i)){
System.out.println(String.valueOf(i));
}
}
}
public static boolean isPrime(int n){
if( n <= 1) {
return false;
}
for( int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
You are overwriting the content of the TextView resp in each iteration that's why you see just le last one.
Try something like this:
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
String result = "";
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
result = result + " " + i;
}
}
if(!("".equalsIgnoreCase(result.trim()))){
resp.setText(str + result);
}
Problem is not in Android SDK. your logic is wrong.
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
//resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( str += String.valueOf(i));//see change here
}
}
Try with:
str = str + String.valueOf(i);
resp.setText(str);
you have found all prime numbers but override with last one on last loop iterate.
Try that;
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( resp.getText() + String.valueOf(i));
}
}
I have code that searches for a term in a string and want it to find it then it counts and outputs the total. I am trying to search for another term and output the total of that term.
For example:
for(String[] passenger : passengerList) {
if(passenger[3].equalsIgnoreCase("female")) {
allFemale++;
if(passenger[1] != null && Integer.parseInt(passenger[1]) == 1 {
femaleSurvivors++;
}
}
count ++;
}
System.out.println("The number of females who survived: ");
return femaleSurvivors;
}
Now, I want to search for the male and count the times that occurs. Not having any luck.
You would really need to keep track of 4 things, sex (m/f) and status (dead/alive). You can do it all in a single loop. Part of it can be captured in the loop, and part of it could be calculated after the fact.
int survivors = 0;
int femaleSurvivors = 0;
int femaleDeaths = 0;
for(String[] passenger : passengerList) {
boolean isFemale = false;
if(passenger[3].equalsIgnoreCase("female")) {
isFemale = true;
}
if(passenger[1] != null && Integer.parseInt(passenger[1]) == 1) {
survivors ++;
if (isFemale){
femaleSurvivors++;
}
} else {
if (isFemale){
femaleDeaths++;
}
}
}
int totalPassengers = passengerList.size();
int maleSurvivors = survivors - femaleSurvivors;
int deaths = totalPassengers - survivors;
int maleDeaths = deaths - femaleDeaths;
int males = maleSurvivors + maleDeaths;
int females = totalPassengers - males;
System.out.println("Survivors (Total/M/F): " + survivors + "/" + maleSurvivors + "/" + femaleSurvivors);
System.out.println("Deaths (Total/M/F): " + deaths + "/" + maleDeaths + "/" + femaleDeaths);
System.out.println("Totals (All/M/F): " + totalPassengers + "/" + males + "/" + females);
Here I am to ask something weird.
I would like to ask that is there any method/logic by which we can convert an integer value to a string value containing the English words for the number?
E.g user inputs 22 and gets the output twenty two or two.
Thanks
Check out this code, it might be what you're looking for. For example, inside the main method if we had:
System.out.println(convert(22));
Output:
twenty two
EDIT I've reproduced the code below, cleaning up the formatting a bit (main-method is at the bottom):
import java.text.DecimalFormat;
public class EnglishNumberToWords {
private static final String[] tensNames = { "", " ten", " twenty",
" thirty", " forty", " fifty", " sixty", " seventy", " eighty",
" ninety" };
private static final String[] numNames = { "", " one", " two", " three",
" four", " five", " six", " seven", " eight", " nine", " ten",
" eleven", " twelve", " thirteen", " fourteen", " fifteen",
" sixteen", " seventeen", " eighteen", " nineteen" };
private static String convertLessThanOneThousand(int number) {
String soFar;
if (number % 100 < 20) {
soFar = numNames[number % 100];
number /= 100;
} else {
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
}
if (number == 0)
return soFar;
return numNames[number] + " hundred" + soFar;
}
public static String convert(long number) {
// 0 to 999 999 999 999
if (number == 0) {
return "zero";
}
String snumber = Long.toString(number);
// pad with "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int billions = Integer.parseInt(snumber.substring(0, 3));
// nnnXXXnnnnnn
int millions = Integer.parseInt(snumber.substring(3, 6));
// nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(snumber.substring(6, 9));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(9, 12));
String tradBillions;
switch (billions) {
case 0:
tradBillions = "";
break;
case 1:
tradBillions = convertLessThanOneThousand(billions) + " billion ";
break;
default:
tradBillions = convertLessThanOneThousand(billions) + " billion ";
}
String result = tradBillions;
String tradMillions;
switch (millions) {
case 0:
tradMillions = "";
break;
case 1:
tradMillions = convertLessThanOneThousand(millions) + " million ";
break;
default:
tradMillions = convertLessThanOneThousand(millions) + " million ";
}
result = result + tradMillions;
String tradHundredThousands;
switch (hundredThousands) {
case 0:
tradHundredThousands = "";
break;
case 1:
tradHundredThousands = "one thousand ";
break;
default:
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
+ " thousand ";
}
result = result + tradHundredThousands;
String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;
// remove extra spaces!
return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}
public static void main(String[] args) {
System.out.println(convert(22)); // "twenty two"
}
}
While the accepted answer works, it would probably be best to use already-implemented functions to perform this. ICU4J contains a class com.ibm.icu.text.RuleBasedNumberFormat that can be used to perform this operation. It also supports languages other than English, and the reverse operation, parsing a text string to integer values.
Here is an example, assuming that we have the ICU4J dependency in the classpath:
import com.ibm.icu.text.RuleBasedNumberFormat;
import java.util.Locale;
RuleBasedNumberFormat nf = new RuleBasedNumberFormat (Locale.UK, RuleBasedNumberFormat.SPELLOUT);
nf.format(24);
// The result is "twenty-four"
I have a very simple solution that can convert whole integer range in java to hinglish notation
String h1[] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Eleven", "Tweleve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen" };
String h2[] = { "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy",
"Eighty", "Ninety" };
String h3[] = { "Hundred", "Thousand", "Lakh", "Crore", "Arab" };
public String parseToHinglishNotation(int num) {
String word = "";
if (num < 0) {
word += "Minus ";
num = -num;
}
if (num < 20) {
word += h1[num];
} else if (num < 100) {
int temp = num / 10 - 2;
word += h2[temp];
temp = num % 10;
if (temp > 0) {
word += " " + parseToHinglishNotation(temp);
}
} else if (num < 1000) {
int temp = num / 100;
word += parseToHinglishNotation(temp) + " " + h3[0];
temp = num % 100;
if (temp > 0) {
word += " " + parseToHinglishNotation(temp);
}
} else if (num < 100000) {
int temp = num / 1000;
word += parseToHinglishNotation(temp) + " " + h3[1];
temp = num % 1000;
if (temp > 0) {
word += " " + parseToHinglishNotation(temp);
}
} else if (num < 10000000) {
int temp = num / 100000;
word += parseToHinglishNotation(temp) + " " + h3[2];
temp = num % 100000;
if (temp > 0) {
word += " " + parseToHinglishNotation(temp);
}
} else if (num < 1000000000) {
int temp = num / 10000000;
word += parseToHinglishNotation(temp) + " " + h3[3];
temp = num % 10000000;
if (temp > 0) {
word += " " + parseToHinglishNotation(temp);
}
} else if (num <= 2147483647) {
int temp = num / 1000000000;
word += parseToHinglishNotation(temp) + " " + h3[4];
temp = num % 1000000000;
if (temp > 0) {
word += " " + parseToHinglishNotation(temp);
}
}
return word;
}
I know this post is kind of old, but I recently came up with my own solution and figured it might be worth sharing. The primary function numToWords takes any Integer between 1 and 9999 (inclusive) and outputs its corresponding English words, followed by the String of digits in parenthesis.
Example: If Integer x = 2614;, numToText(x); returns "Two Thousand Six Hundred Fourteen (2614)":
The digit-equivalent words are stored in HashMaps depending on whether they're multiples of 1 or 10 (e.g. 6 --> "Six", 60 --> "Sixty") while the teens are handled independently with a switch statement.
import java.util.HashMap;
public class Converter{
public Converter(){
hm1.put(0, "");
hm1.put(1, "One");
hm1.put(2, "Two");
hm1.put(3, "Three");
hm1.put(4, "Four");
hm1.put(5, "Five");
hm1.put(6, "Six");
hm1.put(7, "Seven");
hm1.put(8, "Eight");
hm1.put(9, "Nine");
hm10.put(0, "");
hm10.put(1, "");
hm10.put(2, "Twenty ");
hm10.put(3, "Thirty ");
hm10.put(4, "Fourty ");
hm10.put(5, "Fifty ");
hm10.put(6, "Sixty ");
hm10.put(7, "Seventy ");
hm10.put(8, "Eighty ");
hm10.put(9, "Ninety ");
}
public static String numToWords(Integer x){
// Obtain a char[] of the Integer to analyze each digit.
String s = x.toString();
char[] cArray = s.toCharArray();
// Refer to the length of the Integer as its final index.
int l = cArray.length-1;
String retStr = "";
// The loop counts backwards from the right-most digit.
for(int i = l; i >= 0; i--){
// Determine the numeric value at the left-most index, then move rightward.
// This setup is attributed to the nuances of the English language.
int j = Character.getNumericValue(cArray[l-i]);
//
if(i == 3){
retStr += hm1.get(j);
retStr += " Thousand ";
} else if(i == 2){
retStr += hm1.get(j);
retStr += " Hundred ";
} else if(i == 1){
//If the 10s digit is 1, the final word is 10 <= x <= 19.
if(j == 1){
String tens = "";
// Check the 1s digit to determine x (10 <= x <= 19)
switch(Character.getNumericValue(cArray[l])){
case 0: tens = "Ten";
break;
case 1: tens = "Eleven";
break;
case 2: tens = "Twelve";
break;
case 3: tens = "Thirteen";
break;
case 4: tens = "Fourteen";
break;
case 5: tens = "Fifteen";
break;
case 6: tens = "Sixteen";
break;
case 7: tens = "Seventeen";
break;
case 8: tens = "Eighteen";
break;
case 9: tens = "Nineteen";
break;
}
i = -1; // Ensure it's the last word by indexing out of the loop.
retStr += tens;
} else {
//If the 10s digit is 2 <= x <= 9, the 10s word is 20 <= x <= 90.
retStr += hm10.get(j);
}
} else if(i == 0){
retStr += hm1.get(j);
}
}
return retStr + " (" + x + ") ";
}
private HashMap<Integer, String> hm1 = new HashMap<Integer, String>();
private HashMap<Integer, String> hm10 = new HashMap<Integer, String>();
}