I'm currently trying to code a basic Baccarat game, but when I try to add the value of the player's cards together, I'm getting random numbers. The code should take the values of all of its card integers, add them together, and take the one's digit of the number.
Here's my code to get and add the values of the numbers:
public void TakeACard(String c) {
char number;
String temp;
allCard = allCard+c+" ";
if (c.charAt(0)=='J' || c.charAt(0)=='Q' || c.charAt(0)=='K') {
value = 0;
} else if (c.charAt(0)=='A') {
value = 1;
} else {
number = c.charAt(0);
value = Integer.parseInt(String.valueOf(number));
}
hand[numCards] = value;
numCards++;
}
public void GetTotalValue(){
for (int i = 0; i<numCards; i++){
value = hand[i];
total += value;
}
int finalValue = total%10;
System.out.print("Your hand value is: "+ finalValue);
}
Here is the sample output that I am getting:
Your cards are: 2, 6. Your hand value is: 8
Click 1 to get your cards, and click anything else to stop choosing 1
Your cards are: 2, 6, A. Your hand value is: 7
Click 1 to get your cards, and click anything else to stop choosing 1
Your cards are: 2, 6, A, 5. Your hand value is: 1
Does anyone have an idea on why they are not adding together properly and how I can fix it?
You are not resetting total. It's a class variable which will keep growing and growing. What's happening is entirely expected. Let's see:
2 + 6 = 8 (total) --> 8 % 10 = 8
8 (current total) + 2 + 6 + 1 = 17 --> 17 % 10 = 7
17 (current total) + 2 + 6 + 1 + 5 = 31 --> 31 % 10 = 1
Here is how you correct it:
public void GetTotalValue(){
total = 0; // <---- ADD THIS RESET
for (int i = 0; i<numCards; i++){
value = hand[i];
total += value;
}
int finalValue = total%10;
System.out.print("Your hand value is: "+ finalValue);
}
And just a little thing, don't name your function Get... when it returns void. Either return something or rename the function to something else. It's harder to maintain your code when you do not follow any naming convention.
Related
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 2 years ago.
Improve this question
Given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:
Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.
Traverse from left to right and change the first occurrence of 6 to 9. If there is not any 6 while traversal then does not change any digit.
Following code may help:-
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class testing {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
int a=sc.nextInt();
String numberString = Integer.toString(a);
for (int i = 0; i < numberString.length(); i++){
char c = numberString.charAt(i);
if(c=='6') { // check if the digit is 6 or not, if 6 is present then change it to 9
numberString = numberString.substring(0, i) + '9' + numberString.substring(i + 1);
break; // break the loop if 6 is changed to 9
}
}
System.out.println("Largest Number is : "+numberString);
}
}
public class Maximum69 {
public static void main(String[] args) {
int num=6669;
int added = 0;
int cur = 1;
int curNum = num;
while(curNum > 0) {
if(curNum % 10 == 6)
added = cur;
cur *= 10;
curNum = curNum / 10;
}
System.out.println(num + added * 3);
}
}
I found out how to slove, This takes less time to run:
I have found a formule, it could have been a single line solution but for clarity I have divided in two lines
First , get the highest number based on input number of digits , for example if input is 6, topNumber will be 9, for 69 top will be 99 , for 696 top is 999, so topNumber can be 9 or 99 or 999 or 9999 or 99999,etc up to java limit, the formula to get number of digits in an integer is :
floor(log10(input)) + 1
Then you can notice that the top number minus the input, it gives you a number that starts with 3, for example 9-6 = 3 , 99 - 69 = 30 , 999 - 696 = 303, except when the input is equal to the top number, in that case the result is 0,
knowing that fact, we can conclude that for switching the first 6 in the number can be achieved by summing up 3 * (((the position of the 6) -1) * 10) , eg. 3 or 30 or 300 or 3000 or 30000, etc.
resulting in the last part of the function : input + (10^(NumberOfDigits(top - input)) -1) * 3
private static int largest69(int number) {
int topNumber = (int) (Math.pow(10,(int)(Math.log10(number)) + 1) -1);
return number + (int) Math.pow(10,(( (int)(Math.log10(topNumber - number)) + 1 ) -1) ) * 3;
}
If you're not as good as nitinsridar at intuitively implementing math into your algorithm, and if you don't want to mess around with strings like backdoor did, then you can utilize data structures to help you come to a solution without much thought
public static void main(String[] args) {
System.out.println(maxNumber(9669));
}
public static int maxNumber(int number) {
Stack<Integer> numbers = new Stack<Integer>();
int numberLength = 0;
while(number > 0) {
numbers.push(number % 10);
number /= 10;
numberLength++;
}
boolean changedFirstOccurrence = false;
int maxNumber = 0;
for(int i = numberLength; i > 0; i--) {
int numberToAdd = numbers.pop();
if (numberToAdd == 6 && !changedFirstOccurrence) {
numberToAdd = 9;
changedFirstOccurrence = true;
}
maxNumber += numberToAdd * (int) Math.pow(10, i);
}
return maxNumber / 10;
}
Is this the best solution? Nope, I would go with nitinsridar's answer (I also believe that his/her answer should get the green checkmark).
Backdoor's answer is definitely how I would've solved this problem before I took my data structures and algorithms class. I'm not saying it's a bad answer. In fact, his algorithm is more concise than mine. It's just my opinion that you don't want to get in the habit of relying on string manipulation to solve these sort of "numerical" problems, because one day it's not going to work; in this case, it did. I'm just providing another way of doing it
Considering two variables:
"n" is any arbitrary value.
"i" is the number of times a value is increased in a sum before it reaches the value of "n".
So for instance if the value n = 344 is chosen, then i = 26 because:
26 + 25 + 24 + ... + 3 + 2 + 1 = 351
26 is how many times the variable "i" gets added together in a descending order before it either is equal to n = 344 or the first time it surpasses.
public class Trstuff{
public static void main (String [] arg) {
int n = 4;
int i = computeIndex(n);
System.out.print(i);
}
public static int computeIndex(int n) {
int i = 1;
int sum = 0;
for(i = 1; sum <= n; i++) {
sum = sum + i;
}
return i;
}
}
My goal is to choose any "n" value and then have the program return the variable "i" to me.
As my program stands, I thought it should be correct, but somehow it's not. Here is the example with n = 4.
The result should be that "i = 3" because:
1 + 2 = 3
1 + 2 + 3 = 6
So the ascending value of "i" in the loop is added 3 times before the loop supposedly should stop because of the expression "sum <= n" in the loop.
However, when I run the program it returns the value 4 instead. I simply cannot figure out what is wrong and why my program gives me 4 instead of the correct answer, 3?
Read the for loop as follows:
for every value of i while sum smaller or equal to n, add i to sum and increment i
The last part of the line and increment i is executed after the sum of sum + i, but before the next check which checks if sum is smaller or equal to n, with as result that i always is one larger than expected.
The solution could be to use a different exit (different solutions exist):
public static int computeIndex(int n) {
int i = 1;
int sum = 0;
while true {
sum = sum + i;
if sum<n {
i++;
} else break;
}
return i;
}
the sum of p consecutive integers starting at 1 is p*(p+1)/2
so basically you need to solve x^2+x-2*n = 0, with solution
x = 0.5*(sqrt(1+8n)-1)
I'm a Java beginner, please bear with me. :) I haven't learned anything like if statements and such yet, I've only learned about loops, variables, and classes. I need to write a single loop which produces the following output:
10 0 9 1 8 2 7 3 6 4 5 5
I can see from the segment, that the difference between the numbers is reduced by one, so from 10 to 0 it is subtracted 10, then from 0 to 9 it is added by 9, and it goes on alternating between adding and subtracting.
My idea was to create the loop where my variable i = 10 decreases by 1 in the loop (i--) but I'm not quite sure how to alternate between adding and subtracting in the loop?
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 0; i--) {
System.out.print(i + " ");
}
}
}
Why not have two extra variables and the increment one and decremented the other:
int y = 0;
int z = 10;
for(int i = 10; i >= 5; i--) {
System.out.print(z + " " + y + " ");
y++;
z--;
}
Output:
10 0 9 1 8 2 7 3 6 4 5 5
However we can also do this without extra variables:
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + 10-i + " ");
}
I don't think the OP actually wanted somebody to do their homework for them, so I'm gonna stick to answering the question they actually asked: how to alternate between two operations within a loop (so they can keep the algorithm they came up with :)).
There's a nifty "trick" that's very often used when we want to do something every other iteration in most programming languages. You'll most definitely come across it in your life, and it could be perplexing if you've got no clue what's going on, so here it goes!
The modulo (%) operator will yield the remainder of the division between its operands.
For instance, consider the following: 7 ÷ 2 = 3.5
When working for integers, you'd say that 7 ÷ 2 = 3, then you're left with 1.
In this case, when all variables are ints, in Java, 7 / 2 would be 3 and 7 % 2 is 1.
That's modulo for you!
What's interesting about this operator is inherent to what's interesting about division in general, and one case in particular: the remainder of a division by 2 is always either 0 or 1... and it alternates! That's the key word here.
Here comes the "trick" (not really a trick, it's basically a pattern considering how widely used it is) to alternating operations over iterations:
take any variable that is incremented every iteration in a loop
test for the remainder of the division of that variable by 2
if it's 0, do something, otherwise (it'll be 1), take the alternate path!
In your case, to answer your actual question (although others do have good points, I"m not trying to take that away from anybody), you could consider using something like that:
if( i % 2 == 0 ) {
// i is even, subtract
} else {
// i is odd, add
}
That'd allow you to keep going with the algorithm you initially thought of!
public class exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + (10-i) + " ");
}
}
}
Or you can do it this way, if you want to be a wiseass ;)
for(int i = 0, arr[] = {10,0,9,1,8,2,7,3,6,4,5,5}; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
This looks a bit like a homework assignment, so I won't give you working code.
But remember that you can put multiple print statements inside the for loop. You don't necessarily have to iterate 10 times to get your output. 5 times is totally enough. And as already stated in a comment above: the numbers alternate between i and 10-i, for the right range of i.
replace i >= 0 with i >= 5
add this : System.out.print((10-i--) + " ");
starting from what you did
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; ) {
System.out.print(i + " " + (10-i--) + " ");
}
}
}
Somethings don't need overthinking:
public class Answer2 {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++){
System.out.println(i);
System.out.println(10 - i);
}
}
}
edit
You CAN and should generalize your task. Here is an example how you could do it (I won't write the method, since it's your job - instead I'll alter my answer just to show you the possibilities)
public class Answer2 {
private static final Random RANDOM = new Random();
public static void main(String[] args) {
//You can use any upper bound for 'someLength'
int someLength = 1 + RANDOM.nextInt(20);
for (int i = 0; i <= someLength / 2; i++) {
System.out.println(someLength - i);
System.out.println(i);
}
}
}
Who said that you can only use one System.out.print in the loop?
for (int i=0; i < 5; i++) {
System.out.print((10 - i) + " " + (i + 1) + " ");
}
You should think about generalizing the series. As you have observed, the series alternates between addition and subtraction. Also, the difference goes down by one at each step. You can define variables for these two and adjust them in the loop.
public static void main(String[] args) {
int term = 10;
int sign = 1;
for(int delta = 10; delta >= -1; delta--) {
System.out.print(term + " ");
sign = -1 * sign;
term = term + sign * delta;
}
}
Simply run a loop either starting from 0 or starting from 10.
1.
If you start from 10
for(int i=10;i>=5;i--){
System.out.print(i + " " + (10-i) + " ");
}
2.
If you start from 0
for(int i=0;i<=5;i++){
System.out.print((10-i) + " " + i + " ");
}
The output will be:
10 0 9 1 8 2 7 3 6 4 5 5
I tried this code. It worked for me.
for(int i = 10; i >= 5; i--) {
System.out.print(i + " ");
System.out.print(10-i + " ");
}
This is here. The output list is a list of combinations to make 10;
10 0 9 1 8 2 7 3 6 4 5 5
10 + 0 = 10
9 + 1 = 10
8 + 2 = 10
7 + 3 = 10
6 + 4 = 10
5 + 5 = 10
int n = 10;
int half = n / 2;
if(n % 2 == 1){
half++;
}
for(int x = n; x >= half;x--){
int remainder = n % x;
if(remainder == 0){
remainder = n - x;
}
System.out.print(x);
System.out.print(" ");
System.out.println(remainder);
}
I'm writing a program where you input two divisors and a list of numbers you want to check are divisible by the two numbers you inputed.
Here's an example of how the output should look like:
Please input a command: A
A [Create a new divisible test]
[Type two divisors]: 2 6
[Input a list of numbers in one single line]: 2 4 6 9 15 18 19 25 30
Please input a command: D
D [Display the information]
( 2 4 6 9 15 18 19 25 30 ) are numbers to check
( 2 4 6 18 30 ): are divisible by 2
( 6 18 30 ): are divisible by 6
( 6 18 30 ): are divisible by both 2 and 6
My problem is it won't check which number is divisible by the two divisors, instead it prints out
( 2 4 6 9 15 18 19 25 30 ) are numbers to check
( 2 4 6 9 15 18 19 25 30 ): are divisible by 2
( 2 4 6 9 15 18 19 25 30 ): are divisible by 6
( 2 4 6 9 15 18 19 25 30 ): are divisible by both 2 and 6.
here's my code:
class Divisible {
private int divisor1;
private int divisor2;
public String numbers;
public Divisible() {
divisor1 = (Integer) null;
divisor2 = (Integer) null;
numbers = " ";
}
public Divisible(int div1, int div2, String num) {
this.divisor1 = div1;
this.divisor2 = div2;
this.numbers = num;
}
private boolean isDivisible1(int input) {
boolean isDivisible1 = true;
return (input % divisor1 == 0);
}
private boolean isDivisible2(int input) {
boolean isDivisible2 = true;
return (input % divisor2 == 0);
}
public String printDivisible1() {
if (this.isDivisible1(divisor1)) {
System.out.println();
System.out.println("are divisible by " + divisor1);
}
return numbers;
}
public String printDivisible2() {
if (this.isDivisible2(divisor2)) {
System.out.println(" are divisible by " + divisor2);
}
return numbers;
}
public String printDivisibleBoth() {
if (this.isDivisible1(divisor1) && this.isDivisible2(divisor2))
System.out.println(" are divisible by " + divisor1 + " and " + divisor2);
return numbers;
}
}
It looks to me like you're missing a few steps in your code!
To solve this problem we need to:
Break the string of numbers up, and convert them into integers, and enter them into a list or array.
Iterate over this list when printing, applying your isDivisible() function to determine if it should go to output.
First I think maybe we could make your program a bit more modular. In particular your isDivisible(int input) functions could be changed to something like:
private boolean isDivisible(int input, int divisor) {
return (input%divisor==0);
}
this means we can use the same function for both our divisors! Like isDivisble(30, 6) and isDivisble(30, 2)
Now we need to focus on your string of numbers to check. You'll notice our new function requires an integer for the input, but we currently have a huge string containing all our numbers. We could probably try a function like:
String[] numArray = num.split(" ");
to take our String 'num' and split it up into pieces wherever there is a space (" "), and put those pieces into the elements of the 'numArray' array.
Ok, now we have our array of inputs. All that's left is to convert these elements into Integers so they can be used as inputs to our isDivisible() function. We can use the Integer.valueOf(str s) function to do this!
And that's all the tools we need to finish this problem! Put together, a rough solution would look like:
String[] numArray = num.split(" ");
for (int i = 0; i < numArray.length; i++) {
if (isDivisible(Integer.valueOf(numArray[i]), div1)) {
System.out.print(numArray[i] + " ");
}
}
System.out.println("): are divisible by " + div1);
UPDATE
No arrays!? Ok, in that case I think your teacher wants you to iterate through the input, checking if they are divisible, and if they are, concatenating some output strings.
So let's start by adding a couple of Strings that will later become our output to the top of our code:
class Divisible {
private String outputDiv1 = "( ";
private String outputDiv2 = "( ";
private String outputBoth = "( ";
Now, for each of these outputs we want to concatenate only the divisible numbers. We can do this without arrays by looping through the characters of our String num, and breaking apart the numbers whenever we find spaces like:
//Since we're checking for spaces, we should probably add one to the end of our string, so we can find the last number!
num += " ";
//We need to keep a record of the previous space!
int lastSpace = -1;
for (int i = 0; i < num.length(); i++) {
if (num.charAt(i) == ' ') {
//If the current character is a space, we know everything before it and the last space was a number
//Our logic will go here!
//Currently converts our string into an Integer and prints it out
int currentNumber = Integer.parseInt(num.substring(lastSpace, i));
System.out.println(currentNumber);
//Update where the last space we found was
//The '+ 1' is so we skip the spaces!
lastSpace = i + 1;
}
}
Ok, no we are iterating through our string and breaking them apart without using any arrays! All that's left to do is apply the tool we made earlier isDivisible().
Something like:
if (isDivisible(currentNum, div1)) {
outputDiv1 += currentNum;
}
Can be put into //Our logic goes here section to determine whether a number should be added to our output list or not!
Finally, we print off our finished lists:
System.out.println(outputDiv1 + " ): are divisble by " + div1);
Hello i am having a tough time trying to write a function that can create an array that holds integers, that equal my simple math problem.
my problem is not adding integers into the array but finding the correct integers that could add up to a math problem.
for example i have a simple math problem like: 10 + 10 = ? we know it equals 20
so i want my array to hold up to ten integers, that when added all together equal 20.
this is what i have been trying in code but not getting the results i want.
while (totalCount != answer
&& count < setCount) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
i am trying to find random numbers that add up to the math problems answer so i can draw them on balloons. problem is i can never get ten numbers to equal the answer in my while loop.
does anyone know some way of doing something like this?
need array to hold 3 - 10 integers that equals my math problems answer.
** update on code thanks to the advice i received i managed to fix my while loop now it looks like this
had to post like this cause my rep is very low. sorry.
while (totalCount != answer) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(totalCount + randomNumber > answer) {
randomNumber = rand.nextInt((int) answer - totalCount) + 1;
}
if(count + 1 == setCount) {
randomNumber = answer - totalCount;
}
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer
|| totalCount == answer
&& count < setCount
|| totalCount != answer
&& count == setCount) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
this is what i got in my console from this code
Total count = 10
Total totalCount = 20
sumOfBalloons 0 = 2
sumOfBalloons 1 = 3
sumOfBalloons 2 = 3
sumOfBalloons 3 = 2
sumOfBalloons 4 = 1
sumOfBalloons 5 = 4
sumOfBalloons 6 = 2
sumOfBalloons 7 = 1
sumOfBalloons 8 = 1
sumOfBalloons 9 = 1
I think there are a few options here re: generating random numbers that sum to 20.
Here's one possible solution:
Create an array of length 4, for example.
Generate random number between 1 and 6 for each of the first 3 indices of your array.
At this point you'll have an array of the form: { 4, 5, 2, _ } (where our 4th element hasn't been chosen yet).
Sum our first 3 elements: 4 + 5 + 2 = 11. Determine 4th element by calculating 20 - current_total (11) = 9.
Set myArray[3] = 9;
A few things to note:
You may need to modify the range of possible random numbers ( 1-6 ) I've given. Consider what happens if the array we generate turns out to be { 2, 1, 2, _ }...then there's no digit that will ensure the elements sum to 20.
Another option is to use an arrayList instead of an array. The benefit to this is that you can keep adding elements to your arrayList until you either hit 20 (then you're done) or go over (in which case you delete the most recent element and begin adding again). You also won't need (or be able) to know the length of your arrayList in advance.