I have this simple program where I am trying to output all the cards in a deck of cards.
However it is only outputting the 1-9 cards of each set, and none of the face cards. i.e. only the for loop with j is being executed, but not the f for loop involving the cardFace array. Why is this?
public class cards {
public final String cardValue[] = {"Heart", "Diamond", "Spade", "Club"};
public final String cardFace[] = {"Jack", "Queen", "King", "Ace"};
public void outputCards() {
for (int i = 0; i < cardValue.length; i++) {
int k = 1;
if (k <= 9) {
for (int j = 1; j <= 9; j++) {
System.out.println("The Card is a " + j + " And is a " + cardValue[i]);
k++;
}
} else {
for (int f = 10; f < cardFace.length; f++) {
System.out.println("The Card is a " + f + " And is a " + cardValue[i]);
k++;
}
}
}
}
}
for(int i = 0; i <cardValue.length; i++){
int k = 1;
if(k <=9){
...
Given the preceding code, it'll always enter on the if and never on the else. Therefore, the for that uses the f variable, will never be executed.
Even if your code got to the loop it will never run because this for condition will never be true:
for(int f = 10; f < cardFace.length; f++){
If you inspect the cardFace array and get its length, you'll see that it is always less than f.
Most all of your logic is a bit off. I suggest that you write out the program steps on paper first, thinking through the steps before trying to commit it to code, because usually these types mistakes are caused by coding before thinking.
Related
I'm supposed to modify code that I've written for an assignment:
public class ToweringStrings2 {
public static final int H = 2; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print("+");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("#");
}
System.out.println();
}
}
so that it prints sequential numbers starting at 1, instead of +s. Currently, it prints:
This is what the new code is supposed to print:
and so on.
For some reason I'm just really stuck and can't figure it out.
You can create an extra variable to print and increment
Like that:
public class ToweringStrings2 {
public static final int H = 10; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
int count = 1;
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print(count++ + " ");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("# ");
}
System.out.println();
}
}
Step 1 - make it print a variable rather than a hard-coded string. Instead of System.out.print("+"), System.out.print(counter).
For this to work you need to have declared counter somewhere in the same scope as the statement: int counter = 0.
Run this. You'll see it print "0" where it used to print "+".
Step 2 - Now you need to make counter increase by one every time it prints.
Find the right place to add:
counter = counter + 1;
Run it and see it work.
Further notes
A more concise alternative to var = var + 1 is var++.
You can even do this at the same time as you use the value of a variable:
System.out.println(var++);
This can be used to express some algorithms very concisely -- but it can be confusing for beginners, so feel free to not use this technique until you're comfortable with the basics.
The variable "num" is a 2D array. I'm trying to check in that array, if there are any duplicates. "num" is a user-input.
I have extensively looked through Java documentation and asked my lectures and I can't get a working answer. I understand the concept, what I'm meant to do, but just can't get the coding right.
Here is my code:
for(int i = 0; i < 3; i++){ //3 rows with 5 numbers each
for(int j = 0; j < 5; j++){
num[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value for line: " + i + " and position: "+ j ));
if((num[i][j] == num[i][0]) || (num[i][j] == num[i][1]) ||(num[i][j] == num[i][2]) || (num[i][j] == num[i][3]) || (num[i][j] == num[i][4])){
if(num[i][j] != 0){
num[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "ERROR. Enter value for line: " + i + " and position: "+ j ));
}
}
}
}
I have also tried using HashSet, but I think that only works with 1D arrays.
I would like to use something like this, as I feel this I understand the most:
secret = new Random().ints(1, 40).distinct().limit(5).toArray();
But obviously not with Random.
I've tried this:
Set<Integer> check = new HashSet<>();
Random gen = new Random();
for(int i = 0; i < 3; i++){ // 3 rows, 5 numbers
for(int j = 0; j < 5; j++){
num[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value for row " + i + " and position " + j));
check.add(gen.nextInt(num[i][j]));
}
}
This last section of coding (directly above this) compiles and runs, but doesn't check for duplicates.
There are alternative ways to checking for duplicates (e.g. you could loop back through the data you've entered previously into the 2D array in order to check for duplicate values) however here's how I'd go about using a Set to check for duplicates in order to, Are you trying to populate the 2d array with all unique values, where each value is from the user?? (also - knowing this explicitly in the original post would be very helpful, thanks to Michael Markidis for specifying that)
With a little UX knowledge here, separating the ERROR is def helpful to the end-user, as ERROR + re-input at the same time is confusing.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;
public class App {
public static void main(String[] args) {
int[][] num = new int[3][5];
System.out.println("Before:");
for (int i = 0; i < 3; ++i)
System.out.println(Arrays.toString(num[i]));
Set<Integer> data = new HashSet<Integer>();
for (int i = 0; i < 3; i++) { // 3 rows with 5 numbers each
for (int j = 0; j < 5; j++) {
boolean isGoodInput = false;
while (!isGoodInput) {
String input = JOptionPane.showInputDialog(null, "Enter value for line: " + i + " and position: " + j);
Integer n = Integer.parseInt(input);
if (data.contains(n)) {
JOptionPane.showMessageDialog(null, "ERROR: Try again");
} else {
num[i][j] = n;
isGoodInput = data.add(n);
}
}
}
}
System.out.println("After:");
for (int i = 0; i < 3; ++i)
System.out.println(Arrays.toString(num[i]));
}
}
Note: the 2D array is limited to your specification in the original post as a 3x5, so you'd have to change these values in multiple places to make different sized arrays - perhaps making these more dynamic could speed up further development of this application in the future.
Here's one way to accomplish this where you use the hashset to track what has already been inserted into the 2D array:
int[][] num = new int[3][5];
Set<Integer> check = new HashSet<>();
for (int i = 0; i < 3; i++)
{ // 3 rows, 5 numbers
for (int j = 0; j < 5; j++)
{
int n = 0;
do
{
n = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value for row " + i + " and position " + j));
} while (!check.add(n)); // keep looping if it was in the hashset
// add it to the array since we know n is not a duplicate at this point
num[i][j] = n;
}
}
I am learning to code Java, and in a tutorial I learned to make the percentage of the percentage of wins I got. I am really confused what the integer "a" does exactly. Can someone please explain it in simple terms? (because I'm a complete newb)
double numOfGames = 10000;
double arrayNum = 1;
Random r = new Random();
int[] num = new int[(int) arrayNum]; // same as "= {0,0,0,0,0}
boolean gameResult = true;
boolean[] odds = new boolean[(int) numOfGames];
double numOfWins = 0;
for (int a = 0; a < numOfGames; a++) {
for (int i = 0; i < num.length; i++) {
num[i] = r.nextInt(100) + 1;
if (num[i] % 2 == 0) {
} else {
gameResult = false;
}
}
if (gameResult) {
odds[a] = true;
}
gameResult = true;
}
for (int i = 0; i < odds.length; i++) {
if (odds[i]) {
numOfWins++;
}
}
double perWin = (numOfWins / numOfGames) * 100;
System.out.println(perWin + " % of an array with " + arrayNum
+ " positions.");
}
}
It's a counter.
Basically it goes up by one every time that code block is run, in plain English this:
for (int a = 0; a < numOfGames; a++) {
// Do things.
}
Is like saying "Start counting at 0; Do things repeatedly until the counter reaches numOfGames".
a++ is just shorthand for a = a + 1 or "add 1 to a".
int = a is a local variable (an integer number) that increases by one in each iteration of your for loop. it simply goes from 0 to the total number of games, in this case: 10000. when it reaches the number of total games, it is discarded.
public class trothBrthdays {
public static void main ( String args [] ) {
Random day = new Random();
int days[] = new int[366];
int smallest = 0;
int largest = 885000;
for (int i = 1; i <= 885000; i++)
{
int persons = day.nextInt(365) + 1;
days[persons] += 1;
}
for (int a = 1; a <= 365; a++)
{
System.out.printf ( " \nDay %d: %d ", a, days[a]);
}
Here program finds day with most birthdays on it
for (int b = 0; b < days.length;)
{
if(days[b] > smallest)
{
largest = days[b];
System.out.printf ( "\nLargest: %d ", days[b]);
}
}
Here program finds day with least birthdays on it
for (int c = 0; c > days.length;)
{
if (days[c] < largest)
{
smallest = days[c];
System.out.printf ( "\nSmallest: %d ", days[c]);
}
}
}
}
The problem is when the program gets to finding the largest number it infinitely loops the largest number and I can't figure out why. I'm still a Beginner program and would love constructive criticism on how to format and type this program.
The reason this is happening is because of your for loops:
for (int b = 0; b < days.length;)
The construction of a for loop is in three parts. Part one is the iterator's declaration:
(int b = 0;
part two is the break condition. That is, what condition must be met, else the loop breaks.
b < days.length;
finally, the third part determines what should change between each iteration. But your for loop is missing that part. It should be...
b++)
Edit:
The second problem that you have is that this will not work with the code as it is written. But I suppose that will be an exercise for you to figure out why.
Hello I'm new to programming and registered to this forum :)
So I created a little program with nested for loops that prints out all combinations of five numbers which can have a value from 0 to 5. With nested for-loops this works fine. But isn't there a cleaner solution? I tried it with calling the for loop itself, but my brain doesn't get the solution.. :(
//my ugly solution
int store1, store2, store3, store4, store5;
for (int count = 0; count <= 5; count++) {
store1 = count;
for (int count2 = 0; count2 <= 5; count2++) {
store2 = count2;
for (int count3 = 0; count3 <= 5; count3++) {
store3 = count3;
for (int count4 = 0; count4 <= 5; count4++) {
store4 = count4;
System.out
.println(store1 + " " + store2 + " " + store4);
}
//I'm trying around with something like this
void method1() {
for (int count = 0; count <= 5; count++) {
list.get(0).value = count;
count++;
method2();
}
}
void method2() {
for (int count = 0; count <= 5; count++) {
list.get(1).value = count;
count++;
method1();
}
}
Usually when people try to use recursion or functional, using a loop is simpler or faster. However, in this case recursion is the simpler option in combination with a loop.
public static void method(List<Integer> list, int n, int m) {
if (n < 0) {
process(list);
} else {
for(int i = 0; i < m; i++) {
list.set(n, i);
method(list, n-1, m);
}
}
}
I know that you are trying combinations but this might help.
Permutation with repetitions
When you have n things to choose from ... you have n choices each time!
When choosing r of them, the permutations are:
n × n × ... (r times) = n^r
//when n and r are known statically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i = 0, j = 0;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
System.out.println(values[j] + " " + values[i]);
}
}
}
}
//when n and r are known only dynamically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i[] = new int[r];
int rc = 0;
for(int j=0; j<Math.pow(n,r); j++)
{
rc=0;
while(rc<r)
{
System.out.print(values[i[rc]] + " ");
rc++;
}
System.out.println();
rc = 0;
while(rc<r)
{
if(i[rc]<n-1)
{
i[rc]++;
break;
}
else
{
i[rc]=0;
}
rc++;
}
}
}
}
Something like this?
// Print all sequences of len(list)+n numbers that start w/ the sequence in list
void method( list, n ) {
if ( list.length == n )
// print list
else for ( int c=0; c<=5; c++ ) {
// add c to end of list
method( list, n );
// remove c from end of list
}
}
Initial call would be method( list, 5 ) where list is initially empty.
here another interative but less elegant version
while (store1 < 6) {
store5++;
if (store5 == 6) {
store5 = 0;
store4++;
}
if (store4 == 6) {
store4 = 0;
store3++;
}
if (store3 == 6) {
store3 = 0;
store2++;
}
if (store2 == 6) {
store2 = 0;
store1++;
}
System.out.println(store1 + " " + store2 + " " + store3 + " " + store4 + " " + store5 + " ");
}
The simplest code I can think of would tackle the problem with an entirely different approach:
public class TestA {
public static void main(String[] argv) {
for (int i=0; i<(6 * 6 * 6 * 6 * 6); ++i) {
String permutation = Integer.toString(i, 6);
System.out.println("00000".substring(permutation.length()) + permutation);
}
}
}
From your text (not your code) I gather you have 5 places and 6 symbols, which suggests there are 6 to the 5th power combinations. So the code just counts through those numbers and translates the number to the output combination.
Since this can also be viewed as a number system with base 6, it makes use of Integer.toString which already has formatting code (except the leading zeros) for this. Leading zeros are added where missing.