Hi I want to put my prints in a for-loop. how to do it? So something like
if index = 0,1,2 print.
if index = 2,3,4 print.
if index = 4,5,6 print.
Code:
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.println("\n\nThis starts to look like calculations:");
System.out.print("\n" + objectList.get(0));
System.out.print(" "+ objectList.get(1));
System.out.print(" " + objectList.get(2) + " =");
System.out.print("\n\n" + objectList.get(2));
System.out.print(" " + objectList.get(3));
System.out.print(" " + objectList.get(4)+ " =");
System.out.print("\n\n" + objectList.get(4));
System.out.print(" " + objectList.get(5));
System.out.print(" " + objectList.get(6) + " =");
output:
This starts to look like calculations:
1 + 3432.123 =
3432.123 * 4535 =
4535 - 24.4 =
private String buildOperation(int pos){
String output;
if(pos == 0) {
output = "+";
}else if(pos == 1){
output = "*";
}else {
output = "-";
}
return output;
}
List<Object> objectList = new ArrayList(res);
for(int i = 0; i < objectList.size()-1; i++){
System.out.println(objectList.get(i) + buildOperation(i) + objectList.get(i+1) + "=");
}
Additionaly I'll use a HashMap with the operations to avoid all if/else conditions
Map<Integer,String> operations = new HashMap{}
operations.put(0,"+");
operations.put(1,"*");
operations.put(2,"-");
System.out.println(objectList.get(i) + operations.get(i) + objectList.get(i+1) + "=");
}
Final solution now the String size does not matter anymore.
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.print("\n\nThis starts to look like calculations:");
int maxi= objectList.size();
maxi = maxi -2;
System.out.println("\n\nmaxi = " + maxi);
for (int i = 0; i < maxi; i+=2) {
System.out.println("");
System.out.println(i);
System.out.print("\n\n" + objectList.get(i));
System.out.print(" " + objectList.get(i + 1));
System.out.print(" " + objectList.get(i + 2)+ " =");
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);
}
Hi guys this is my first post in this website and I'm still new to Java. This my code that i am working on.
public static void main(String[] args) throws Exception {
// debug
if ($DEBUG) System.out.println("starting\n");
//read data from text file into arrays w,p
String[] wArr = new String[50];
String[] pArr = new String[50];
String fileName = "homs.txt";
readFile(fileName, wArr, pArr);
//main control loop
while (true) {
//use input dialog to get 2 words from user
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
String[] words = input.split("\\s+");
String w1 = words[0];
String w2 = words[1];
//check each word if in dictionary
int w1ix = chkFound(wArr, w1);
boolean isFound = (w1ix >= 0);
System.out.println(w1 + " is found: " + isFound);
int w2ix = chkFound(wArr, w2);
boolean isFound2 = (w2ix >= 0);
System.out.println(w2 + " is found: " + isFound2);
if (w1ix >=0 && w2ix >=0 ) msg = "both words " + w1 + " and " + w2 +
"\n\tare in dictionary";
else { msg = "one or more words not in dictionary: ";
if (w1ix <0) msg += w1 + " ";
if (w2ix <0) msg += w2 + " ";
System.out.println(msg);
//check if homonyms
boolean isHom = chkHom(pArr, w1, w2);
//output result
String line = msg +
"\nWord 1: " + w1 +
"\nWord 2: " + w2 +
"\nWord 1 in dictionary: " + isFound +
"\nWord 2 in dictionary: " + isFound2 +
"\nHomonyms: " + isHom;
JOptionPane.showMessageDialog(null, line);
//ask user to continue Y/N?
int cont = JOptionPane.showConfirmDialog(null, "Continue?");
if (cont > 0)
break;//exit loop or continue
}
//end main
}
}
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
My problem for this code is that when i run it it keeps looping
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
I think the reason for this problem is this part of the code. I have not come up with a solution for this though.
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
https://docs.oracle.com/javase/7/docs/api/constant-values.html#javax.swing.JOptionPane.OK_OPTION
public static final int OK_OPTION 0
your break doesn't work
if (cont > 0)
break;//exit loop or continue
change it to:
final int cont = JOptionPane.showConfirmDialog(null, "Continue?","Continue?", JOptionPane.YES_NO_OPTION);
if(cont == JOptionPane.NO_OPTION){
break;
}
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.