Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
If I am not mistaken, this bit of code should print out all even numbers smaller than or equal to 100. When I run this code, nothing happens. No error message or anything. I'm using Eclipse.
public class Even {
public static void main(String args[]) {
int number = 1;
int remainder = number % 2;
while(number <= 100) {
number++;
if(remainder == 0) {
System.out.println(number);
}
}
}
}
As others stated before, value of remainder is set only once. However, you check it a hundred times expecting it to tell you something else every time. I'd suggest putting it inside a loop, so you get a "fresh" value for every number.
public class Even {
public static void main(String args[]) {
int number = 1;
int remainder;
while(number <= 100) {
number++;
remainder = number % 2;
if(remainder == 0) {
System.out.println(number);
}
}
}
}
The reminder doesn't change as the assignment is prior to while loop. The statement int remainder = number % 2; has to be inside while loop to see the expected result.
for(int i = 0;i<=100; i= i+2)
System.out.println(i);
You do not need remainder :)
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 days ago.
Improve this question
I saw a program like this in a book:
Here is a program: print out integers. Here you have a positive integer n and want to print it out. The name of the program is printOut(n). Suppose there is an existing routine that will only process a single number and output it to the terminal .The routine that prints a single digit is named printDigit.
The program requires the use of recursion.
The sample code given in the book is:
public static void printOut(int n)
{
if (n >= 10)
{
printOut(n / 10);
}
else
{
printDigit(n % 10);
}
}
The code of the routine printDigit is not given in the book. After thinking, I think the program should be like this:
public class PrintOutTest
{
public static void main(String[] args)
{
Print.printOut(76234);
}
}
class Print
{
public static void printOut(int n)
{
if (n >= 10)
{
printOut(n / 10);
}
else
{
printDigit(n % 10);
}
}
static void printDigit(int n)
{
System.out.print(n); //7
}
}
But when I run it, the terminal only outputs the number 7.
I took a closer look and found that the printDigit method only entered once, which should be the problem. But I don’t know how to modify it. Please ask if you can help me. Thanks
You need to emit the digits from left to right (most significant to least significant).
It is easier to get the rightmost digit (this is n % 10) than the leftmost one (this is n divided by... some power of 10). So the recursion will take this shape:
To print out a number:
if longer than one digit
recurse on the number without its rightmost digit
print out the rightmost digit
and more precisely,
To print_number n:
if n > 9
print_number n / 10
print_digit n % 10
PrintDigit is only called when n is less than 10, so that happens only once...
You need to also call PrintDigit when you make the recursive call. So:
public static void printOut(int n)
{
if (n >= 10)
{
printOut(n / 10);
}
printDigit(n % 10);
}
In each iteration, the number goes diving by 10
for your example 76234 > 7623 > 762 > 76 > 7 and now 7 is smaller than 10 so the recursive function called the print method and 7 gets printed.
below is an example to fix the problem.
class Print
{
public static void printOut(int n)
{
if (n == 0) return ;
printOut(n / 10);
printDigit(n % 10);
}
static void printDigit(int n)
{
System.out.print(n); //7
}
}
Your printDigit function is OK. Just dont wrap it with else block:
public static void printOut(int n)
{
if (n >= 10)
{
printOut(n / 10);
}
printDigit(n % 10);
}
And also, I personally don't prefer to learn any programmin language from books cause they gets outdated and writers often suck at algorythms. And once they make a mistake there is no chance to republish a book but in Github there is issues, pull requests, comments, and code is editable also forkable.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
//Name of Program: HippityHop.java
//Entered by: No Name
//Date: 10/19/2020
import java.util.Scanner; // Needed for the Scanner class
public class HippityHop
{
public static void main(String[] args)
{
// get scanner to read input
Scanner keyboard = new Scanner(System.in);
for(int x=1; x <= 100; x++){
if(x % 3 && x % 4) {
System.out.println(x);
}else{
if(x % 3 == 0){
System.out.println("Hippity");
}
if(x % 4 == 0){
System.out.println("Hop");
}
}
}
}
}
I am trying to create a program that on multiples of 3 it prints "Hippity" and on multiples of 4 it prints "hop". I seem to be getting a bad operand error. What can I do to fix it?
The following expression:
if(x % 3 && x % 4) {
Isn't a proper one. What x%3 is doing is calculating the modulus. You never compared it to anything, so it's throwing a bad operand error. That's like saying in real life:
if x modulus 3 then do this
Or, just for the sake of the argument (and to make it easier to understand), it's like saying:
if x subtract 3 then do this
Instead, it should be if(x%3!=0 && x%4!=0), like so:
import java.util.Scanner; // Needed for the Scanner class
public class HippityHop
{
public static void main(String[] args)
{
// get scanner to read input
Scanner keyboard = new Scanner(System.in);
for(int x=1; x <= 100; x++){
if(x % 3 !=0 && x % 4 !=0) {
System.out.println(x);
}else{
if(x % 3 == 0){
System.out.println("Hippity");
}
if(x % 4 == 0){
System.out.println("Hop");
}
}
}
} }
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am fairly new to Java and I ran into this problem once or twice in one of my books. This is a super simple program and I just don't understand why it's not working. I know when you use return, anything after it in the method is meaningless. So does this mean after you perform an for statement or an if statement that is a return?
I am using Java 8 on Windows 8 in the latest version of Eclipse.
This is my simple program:
// Find the sum of 1 through 50 and the average.
class SumAndAverage
{
public static void main(String args[])
{
int sum = 0;
double average = 0;
for(int i = 1; 1 <= 50; i++)
{
sum += i;
}
// the following code is "unreachable"
average = sum / 100;
System.out.println("The sum is: " + sum);
System.out.println("The average is " + average);
}
}
1 is always less than or equal to 50, isn't it? You probably meant to compare i with 50:
for(int i = 1; i <= 50; i++)
{
sum += i;
}
for(int i = 1; 1 <= 50; i++)
1 is always less than or equal to 50.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
The user must enter x, y, and the limit. The program must find the multiples of these numbers that are below the limit that the user set themselves. The program adds up all the multiples and prints just that number at the end, and not all the multiples. For some reason it just isn't working for me and I can't figure it out.
import java.util.Scanner;
public class SumMultiples.java {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter x value: ");
int x = scanner.nextInt();
System.out.print("Enter y value: ");
int y = scanner.nextInt();
System.out.print("Enter limit value: ");
int limit = scanner.nextInt()
int sum = 0;
for (int i = 0; i < limit; i++) {
if (((i % x) == 0 || ((i % y) == 0))) {
sum += i;
}
}
}
System.out.println(sum);
}
From copying your code into Eclipse:
Firstly you are missing a ; when you are getting the input for limit.
Secondly your System.out.println(sum); is outside of your main method, it should be at the end of the method i.e. after your for loop.
Thirdly, you have named your class SumMultiples.java. This is not a valid name, rename it to SumMultiples.
You should be getting compile errors and your IDE should help you work this out. If you aren't using an IDE, please do so as it will help you debug these issues and help you get familiar with Java.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am working on Project Euler Problem 12. Could anyone provide any tips on how to improve my code so it executes in my life time?
public class HighlyDivisibleTriangularNumber {
public static void main(String[] args) {
int divisors = 0;
int count = 1;
while(divisors <= 501) {
long triNum = triangularNumber(count);
divisors = getFactors(triNum);
System.out.println(triNum+"_"+divisors);
count++;
}
}
private static int getFactors(long triNum) {
int divisors = 0;
while(triNum > 1) {
triNum = triNum / 2;
divisors++;
}
return divisors;
}
private static long triangularNumber(int i) {
long total = 0;
for(int k = 1; k <= i; k++) {
total += k;
}
return total;
}
}
1) triangular numbers
The first (and probably most important) optimization you can do is in how you compute the triangular numbers.
You can observe that the nth triangular number (let's call it t(n) ) is equal to n + t(n-1).
So each time you compute a triangular number, you can just take the triangular number before it and add n. This would lead to the naive recursive function :
private static long triangularNumber(int i) {
if(i == 1) return 1;
else return i+triangularNumber(i-1);
}
But this won't improve the performance much... to resolve this, I suggest you do some research on memoization and adapt the function I gave you (I won't give you the answer, this is an excellent exercise)
Now, on a regular computer you should have the answer to the problem in a reasonable time. But it can be improved a little better
2) counting divisors
Your function for counting divisors is wrong. What you should do is try to divide your number by successive natural numbers and see if the result is an natural integer.
private static int getFactors(long triNum) {
int divisors = 0;
for(int i = 1; i <= triNum; ++i) {
if(triNum%i == 0) // triNum is a multiple of 1 <=> i is a divisor of triNum
divisors++;
}
return divisors;
}
You can even improve this by counting only to the square root of trinum and adding two divisors each time. But there's a trick if you do this, I'll let you figure it out if you decide to try this.
Why do do recompute the triNum each time? Just add the difference each time (basically your count).
public static void main(String[] args) {
int divisors = 0;
int count = 1;
long truNum = 0;
while(divisors <= 501) {
triNum += count;
divisors = getFactors(triNum);
System.out.println(triNum+"_"+divisors);
count++;
}
}
Furthermore, your approach to count the factors is completely off. You are just searching for the first power of two to be greater than the given number. Read up on (prime)-factorization. Note that you need to account for the combinations of (prime) factors, too.
Example: 12
12 = 2 * 2 * 3
But the divisors of 12 are
1, 2, 3, 4 (= 2*2), 6 (= 2*3), 12
So in total there are 6 divisors of 12 and not 3 as the mere prime factorization may lead you to believe.