I'm stuck on a program from mooc.fi course; wherein I can't get my program to print results.
The program should 'print all the numbers divisible by three in the given range. The numbers are to be printed in order from the smallest to the greatest.'
Thanks for the help.
public class DivisibleByThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
divisibleByThreeInRange(a, b);
}
public static void divisibleByThreeInRange(int beginning, int end) {
for (int i = 0; i >= beginning && i <= end; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
}
}
Welcome to stack overflow, Entropy!
The problem is this line:
for (int i = 0; i >= beginning && i <= end; i++) { ... }
Let's break up that for loop:
for says its a loop, with the first statement initializing the loop, the second giving the condition for executing the next iteration, and the third saying how to update after an interation. Inside the quotes is what to execute in an interation.
Loop initializing: int i = 0 defines the loop variable i and sets it to 0.
Loop condition: i >= beginning && i <= end. So we will execute the next iteration if i lies in the entered range.
Loop post update: i++ just increments the counter.
So effectively, you start with i being 0, and then execute the loop WHILE that number is within the entered range. But if i BEGINS outside your range, the loop is never executed, because the condition is false at the very beginning.
You can confirm that by entering making the range contain 0, i.e. enter a non-positive lower and a non-negative upper range (like -10 to 10). Then, the initial condition is fulfilled and your loop happily shows all the number divisable by 3.
So simply change the loop to
for (int i = beginning; i <= end; i++) { ... }
and it will work as intended: Start at the beginning of the range, and go the end of it -- done!
These for-loops can be tricky sometimes, don't they? :)
That's a great first post, by the way. Having a Minimal Reproducible Example (MRE, also called reprex or MCVE [Minimal, Complete, Verifiable Example]) always help others to quickly verify, debug and solve your problem.
public class DivisibleByThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
divisibleByThreeInRange(a, b);
}
public static void divisibleByThreeInRange(int beginning, int end) {
for (int i = beginning ; i <= end; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
}
}
Related
I just started with java and while was doing an exercise about permutations (the exercise asked to create a permutation of N elements using an array a[] meeting the requirement that no a[i] is equal to i.) I've created the following code. While testing it, I realized that it entered in a infinite loop sometimes when N = 6 specifically.
Any thoughts on where is the problem?
public class GoodPerm {
public static void main(String arg[]) {
int n = Integer.parseInt(arg[0]);
int[] guests = new int[n];
for (int i = 0; i < n; i++) {
guests[i] = i;
}
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int q = guests[r];
guests[r] = guests[i];
guests[i] = q;
if(guests[i] == i){
i --;
}
}
for(int q : guests){
System.out.println(q);
}
}
}
Maybe the code enters in a inf-loop in another values, but I didn't found any others.
This code can always enter an inf-loop. As I understand the code, you try to do some random switches to achieve your needed result. But if the last element of your array has never been switched, it won't be possible to switch it to any "later/higher" position (because there are no more). In the "last" iteration of your second for-loop (so i + 1 == n holds at the beginning) r will always evaluate to i thus no real switch happens. If the last element is still in place, you gonna repeat this forever.
I am trying to take input into the variable n. However, it gets infinitelly stuck when trying to take input.
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
int i,r=0,max=0;
Scanner s=new Scanner(System.in);
//int i,r=0,max=0;
int n=s.nextInt();
for(i=1;i<=n;i++)
{
while(i>0)
{
r+=i%10;
i/=10;
}
if(max<=r)
max=r;
r=0;
}
System.out.print(max);
}
}
I want the program to take one input, then proceed further in the program and compute the result. But, instead it gets stuck while trying to recieve input.
The problem is that the inner while loop will terminate when i becomes zero. But, the outer for loop will happily keep iterating. So the infinite loop is actually the for loop, which will never end. Without knowing exactly what your code is supposed to be doing, I can suggest that you use another variable instead of i directly:
for (i=1; i <= n; i++) {
int j = i;
while (j > 0) { // use variable j to do the math; don't change loop counter i
r += j % 10;
j /= 10;
}
if (max <= r) { // possibly record a new max value
max = r;
}
r = 0; // always reset r
}
You should use while(i>1) instead. Using while(i>0) doesn't work because you're trying to reach 0 through division, so the loop becomes infinite.
I'm learning Java from a MOOC and am stuck on this one exercise:
Really having trouble with this one. I'm able to create a program that counts up to the user's chosen number (below) but stuck on how to add all the numbers up to variable n.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int start = 0;
System.out.println("Until which number? ");
int n = Integer.parseInt(reader.nextLine());
System.out.println("Counting begins now...");
while (start <= (n - 1)) {
System.out.println(start += 1);
}
}
Any help is appreciated.
You on the right track, firstly to get input on the same line (like in the expected output of your task) use print rather than println.
Then basically just keep track of two "helper" variables count and sum and only print the value of the variable sum once outside the while loop:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Until what?");
int n = scanner.nextInt();
int count = 0;
int sum = 0;
while(count <= n) {
sum += count; // increment the sum variable by the value of count
count++; // increment the count variable by 1
}
System.out.println("Sum is " + sum);
}
}
N.B. Also above I have made use of the Scanner method nextInt() rather than your Integer.parseInt solution, in the future you may want to look into pairing this with hasNextInt() that returns a boolean to ensure your program does not crash if the user inputs something other than an Integer.
Example Usage 1:
Until what? 3
Sum is 6
Example Usage 2:
Until what? 7
Sum is 28
Try it here!
int sum = 0;
while (start <= n) {
sum += start;
++start;
}
System.out.println(sum);
According to your guidelines you need to keep a record of the number of iterations start and you need to calculate the sum stored in its own variable sum.
start needs to increment every iteration
sum needs to be its previous value plus the current value of start
public class problem1 {
public static void main(String args [])
{
int [] a = new int [1000];
for (int counter = 0; counter<=a.length;counter++);
{
if ((counter % 3 == 0) || (counter % 5 == 0))
{
int temp += counter;
}
}
}
}
I am trying to solve an equation where you have to go through an array with the numbers 1-1000, and add up all of the numbers that are multiples of 3 and 5, but my code wont execute. Can anyone see my error?
Your code has two major problems:
You have a semi-colon at the end of your for loop.
for (int counter = 0; counter<=a.length;counter++); // Remove the ;
You are re-declaring your variable each time in your for loop.
int temp += counter; // replace it with `temp += counter`.
And declare the variable temp outside the for loop, with it's default value 0.
And a minor problem is:
You don't need that array a. Rather declare an int variable say total with the required value (in this case, 1000). And use it in loop condition, rather than a.length.
Do not create an array for your counter. It is not necessary, arrays usually store reusable values such as names, cities, ages etc. basically.
Also for loop does not ends with semi-colon.
Most important: Not declare a variable in a loop. If you do it you will create X times variable again and again
public class problem1 {
public static void main(String[] args) {
int temp = 0;
for (int i = 0; i <= 1000; i++)
{
if ((i % 3 == 0) || (i % 5 == 0)) {
temp += i;
}
}
System.out.println("Result is :" + temp);
}
}
Your code will never execute because of the semi-colon at the end of your for, it won't give you compilation error, but it means an empty statement, so the for body will never be executed, just remove the semicolon.
I believe you should initialize int temp outside the for loop first. It should be as follows: int temp = 0; and then temp += counter; should work.
I understand the concept of one having certain advantages over the other depending on the situation but are they interchangeable in every circumstance? My textbooks writes
for (init; test; step) {
statements;
}
is identical to
init;
while (test) {
statements;
step;
}
How would I rewrite the following program in the for loop? I'm having trouble setting the value for the init and the test if i rework the following program into the for loop form.
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("this program sums the digits in an integer");
int n = readInt("enter a positive number: ");
int dsum = 0;
while ( n > 0) {
dsum += n % 10;
n /=10;
}
}
}
int dsum = 0;
for(int n = readInt("enter a positive number: "); n > 0; n /=10) {
dsum += n % 10;
}
As I can't stop myself from writing this, so I'll point it out.
Your for loop: -
for (init; test; step) {
statements;
}
Is not identical to the while loop you posted. The init of the for loop will not be visible outside the loop, whereas, in your while loop, it would be. So, it's just about scope of the variable declared in init part of for loop. It is just inside the loop.
So, here's the exact conversion of your for loop: -
{
init;
while (test) {
statements;
step;
}
}
As far as the conversion of your specific case is concerned, I think you already got the answer.
Well, by the above explanation, the exact conversion of your while loop is a little different from the #Eric's version above, and would be like this: -
int dsum = 0;
int n = 0;
for(n = readInt("enter a positive number: "); n > 0; n /=10) {
dsum += n % 10;
}
Note that this has a very little modification from the the #Eric's answer, in that, it has the declaration of loop variable n outside the for loop. This just follows from the explanation I gave.
Beside the scope of variables declared in the initializer, there is another time when a for will exhibit different behavior, which is in the presence of a continue:
for (init; test; update) {
if(sometest) { continue; }
statements;
}
is NOT identical to
init;
while (test) {
if(sometest) { continue; }
statements;
update;
}
because in the while loop the continue it will skip update, where the for loop will not.
To show this via the starkest of examples, consider the following two loops (thanks #Cruncher):
// terminates
for(int xa=0; xa<10; xa++) { continue; }
// loops forever
int xa=0;
while(xa<10) { continue; xa++; }
+1, good question
The difference between the two is mostly eye-candy. In the one instance the one may simply read better than the other. For your example, the following is the for-loop equivalent in a single line of code. In this case, however, the while loop reads easier.
public void run() {
println("this program sums the digits in an integer");
for (n = readInt("enter a positive number: "), dsum=0; n > 0; dsum+=n%10, n/=10);
}
Yes, except for the two things:
"For" let you declare and initialize your conditions (= variables, btw - more than one variable!) in it, and then it is cleaned up automatically, as you leave the "For" cycle.
Whereas with "While" you will have to do it yourself, initialize - outside the "While", clean up - only as you leave the of visibility where your variables (for conditions) were declared.
"For" has convenient syntax (and all cleanup afterwards) for iteration over collections and arrays.
Your code I would rewrite this way:
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("this program sums the digits in an integer");
for(int n = readInt("enter a positive number: "), dsum = 0; n > 0; n /=10) {
dsum += n % 10;
}
}
}
Don't forget - in init you can place declaration/initialization for more than one variable.
what kind of difficulties you have,anyway
int n = readInt("enter a positive number: ");
for(n;n>0;n=n/10)
{dsum+=n%10;
}
This should work. Replace your while loop with this. Just leave the initialization part empty.
for(;n>0;n=n/10)
{
dsum+=n%10;
}