This question already has answers here:
How to count the number of occurrences of an element in a List
(25 answers)
Closed 6 years ago.
I'm trying to do a Blackjack game but I don't know how to change the value of "ACE" to 1 if 11 is too high. I'm now trying to search a Arraylist for A's to change the value of one ore more of them. But how can I see how much A's are in my Arraylist?
while (getPointsPC() < 17 || getPointsPC() < getPointsPL()){
int acees = 0;
random = bj.getRandom();
CardsPC.add(bj.getCard(random));
setPointsPC(random);
lblPointsPC.setText("Points Dealer: " + Integer.toString(getPointsPC()));
String text = CardsPC.get(0);
for(int i = 1; i < CardsPC.size(); i++){
text = text + ", " + CardsPC.get(i);
}
if (CardsPC.contains("A") && getPointsPC() > 21 && acees < CardsPC.**HOW_MUCH_A's???**){
setPointsPC(13);
acees++;
}
lblCardsPC.setText(text);
}
Is your CardsPC is your mentioned ArrayList? Just set counter variable:
String text = "";
int counter = 0;
for(int i = 0; i < CardsPC.size(); i++){
text = text + (i > 0 ? ", " : "") + CardsPC.get(i);
if (CardsPC.get(i).contains("A")) { // or use equals, base on your input.
counter++;
// do something with found "A" element if you want.
}
}
Related
I know I'm being a little dumb about this, but I figured id take a break for a few mins and ask this question. I'm trying to add a countdown feature to an input box. The problem is that its doing the input amount a squared number of times when all im really trying to is increment a variable thats called inside the loop itself. I'm certain it will come to me, but getting someone else perspective helps.
String propertyNumber = JOptionPane.showInputDialog("Enter Numer of Properties...");
int propNumber = Integer.parseInt(propertyNumber);
numOfProperties = new float[propNumber];
for(int i= 0; i < propNumber; i++) {
for(int a = propNumber; a >= 0; a--) {
String propertyVal = JOptionPane.showInputDialog("Enter each property value for the " + propNumber + " Properties you listed. You have " + a + " inputs left.");
numOfProperties[i] = Float.parseFloat(propertyVal); //takes property value info and stores them inside the property number array
}
}
Suppose, propNumber = 3. Since, you are using nested loops it will work as follows :
Take the case of the nested loop first :
for(int a = propNumber; a >= 0; a--) {
}
Given propNumber is 3, the code inside it will be executed 3 times.
Take the case of the main loop :
for(int i= 0; i < propNumber; i++) {
//another loop inside
}
As the code inside the main loop will be executed 3 times, the loop inside it will get executed 3 times as well. 3*3 = 9.
As I mentioned in the comments, you do not need a nested loop. I believe you want a single loop and a should be calculated from the number of properties and the current index i. Like,
for (int i = 0; i < propNumber; i++) {
int a = propNumber - i;
String propertyVal = JOptionPane.showInputDialog("Enter each property value for the "
+ propNumber + " Properties you listed. You have " + a + " inputs left.");
numOfProperties[i] = Float.parseFloat(propertyVal);
}
This question already has answers here:
Is there an easy way to output two columns to the console in Java?
(3 answers)
Closed 4 years ago.
I have code here that takes in two different array types, one boolean and one of ints. I want to get the code to print like this
marked edgeTo
------ --------
true 2
true 0
true 0
true 5
true 3
true 0
I am currently using a foreach loop to print out the data and I cannot get edgeTo's data (2 0 0 5 3 0) to print underneath its title edgeTo and across from its respective marked boolean value. Any suggestions as to what I am doing wrong? Here is the snipet of code I have so far
System.out.println("marked edgeTo");
System.out.println("------- --------");
for (boolean el : bob.marked) {
System.out.println(el);
}
for (int el : bob.edgeTo) {
System.out.println(el);
}
if two arrays have same length, you can use 1 loop
System.out.println("marked\tedgeTo");
System.out.println("-------\t------");
for (int i = 0; i < bob.marked.length;i++) {
System.out.println(String.valueOf(bob.marked[i]) + "\t" + String.valueOf(bob.edgeTo[i]));
}
In case your arrays are of different lengths:
System.out.println("marked edgeTo");
System.out.println("------- --------");
int lesserArr = Math.min(bob.marked.length, bob.edgeTo.length);
for (int i = 0; i < lesserArr;i++) {
System.out.println(String.valueOf(bob.marked[i]) + "\t" + String.valueOf(bob.edgeTo[i]));
}
for (int j = 0;j < Math.abs(bob.marked.length-bob.edgeTo.length); j++) {
if (bob.marked.length < bob.edgeTo.length)
System.out.println("\t\t" + String.valueOf(bob.edgeTo[lesserArr + j]));
else
System.out.println(String.valueOf(bob.marked[lesserArr + j]));
}
}
This question already has answers here:
Variable might not have been initialized error
(12 answers)
Initializing multiple variables to the same value in Java
(7 answers)
Closed 5 years ago.
I am trying to assign 3 integer arrays to a method that returns one version. But when i try this it says variable bubbleArray and variable insertionArray have not been initialized. Is there another way to do this and still keep the same original values from the method.
Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();
bubbleSort(radioValue,bubbleArray);
selectionSort(radioValue,selectionArray);
insertionSort(radioValue,insertionArray);
public Integer[] numGenerator() {
Random rn = new Random();
originalOutput.setText("");
sortedOutput.setText("");
referenceArray.clear();
if (number10Button.isSelected()) {
for (int i = 0; i < 10; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number100Button.isSelected()) {
for (int i = 0; i < 100; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number1000Button.isSelected()) {
for (int i = 0; i < 1000; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number5000Button.isSelected()) {
for (int i = 0; i < 5000; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
}
Integer[] bubbleArray = referenceArray.toArray(new Integer[referenceArray.size()]);
return bubbleArray;
}
Your code declares 3 Integer[] variables and assigns the last one to what numGenerator() returns.
Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();
Now since you want three arrays, not just three variables pointing to one array you need to make copies of the array, for example with clone(). If you don't make copies you will have one array which is sorted by bubble sort and the other sorting methods will try to sort an already sorted array, which is not what you want.
Integer[] bubbleArray = numGenerator();
Integer[] insertionArray = bubbleArray.clone();
Integer[] selectionArray = bubbleArray.clone();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to write a program that reads a sequence of integers and divide it into two sequences. The values on odd positions will be the first sequence and the values of even positions will be the second sequence. The program prints the elements of the first sequence and then the elements of the second sequence separated by a single space. The first input value specifies the number of elements.
Input: 7 1 2 4 5 6 8 9
Expected Output: 1 4 6 9 2 5 8
My Output: 2 0
package twosequences;
import java.util.Scanner;
public class TwoSequences {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] values = new int[n];
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
}
int odd = 0;
int even = 0;
int i = 1;
if (i % 2 == 0) {
even = values[i];
} else {
odd = values[i];
}
i++;
System.out.printf("%d %d%n", odd, even);
}
}
I'm not sure why I'm outputting 2 0. Any suggestions?
You need two different loops to iterate over even and odd elements respectively to obtain the desired output.
for (i = 0 ; i < n ; i += 2) {
even = values[i];
System.out.printf("%d ", even);
}
for (i = 1 ; i < n ; i += 2) {
odd = values[i];
System.out.printf("%d ", odd);
}
Hope this helps.
Print the even-numbered elements in one loop; then use another loop to print the odd-numbered elements.
System.out.print(values[0]); // print by itself to avoid prepending " ".
for (int i = 2; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
for (int i = 1; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
System.out.println();
you take the second element of an array (2), and only for that one you are checking if it's even or not.
The result goes true for first 'if', and
even = 2;
, the if statement ends and odd stays as declares (0), that' why u got result like that.
If you want output whith more than 2 integers, you need to change
, where n would be all scanned even numbers.
Try to put a counter in first for loop, like
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
if(values[i]%2==0) evenCounter++;
}
Now to count odds just count values.length - evenCounter.
Also you do not need to make simple arrays like int[], you can go with
List<Integer> list = new ArrayList<>();
You will be able to add elements in for loop withour knowing how many elements you will be implementing.
Hope some of those helps.
My problem requires me to create a list of all 20 amino acids permutations based on a user imputed chain length. For example, I currently have code that works if the user wants a 3 chain length. This is 20^3 possibilities. So I have 3 nested for loops that run through all possibilities, then a counter that outputs the number of permutations to make sure the answer is correct. How could I code this method so it output permutations based on user input?
protected void getPermutations(int chainlength) {
int counter = 0;
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
for (int k = 0; k < 20; k++) {
System.out.println(AcidArray[i].getTcode() + "-"
+ AcidArray[j].getTcode() + "-"
+ AcidArray[k].getTcode());
counter++;
}
}
}
System.out.println("chain length = " + chainlength);
System.out.println(counter + " permutations");
}
Thanks
Recursion is your friend in this situation
protected String getPermutations(int chainlength) {
int counter = 0;
if(chainlength > 0) { // so that the counter is not 1
counter = getSubPermutations("", chainlength));
}
System.out.println("chain length = " + chainlength);
System.out.println(counter + " permutations");
}
private int getSubPermutations(String prefix, int chainlength){
if(chainlength == 0){ //The bottom of the stack, print out the combination
System.out.println(prefix.substring(0,prefix.length-1)); //remove the final '-'
return 1;
} else {
int counter = 0
for(int i = 0; i < 20; i++) {
//Add this level T code to the string and pass it on
counter += getSubPermutations(prefix + AcidArray[i].getTcode() + "-", chainlength-1);
}
return counter;
}
}
What this will do is make a tree of calls. If chainlength is one then it will call getSubPermutations with 1. This will run through the for loop calling getSubPermutations again with the String for the first value and a chainlength of 0. In this case the string will only have one T code in it. Each inner call will hit the first if statement so it will print out the string containing one T code and return 1. All these will be added up so the counter returned to getPermutations will be 20. By this stage all the permutations will have been printed out.
As chain length increases getSubPermuations is called recursively. With a chainlength of 2 it will call getSubPermutations 20 times with a chain length of 1, passing in the string of the T code. Each of these will call getSubPermutations with a chainlength of 0, with a string containing two T codes. This will then print out the full string and return 1. These return values will get added up to 20 as in the previous example but now when they are returned to the next level they are added up to return a final 400 to getPermutations and 400 Strings will have been printed.