I have a program that takes in 3 numbers (feet, inches, sixteenths) then multiplies them by x. Upon starting to write the output part, I ran into needing:
if (sixteenths4<16) {
sixteenths5=sixteenths4;
inches6=0;
}else if (16<=sixteenths4) {
sixteenths5=sixteenths4-16;
inches6=1;
}else if (32<=sixteenths4) {
sixteenths5=sixteenths4-32;
inches6=2;
}else if (48<=sixteenths4) {
sixteenths5=sixteenths4-48;
inches6=3;
} else {
sixteenths5=sixteenths4-64;
inches6=4;
}
I realize the last else is redundant as it will never happen. My issue is that since the total sixteenths could exceed 4-5 hundred, that would be a lot of if else blocks. Is there a better way to do this?
Remive all the if/else statements and use integer arithmetic instead.
This is equivalent code for all your code:
sixteenths5 = sixteenths4 % 16;
inches6 = sixteenths4 / 16;
Related
I tried this a lot, and debugged it a few times, everything seems to be working and largest prime does indeed become the largest prime even if it takes rather long.
I can't get the printed value from System.out.println. I could find it through the debugger but the value is too high to find fast just holding down step over.
It compiles as well so I am stumped about what's the issue here. I would be very happy to know what I did wrong.
Edit: The reason why I wrote this code in the first place is because in the site project euler it asked for the largest prime value that when divided with the value of primer gave a whole number.
Is there a way at least that would allow me to make it faster with the same value? this seems rather impractical.
package unit5;
public class Primefinder { public static void main(String[] args)
{
double primer = 600851475143d;
double largestprime = 0;
Boolean ifprime = false;
for(double x = 2d; x < primer; x++)
{
for(double z = 2d; z<x; z++)
{
if( (x%z == 0) && (z != x) )
{
ifprime = false;
break;
}
else {
ifprime = true;
}
}
if((ifprime != false) && (x > largestprime))
{
largestprime = x;
}
ifprime = false;
}
System.out.print(largestprime);
}
}
for other questions you might ask everywhere, please tell us that what is the purpose of your code. this way it is easier to get the fault.
the code you have written above runs completely but the numbers you have used are too big so you need to wait a lot, so that compiler be able to reach to this line:
System.out.print(largestprime);
use lower numbers (at least for test) or wait properly.
Your 'primer' Value is very big.
So, loop is taking very much time to reach at '600851475143' value.
Wait Sometime and it with show largest prime number
I'm not quite sure what I'm having trouble with here and I'm hoping someone can help me. This is my first post on Stack Overflow, and I'm relatively new to programming, so I hope I don't offend anyone's sensibilities around here.
Here's the prompt (yes, it's a Project Euler question and please don't give the answer away): What is the lowest number which is divisible by every number between 1 and 20?
Here's what I coded:
int target = 21;
int divisor;
boolean success = false;
while (!success)
{
for (divisor = 1; divisor < 21; divisor++)
{
if (target % divisor != 0)
{
break;
}
else
{
if (divisor == 20)
{
success = true;
}
}
target++;
}
}
System.out.println(target);
The answer I'm getting (232792581) is being flagged as incorrect by P.E. Can anyone tell me what I'm getting wrong here?
Thanks everyone!!
Your problem is that you have target++ in the wrong place. The way your code is now, this is being called inside the for loop where you test the numbers - i.e. you change the target while checking things against it. Move the target++ statement so that it is out of the for loop but still in the while loop.
Is there ever a situation where you must use a do while loop? Is it an accepted practice? It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
int i = 3;
while ( i > 0 ) { // runs 3 times
i--;
}
vs
int j = 3;
do {
j --;
} while ( j > 0 ); // runs 3 times
The same?
EDIT: I have seen the java doc, but
the example in the java docs doesn't look like it requires that the particular routine inside of the do while loop must be run in the do while loop instead of inside of a regular while loop!
Is there ever a situation where you must use a do while loop?
No: every do-while loop can be written as a while-loop by running the body once before the loop begins. However, there are certainly cases where it makes more sense to use the do-while construct (i.e. if you always want the loop to iterate at least once), which is why it exists in the first place.
Is it an accepted practice?
If you use it appropriately, then yes absolutely.
It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
That's right. You can read more about do-while in its tutorial.
This example maybe help you be clearer:
int i = 3;
System.out.print("while: ");
while (--i > 0){
System.out.print("x");
}
System.out.print("\ndo-while: ");
int j = 3;
do
{
System.out.print("x");
}while (--j > 0);
This prints
while: xx
do-while: xxx
A real time example.
There is a contest with 5 level.
In each level if you score 100 you can proceed to next level.
Less code for do while, but not for while.
boolean playContest()
{//do while
int level = 1;
int score;
do
{
score = 0;
score = play();
}while(score>99 && level++<6)
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
boolean playContest()
{//while
int level = 1;
int score;
while(level <6)
{
score = 0;
score = play();
if(score < 100)
break;
level++;
}
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
basic difference between while and do-while is do while will be executed at least once.
when do-while is best option?
in case when you want to execute some actions till you meet condition, of course you could achieve same thing by using while but early termination of loop with break, is nasty and ugly solution
When you want to execute the statement inside do for at least once, then you can go for it.
Directly from Docs
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once,
do {
statement(s)
} while (expression);
No, there is no time a do-while loops is the only option, it is used for convenience when you do not want to repeat code.
I'm doing my homework, and am stuck on some logic (I think I used that term correctly?). I'm writing an application that shows 12 buttons numbered 1-12, 2 pictures of dice, and a Roll button.
The player rolls the dice (2, 6 sided die) and whatever number(s) he gets, he can use to "cover" some of the twelve numbers. For example, let's say he rolls the dice and gets a 3 and a 5. He gets to choose whether to cover the 3 and the 5, or the total of the two numbers - 8 (Did I mention I'm a math wiz?).
The goal of the game is to cover all the numbers using the least amount of rolls.
The problem I'm having is with, what I believe to be, the if statements:
if (die1 == 3 && die2 == 5) {
player can cover 3 and 5, or 8, but not both
}
Now, I think this works, but if I wrote all this out it would be 36 if statements (give or take zero). Is there an easier way?
By your description I think the player can select die1, die2 or die1 + die2, so to see if the user selected a valid value you need just one if.
if (cover == die1 or cover == die2 or cover == ( die1 + die2)) {
//valid..
}
no if statement needed. player can cover die1 and die2 or die1+die2
This is a good example to use a switch case, IMO.
That'd be 2 switchs which have 6 cases each.
Don't check until the player tries to cover something. By only validating the input you simplify everything down to one if statement.
If you do need to know all possibilities (maybe to show the player possible moves), then ... you still don't need all those if statements. Simply highlight the buttons that match the dice roll and only accept those as input; you'll want to index them in an array or map by their value (e.g. "1") as a way to retrieve them.
You know with two dice you always have three covering options. Presumably elsewhere in code you're going to compare your covered options with numbers. Something like
int[] covered = { die1, die2, die1+die2 };
// ... other stuff
if (comparisonValue > 6) {
// maybe do special stuff since this uses both dice
if (comparisonValue == covered[2]) {
// covered/coverable behavior
} else {
// not
}
} else {
// maybe do special stuff since this only uses one die
if (comparisonValue == covered[0] || comparisonValue == covered[1]) {
// covered/coverable behavior
} else {
// not
}
}
gives you first what's covered, then simple use of it. You could also foreach over the array to do stuff for the covered numbers, ala
for (int c : covered) {
// do stuff with c because it's covered
}
That's fairly fragile, but the flexible answer (e.g., dumping the outcomes into Collection) is way overkill for 6-sided, integer face dice, and the really flexible answer (e.g., accommodating a variable number of dice, specialized combination of faces into outcomes) is like nuclear armageddon for this particular problem.
EDIT for your particular problem, I'd do something like
// start new turn, disable all buttons
// get rolls
int[] coverable = { die1, die2, die1+die2 };
for (int covered : coverable ) {
// enabled covered button
}
If the player can change which of the 1-12 are covered by previous rolls based on a new outcome, well, then you could be in for some fun depending on how much help you want to give them.
I would probably create 2 new objects and use them with a lookup table, like so:
class TossResult{
int firstDie;
int secondDie;
}
Class Coverage{
TossResult tossResult;
int getThirdNumber(){
return tossResult.firstDie + tossResult.secondDie;
}
}
Then on application start-up, populate your map:
HashMap<TossResult, Coverage> lookup = new HashMap<>();
for (int i = 0, i < SIDES_ON_DIE; i++){
for (int j = 0, j < SIDES_ON_DIE; j++){
TossResult tempResult = new TossResult(i,j);
Coverage tempCoverage = new Coverage(tempResult);
lookup.put(tempResult, tempCoverage);
}
}
After a user rolls the dice, create a new TossResult and do a lookup.get(tossResult)
You could also create an array of 12 ints or bools. Initialize all 12 elements (say to 0 or false). Then for each role you can do something lik:
if (false == myArray[die1Value] && false == myArray[die2Value]) {
myArray[die1Value] = true;
myArray[die2Value] = true;
} else if (false == myArray[die1Value + die2Value]) {
myArray[die1Value + die2Value]
} else if (false == myArray[die1Value] || false == myArray[die2Value]) {
if (false == myArray[die1Value]) {
myArray[die1Value] = true;
}
if (false == myArray[die2Value]) {
myArray[die2Value] = true;
}
} else {
// all 12 covered
}
And certainly you can refactor this code some more.
The stated goal "The goal of the game is to cover all the numbers using the least amount of rolls." is not doable, really. The best you can do is to use probabilities to know if, for instance, you should cover on a roll of 1 and 2, a 1 and 2, or 3 first:-)
I made a swing calculator as part of homework that I did and would like some advice on continues subtraction in particular.
With continues adding up it is straight forward enough(i.o.w. adding the operands and then to continue adding from there onwards). This is what I did.
if(totalCount > 1)
{
if(sbOne.length() > 0)
{
operandOne = Double.parseDouble(sbOne.toString());
}
else
{
operandOne = 0;
}
if(sbTwo.length() > 0)
{
operandTwo = Double.parseDouble(sbTwo.toString());
}
else
{
operandTwo = 0;
}
result = operandOne + operandTwo;
totalResult += result;
screenResult = Double.toString(totalResult);
txtDisplay.setText(screenResult);
notCalculate = true;
sbOne.setLength(0);
sbTwo.setLength(0);
How can I achieve the same result by subtracting one operand from another and then to continue subtracting from there onwards.
Your code seems confusing, particularly as it is incomplete and not compilable. My interpretation of your code is as follows: you have two presumably positive values which you add together, whereupon you add that sum to a total which you already have. My interpretation of your question is as follows: you want to subtract that sum from the total. A solution to that is as Hot Licks said, which is just to use the following operation: totalResult -= result;. If you want to make it possible to decide whether or not you want to add or subtract, add a Boolean flag, namely:
/*somewhere in your code to determine whether you add or subtract,
have a button or something which changes this value.
*/
boolean isAdding = true;
//...
//button pressed
isAdding = false;
//...
//your calculating code goes here
if(isAdding)
totalResult += result;
else
totalResult -= result;
//all of the other stuff