So i'm trying to make a program which create and print an array made of 29 index with 5 of those being "A" and the 24 others being "-". I've ran across the problem where it's either giving me an outofbound error or just not putting 5 "A" on the board.
Here is what i've tried so far.
static String[] placeRandomAppleAroundBoard(String[] board) throws java.lang.ArrayIndexOutOfBoundsException{ //ADD "A" TO RANDOM INDEX IN BOARD
int x = 5;
while (checkForAInArray(board)==false) {
for (int i = 0; i < x; i++) {
int j = (int)(Math.random()*board.length);
while(board[j-1].equals("A") || board[j+1].equals("A")){ //Make sure there's no A beside another "A"
j = (int)(Math.random()*board.length);
}
board[j] = "A";
}
x = CountAInArray(board);
}
return board;
}
static boolean checkForAInArray(String[] board){ //Make sure there is 5 "A" in the program
int countOfA = 0;
for (int i = 0; i < board.length; i++) {
if(board[i].equals("A")){
countOfA++;
}
}
if(countOfA==5){
return true;
}
else{
return false;
}
}
static int CountAInArray(String[] board){ //Control the number of time the For-loop of
placeRandomAppleAroundBoard
iterate, which is 5 based and then change depending on how much "A" there's on the board
int countOfA = 0;
for (int i = 0; i < board.length; i++) {
if(board[i].equals("A")){
countOfA++;
}
}
if(countOfA==0){
return 5;
}
else{
return 5 - countOfA;
}
}
So as you can see, i've tried to control the number of time the ForLoop add "A" in the board, that didn't work. I've also tried check for the number of "A" already present in the board but that didn't seem to do the tricks
I am expecting a board printed like so :
static void printboard(String[] board){
System.out.println(board[0] + "|" + board[1] + "|" + board[2] + "|" + board[3] + "|" + board[4] + "|" + board[5] + "|" + board[6] + "|" + board[7] + "|" + board[8] + "|" + board[9]);
System.out.println(board[10] + "|" + board[11] + "|" + board[12] + "|" + board[13] + "|" + board[14] + "|" + board[15] + "|" + board[16] + "|" + board[17] + "|" + board[18] + "|" + board[19]);
System.out.println(board[20] + "|" + board[21] + "|" + board[22] + "|" + board[23] + "|" + board[24] + "|" + board[25] + "|" + board[26] + "|" + board[27] + "|" + board[28] + "|" + board[29]);
}
Thanks for you're help!!
So, i've found the trick ! ahahah, pretty simple actually, here it is :
static String[] placeRandomAppleAroundBoard(String[] board) throws java.lang.ArrayIndexOutOfBoundsException{
int iterationNumber = checkForNumberOfAInArray(board);
for (int i = 0; i < iterationNumber; i++) {
int j = (int)(Math.random()*board.length);
while(board[j-1].equals("A") || board[j+1].equals("A") || board[j].equals("A")){
j = (int)(Math.random()*board.length);
}
board[j] = "A";
}
return board;
}
static int checkForNumberOfAInArray(String[] board){
int countOfA = 0;
for (String x : board) {
if(x == "A"){
countOfA++;
}
}
System.out.println(countOfA);
return (5 - countOfA);
}
And then, you basically use the second function to iterate X number of time with the first function.
What about:
String[] board = new String[29];
Arrays.fill(board, "-");
for(int i = 0;i < 5;i++) {
board[i] = "A";
}
Collections.shuffle(Arrays.asList(board));
System.out.println(Arrays.toString(board));
Related
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);
}
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.
I wrote this code here. It is supposed to print out the iteNum.length (array) which is determined by the user input, but it only does one iteration and then it stops. I can't figure out why.
for (int i = 0; i < iteNum.length; i++) {
System.out.print("Num:" + (i+1) + " ");
for (i = 0; i < cMiles.length; i++) {
System.out.print(" (sc" + (i+1) + ":)" + cRandom[i] + " (tsc" + (i+1) + ":)" + df.format(cTimes[i]) + " ");
}
for (i = 0; i < fMiles.length; i++){
System.out.print(" (sf"+ (i+1) + ":)" + df.format(fRandom[i]) + " (tsf" + (i+1) + ":)" + df.format(fTimes[i])+ " " );
}
System.out.print("(cT:)" + df.format(cSum) + " (fT:)" + df.format(fSum));
if (cSum < fSum) {
System.out.print(" City is faster");
}
else {
System.out.print(" Freeway is faster");
}
}
You're reusing the same i variable in the inner and outer loops. Use separate variables.
for (int i = 0; i < iteNum.length; i++) {
for (int j = 0; j < cMiles.length; j++) {
...
}
}
As say #John you are using same iterator variable i, instread of using another one
And also this code can be simplified
if (cSum < fSum) {
System.out.print(" City is faster");
}
else {
System.out.print(" Freeway is faster");
}
like that
System.out.print((cSum < fSum) ? " City is faster" : " Freeway is faster");
On my opinion ternary operator more clear.
for(int counter = 0; counter < args.length; counter++){
System.out.println("Displaying per words: " + args[counter]);
splitWords = args[counter].toCharArray();
for(int counter2 = 0; counter2 < splitWords.length; counter2++){
System.out.println("Word spliced: " + splitWords[counter2]);
System.out.println("The number equivalent of " + splitWords[counter2] + " is "
+ (int) splitWords[counter2]);
occurenceCount[(int)splitWords[counter2]]++;
System.out.println("The letter " + splitWords[counter2] +
" was shown " + occurenceCount[(int)splitWords[counter2]] + " times.");
}
}
My function doesn't detect counter2 as a variable since it was inside the nested for loop. So how do I get out of this dilemma?
I'm trying to use the argument inputs (string respectively) and post the number of occurrences using an ascii table as reference and, as you see, there's just one obstacle from stopping me from accomplishing that.
Any ideas?
Your primary problem is that you have missed one important fact - your counts are not complete until after your loop has completed.
You therefore need to print out your counts in a separate loop after your first loop is complete.
public void test() {
String[] args = {"Hello"};
int[] occurenceCount = new int[256];
for (int word = 0; word < args.length; word++) {
System.out.println("Displaying per words: " + args[word]);
char[] splitWords = args[word].toCharArray();
for (int character = 0; character < splitWords.length; character++) {
System.out.println("Word spliced: " + splitWords[character]);
System.out.println("The number equivalent of " + splitWords[character] + " is "
+ (int) splitWords[character]);
occurenceCount[(int) splitWords[character]]++;
System.out.println("Word spliced: " + splitWords[character]);
}
}
// Scond loop to print the results.
for (int character = 0; character < occurenceCount.length; character++) {
int count = occurenceCount[character];
if (count > 0) {
System.out.println("The letter " + ((char) character)
+ " was shown " + count + " times.");
}
}
}