I'm running a super basic program for my class on Java with eclipse, the point of it to write a for loop that prints odd number from 1 to 99 (inclusive) and I'm writing my code
int num1 = 1;
int num2 = 99;
for (num1 => num2 ;; num1 + 2)
System.out.println(num1);
and it's telling me that + and >= are invalid AssignmentOperators. Why is it doing this?
You have several problems there. The first is you should write <= rather than =>. The second is you put the loop condition in the wrong place (it should be between the two semicolons). And lastly you're not assigning new values to num1 (so it never increases).
In addition, you don't need num2 (although it's not a mistake to use it, it makes it a bit less clear).
The final code should look like this:
int num1 = 1;
for (num1 = 1; num1 <= 99; num1 += 2)
System.out.println(num1);
Plus, I'm pretty sure you're coding in Java and not JavaScript (they're two different things).
Firstly there is no necessity of defining data type in Javascript.
That being said you do not need int num1 or num2.
This answer is valid if you are using Javascript not JAVA
Instead can be done this way
for (i = 1; i < 99 ; i++){
if(i%2 !== 0){
console.log(i);
}else{}
}
Related
I have a very simple java class to solve Decode ways using recursive approach. I am seeing this weird behavior of conditional operator,
package decodeways;
public class Solution {
public static void main(String[] args) {
System.out.println(numDecodings("1456"));
}
public static int numDecodings(String s) {
if(s.length()>0 && s.charAt(0)=='0')
return 0;
if(s.length()==0) return 1;
if(s.length()==1)
return 1;
int num1 = s.charAt(0)-'0';
int num2 = s.charAt(1)-'0';
int one = numDecodings(s.substring(1));
int two = s.length()>1?numDecodings(s.substring(2)):0;
int res = one
+ num1<3 && num2<7 ? two:0;
return res;
}
}
if I put a parentheses, (num1<3 && num2<7 ? two:0) then everything is well and good but if I remove the parentheses, then getting incorrect results.
during the process of debugging, one will be computed to 1 and two will be computed to 1 and res will be 1 as well with parentheses but without it, the computed result of res will be 0 (screnshot attached) which is the source of error.
I am aware of the operator precedence in java, but in this situation I can't figure out why it shows incorrect behavior, because in the below code:
int res = one
+ num1<3 && num2<7 ? two:0;
one + num1<3 is illegal
So, java is intelligent enough to not confuse between (one + num1<3) and (num2<7 ? two:0) to be consider separately.
So, as per my understanding the only legal observable behavior for java compiler is to automatically consider num1<3 && num2<7 ? two:0 as an atomic operation(Please correct me if I am wrong), irrespective of parentheses is available or not.
Please guide me to have a better understanding.
Thanks.
int res = one
+ num1<3 && num2<7 ? two:0;
is equivalent to
int res = (((one + num1) < 3) && (num2 < 7)) ? two : 0;
Everything before ? is included in the boolean expression, since the ternary/conditional operator has the lowest precedence here (not including the assignment operator) and + has the highest.
The order goes something like:
+, so one + num1 is put together first
<, so now there's (one + num1) < 3 and num2 < 7
&&, after which you have ((one + num1) < 3) && (num2 < 7)
and finally ?:
You seem to be expecting the newline to make the compiler think one and num1<3 && num2<7 ? two:0 are separate, but it actually just ignores all whitespace. Putting the parentheses there is the only way to make sure one is added to the whatever the conditional operator evaluates to.
int res = one + (num1 < 3 && num2 < 7 ? two : 0);
My assignment asks for a command-line input to be put through nested while loops to find if a number is a happy number or not. So far I have this:
int i = 0;
int sum = 0;
int dig2, dig1, dig3, dig4, dig1next, dig2next, dig3next;
int digit1sum, digit2sum, digit3sum;
happyNumber = number;
while (i < 500){
while (happyNumber > 0){
while (sum!=1){
dig3 = happyNumber / 100;
dig2 = happyNumber % 10;
dig1 = happyNumber / 10;
dig2next = dig2 % 10;
dig1next = dig1 % 10;
dig3next = dig3 % 10;
digit1sum = dig1next * dig1next;
digit2sum = dig2next * dig2next;
digit3sum = dig3next * dig3next;
sum = digit1sum + digit2sum + digit3sum;
happyNumber = sum;
}
System.out.println("It is a happy number.");
System.exit(0);
}
i++;
System.out.println(i);
System.exit(0);
}
I set i<500 so when i++ reaches 500, the loop should stop. I've pretty much tried putting i++ in every section of the code possible, it never works. what am i doing wrong here?
also: i am not allowed to use for loops or do-while loops on this assignment. i have to use nested while loops only
Happy number: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1(how long the loop will be: 500).
After a quick glance at your code:
while (sum!=1)
....
sum = digit1sum + digit2sum + digit3sum;
happyNumber = sum;
This while test is likely to be always true -> infinite loop -> stack overflow
You will never get out of your innermost while-loop in case of a number that loops endlessly (it is by no means stopped by the 500- limit and your logic is wrong here).
Secondly, something to think about:
digit1sum = dig1next*dig1next;
digit2sum = dig2next*dig2next;
digit3sum = dig3next*dig3next;
these (digitxsum) will always be positive.
sum = digit1sum + digit2sum + digit3sum;
sum will therefore always be positive
happyNumber = sum;
happynumber will always be positive
while (happyNumber > 0)
what is this for?
I'm trying to make a program that finds the largest palindrome that is a product of two 3-digit numbers. This is what I have right now (I am new to programming):
int num1 = 0;
int num2 = 0;
int product = 0;
int tempProd1 = 0;
int tempProd2 = 0;
int tempProd3 = 0;
int tempProd4 = 0;
int tempProd5 = 0;
int tempProd6 = 0;
String prodCheck1 = "";
String prodCheck2 = "";
while (num1 < 1000){
while (num2 < 1000){
product = num1 * num2;
prodCheck1 = Integer.toString(product);
tempProd1 = product % 10;
product = product / 10;
tempProd2 = product % 10;
product = product / 10;
tempProd3 = product % 10;
product = product / 10;
tempProd4 = product % 10;
product = product / 10;
tempProd5 = product % 10;
product = product / 10;
tempProd6 = product % 10;
product = product / 10;
prodCheck2 = "tempProd1" + "tempProd2" + "tempProd3" + "tempProd4" + "tempProd5" + "tempProd6";
if (prodCheck1 == prodCheck2){
System.out.println(prodCheck1);
}
num2++;
}
num1++;
}
Thing is, every time I try to run it, it terminates without an error. Could someone explain what I'm doing wrong?
Edit: Thanks everyone, finally fixed it. The answer is 853358, if anyone was wondering.
Edit: Actually, the number was 906609.
One thing I noticed immediately is that after the first iteration of the inner loop, num2 is 1000 and so the inner loop will just do nothing in the remaining 999 iterations of the outer loop. You have to reset num2 to 0.
Also consider using "for" loops instead; they're designed to prevent this kind of mistake:
for (int num1=0; num1<1000; num1++) {
...
}
Another problem is that the palindrome check is wrong. You cannot compare Strings with == (it tests for object identity, not string equality -- you'd have to use equals() instead). But even that is wrong because prodCheck2 is "tempProd1tempProd2..." and doesn't contain the actual numbers. The easiest way to check for a palindrome would be:
if (tempProd1 == tempProd6 && tempProd2 == tempProd5 && tempProd3 == tempProd$) {
...
}
Equals method for strings
There are several issues here. First == should not be used to compare strings. You should use string.equals(otherString);
Contatinating words
Second you appear to be combining words when you want to combine values
prodCheck2 = "tempProd1" + "tempProd2" + "tempProd3" + "tempProd4" + "tempProd5" + "tempProd6;
will give
prodCheck2 = "tempProd1tempProd2tempProd3tempProd4tempProd5tempProd6";
always. The fact that those words happen to have the same name as some of your variables makes no difference to java.
There are many better ways to concatenate integers. But the easiest is probably as follows
prodCheck2 = tempProd1 + "" + tempProd2 + "" +tempProd3 + "" +tempProd4 + "" +tempProd5 + "" +tempProd6";
Using while when for would be better
while (num1 < 1000){
while (num2 < 1000){
......
num2++;
}
num1++;
}
This code never decreases num2, which means num2 goes 1->1000 for num1=0 and then stays at 1000 from then on. I'm guessing this isn't what you want. We could fix the while loop but really this is what a for loop is for
for(int num1=0;num1<1000;num1++){
for(int num2=0;num2<1000;num2++){
//code as before, no need to inciment or reset num1 or num2 inside the loop
}
}
Issues that don't break your code
You're declaring all your variables with very large scope. For example tempProd1 is declared outside all the loops depite only being needed inside the inner loop. Declare variables in the smallest scope possible. This will catch bugs like those we've found here. Critically num2 couldn't have accidently been made non resetting if you'd delared it within the first loop
if (prodCheck1 == prodCheck2){
System.out.println(prodCheck1);
}
is a comparison that is based solely on the identity equality of prodCheck1 and prodCheck2. Rewrite that code as:
if (prodCheck1.equals()){
System.out.println(prodCheck1);
}
to use value equality that will return true for identical strings.
I ran into a little problem here. Basically my program below is just generating two random numbers and divide both of them.
Before that I insert a statement whereby if num1 is not divisible by num2, then num2 has to generate a number between 1 to "num1" until it is divisible.
But in the end it keeps giving me a number which is not divisible (or basically giving decimal points). I tried looking for an example in the Internet and understood so well with the modulus operator. Where did I go wrong here? I just want both numbers to be divisible that's all.
Below is my code:
int num1, num2, real_ans;
Random randomGenerator = new Random();
num1 = randomGenerator.nextInt(100) + 1;
num2 = randomGenerator.nextInt(100) + 1;
if (num1%num2!=0) {
do {
num2 = randomGenerator.nextInt(num1) + 1
} while(num1%num2==0);
}
real_ans = num1 / num2;
Change the do/while loop to:
do{
num2 = randomGenerator.nextInt(num1) + 1
} while(num1 % num2 != 0);
(note the !=).
This loops until the numbers divide exactly.
you are iterating with the condition that if num1 is divisible by num2, keep iterating. Change the condition to do{...}while (num1%num2 != 0);.
You should be able to find a number that can divide num1 with that code. The only case it still won't work is when num1 is prime, so I suggest you check if num1 is prime and only generate num2, when num1 is not prime.
I'm working on a small Java program, and somewhere, my calculations are going awry. My code is as follows:
import java.io.*;
import java.util.*;
import java.text.*;
public class NumManip
{
public static void main(String args[])
{
Scanner numGetter = new Scanner(System.in);
final int MULT_1 = 9;
final int MULT_2 = 12345679;
final int MULT_3 = 1000;
int poorHatedNumber;
System.out.print("Enter a digit between 1 and 9 that you dislike: ");
poorHatedNumber = numGetter.nextInt();
int num1 = poorHatedNumber * MULT_1, num2 = num1 * MULT_2;
long num3 = num2 * MULT_3;
System.out.println();
System.out.println(" " + poorHatedNumber);
System.out.println(" " + "x" + MULT_1);
System.out.println(" __");
System.out.println(" " + num1);
System.out.println(" x" + MULT_2);
System.out.println(" __");
System.out.println(" " + num2);
System.out.println(" x" + MULT_3);
System.out.println("____________");
System.out.println(num3);
}
}
I've tryed printing num1, num2, and num3 on the screen to see what the problem is, and num1 is right, num2 is right, and num3 is freaky. My input is 9, and the first calculation multiplies by 9 and gets 81. Then it multiplies that by 12345679 and gets 999999999, and then it multiplies by 1000 and gets -727380968. What's wrong with that last step? I'm REALLY new to Java, and I don't get the issue.
999999999 * 12345679 = 1.234567898765432e+16 which is way bigger than the maximum value of an int which is 2,147,483,647
Since Java uses 2-compliment method to store int number (meaning that the leftmost bit is turned on when the number is negative) this calculation "overflows" (carry-over) to the that bit which results in a negative result.
For calculation with such big numbers you should use BigDecimal
As num2 and num1 both are integer, so integer multiplication happened and it exceeds the max of integer value.
long num3 = (long)num2 * MULT_3;
I think you're resulting in a number bigger than the datatype can handle, and as the datatype is signed, it wraps around into the negatives.
Don't worry, it's not such a silly mistake really. The whole "numbers are usually a fixed size"-deal confuses just about everyone initially. Now that you know what's up, here's something even weirder. It's not really an answer to your question, but now that you've just seen an example of "bad overflow", you might find this interesting.
Consider an odd number x. There is a number y such that x * y == 1. That number y is called the modular multiplicative inverse, and it can easily be computed (see Hacker's Delight, exact division by a constant). This may seem really counter intuitive, because it essentially allows a weird kind "division" that only works if the number was an exact multiple of the divisor, and in general it allows you to "undo" a multiplication by an odd number. For example, if you have a = 3 * b, then b = -1431655765 * a - regardless of any overflow in either multiplication, so overflow need not be "destructive".