Divisible by three - java

i'm new in coding and tried to do some open university tasks. Maybe you guys can give some helping hand. I really even don't know how to start this task, witch is divide three Integers from main to method. Example 2, 10 where I should print 3, 6, 9 or 2, 6 where I should print 3, 6.
import java.util.Scanner;
public class divideByThree {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
divideByThree(2, 10);
}
public static void divideByThree(int start, int end) {
while(true) {
if (start % 3 == 0) {
start++;
}
if (end % 3 == 0) {
System.out.println(end);
}
System.out.println(start);
}
}
}

How about the following implementation about divideByThree method?
public static void divideByThree(int start, int end) {
for(int i = start; i <= end; ++i){
if(i%3==0){
System.out.print(i+" ");
}
}
}

Do not use while(true) because it creates an infinite loop which will unnecessarily make your program complex.
You need to increase start by 1 in each iteration and terminate the loop when the value of start value goes beyond end.
Whenever start % 3 == 0 becomes true, print start.
Given below is a sample code which you can use to understand the points mentioned above.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter the start number: ");
int start = reader.nextInt();
System.out.print("Enter the end number: ");
int end = reader.nextInt();
divideByThree(start, end);
}
public static void divideByThree(int start, int end) {
while (start <= end) {
if (start % 3 == 0) {
System.out.println(start);
}
start++;
}
}
}
A sample run:
Enter the start number: 3
Enter the end number: 9
3
6
9

Recursive Approach
import java.util.Scanner;
public class DivideByThree {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int start = reader.nextInt();
int end = reader.nextInt();
divideByThree(start, end);
reader.close();
}
public static void divideByThree(int start, int end) {
if(start % 3 == 0) {
System.out.println(start);
}
if( start <= end) {
divideByThree(++start, end);
}
}
}

The while(true) is an endless loop (something you would want to avoid). It will only stop if you add a break statement somewhere inside it, which you do not have.
I assume this is the issue you need to solve. The key to solving it is simply making sure that your loop stops at some point. How do you do that?
True is a boolean value. a while loop runs again and again for as long as the specified condition remains true, and in your case - it is always true. What you need to do is replace while(true) with while(some condition that will be false at some point). In your specific case, while(start <= end) seems appropriate - just make sure to increment start at every iteration.
Another way of doing it would be using a for loop, i.e:
for (int i = start; i <= end; i++) {
// your code
}
This type of loop takes care of stating the conditions for which the loop should keep on running, and also takes care of incrementing the index i to make sure the loop stops running at some point.

I will make some small changes in your code only so that you will be able to understand quickly.
public static void divideByThree(int start, int end) {
while(start! =end) {
if (start % 3 == 0) {
System.out.println(start);
start++;
}
}
}

Related

Program not getting terminated

I've been doing a Java MOOC, and I'm stuck on a submission as my program does not terminate although I get desired output.
The problem says:
Create a method called printText which prints the phrase "In a hole in the ground there lived a method" and a newline. Then expand the program so that the main program asks the user for the number of times the phrase will be printed (i.e. how many times the method will be called).
I think the problem might be in my while loop not getting terminated.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many times?");
int n = Integer.valueOf(scanner.nextLine());
int a = 0;
while (true) {
if (a < n) {
printText();
a++;
}
}
}
public static void printText() {
System.out.println("In a hole in the ground there lived a method");
}
Your a < n condition should be associated with your loop. Although the if ensures that printText() is only called n times, it does not prevent the infinite loop from continuing forever:
while (a < n) {
printText();
a++;
}
Alternatively, you can keep your infinite loop but break when a >= n:
while (true) {
if (a < n) {
printText();
a++;
} else {
break;
}
}
But the first solution is more readable, in my opinion.
You are almost on track, get rid of outer loop while loop and change if (a < n) to while(a<n)
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many times?");
int n = Integer.valueOf(scanner.nextLine());
int a = 0;
while(a < n) {
printText();
a++;
}
}
public static void printText() {
System.out.println("In a hole in the ground there lived a method");
}
}

N prime numbers in java

So I've written this code in java which should output numbers on the screen from 1 to n(given by the user) and it should write "-prime" near the ones that are prime.
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++)
for(j=2;j<=n/2;j++)
{
if(i%j==0)
System.out.println(i);
else System.out.println(i +"-prime");
}}
}
If I input 6 for example i get :
Dati n: 6
1-prime
1-prime
2
2-prime
3-prime
3
4
4-prime
5-prime
5-prime
6
6
I'm new to this, and i'm really struggling with my algorithmic, could you tell me how should i change my program so it outputs correct values, and explain to me what i did wrong ? Thank you
UPDATE:
I've done it, thank you everyone for helping me out : this is the outcome:
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
boolean gasit = false;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++) {
gasit=false;
for(j=2;j*j<=i;j++)
{
if(i%j==0) gasit=true;}
if(!gasit) {System.out.println(i+"-prime");}
else {
System.out.println(i);}
}
}
}
You print something on every iteration of the inner loop.
Instead, you should print something after all iterations have completed, e.g.
boolean found = false;
for(j=2;j<=n/2;j++) {
if(i%j==0) found = true;
}
if (!found) {
System.out.println(i + "-prime");
} else {
System.out.println(i);
}
Additionally, you shouldn't be going up to n/2: you perhaps mean i/2 (a number doesn't have any factors greater than itself); but you can make it even tighter, since you don't have to check for factors greater than sqrt(i). Or, stated another way, that j * j <= i.
So you can make your loop declaration:
for(j=2; j*j<=i; j++) {
The problem is that the second loop goes until n/2, it should go until i/2 to check if i is prime. A more optimzed version of the primality check algorithm goes until sqrt(i), as suggested in comments.
The next issue is that you are concluding, in a false way, that if in the first case if(i%j==0) you say not prime, otherwise you say it is prime, which is not true necessairly. You should iterate the whole interval of values between [2:i/2] to conclude that i is prime.

Addition with while loop in java

I'm trying to figure out how to create a java program where the user inputs a series of integers, the last integer being a 0 (when the program should stop). After stopping, the program should print out the sum of the integers. This needs to be done using a while (true) loop with an if statement
if (num == 0) {
break;
}
With everything I have tried so far, the loop will not stop even when 0 is inputted.
1) Declare a sum variable
2) Start a infinite loop
3) Read user input
4) Add it to sum variable
5) If the user input is 0 break out of the loop and print the value of sum.
import java.util.Scanner;
public class Statictest {
public static void main(String[] args) {
int sum = 0;
Scanner scn = new Scanner(System.in);
while (true) {
int temp = scn.nextInt();
if (temp == 0) {
break;
}
sum += temp;
}
System.out.println("Sum: " + sum);
}
}

Why does my code only execute once

I want to print all the even numbers, but it only gives me 0!!
public class DataType {
public static void main(String[] args){
int number=0;
int max=20;
do{
System.out.println("this is an even number"+ number);
number++;
}while(number<=max&&EvenNumber(number));
}
public static boolean EvenNumber(int a)
{
if((a%2)==0)
{
return true;
}else
return false;
}
}
that is what your condition states: do while both conditions meet!, afters doing number++ for the 1st time the left side of the condition returns false and your loop is done!
you mean for sure:
do {
if (isEvenNumber(number)) {
System.out.println("this is an even number" + number);
}
number++;
} while (number <= max);
remember, following code means
while(number <= max && EvenNumber(number))
while BOTH conditions meet...
After number++;, number becomes 1, and thus the condition becomes false, and the loop terminates.
I assume, you wanted to do
do {
if (isEvenNumber(number)) System.out.println(number);
number++;
} while(number<=max);
Because in your code, If number is equals to 1, while condition is false
If you intend to find all even number between [0, 20] you may change your code to this version:
public static void main(String[] args) {
int max=20;
for (int number = 0; number <= max; number++) {
if (number % 2 == 0) {
System.out.printf("%d is an even number.\n", number);
}
}
}
This reads like:
start with number 0
while number not past 20
if number is even print it
continue with next number
Because in the second iteration the loop will exit.
if you want to print even numbers then the code should be
do{
if(EvenNumber(number)) {
System.out.println("this is an even number"+ number);
}
number++;
}while(number<=max );

How to recurse back to start?

I'm a noob programmer, but I've been stuck on this one bit of code. How do you recurse back to start? I've tried several different methods but they all either take a ridiculous amount of code or don't work properly. I've been trying to implement this "simple" piece of code in all of my programming assignments, but it hasn't been working out. Thanks!
p.s. I've already finished the assignment. I'm just trying to make it more "complete".
public class OddProduct {
public static void main(String[] args) {
//Inputs from user
System.out.println("Enter an odd number");
Scanner input_odd = new Scanner(System.in);
int odd = input_odd.nextInt();
int oddproduct = 1;
//Multiplies all odd integers
for (int counter = 1; counter <= odd; counter = counter + 2){
oddproduct = oddproduct * counter;
}//end of for- loop
System.out.printf("\nThe product of all the odd integers up to %d is %d\n",
odd, oddproduct);
/* MY NOTES FOR RECURSE
if (odd%2 == 1){ proceed normally}
else if (odd%2 != 1) { HOW TO LOOP BACK???}
else { println = "Application closed"}
*/
}//end of main method
}//end of OddProduct class
Based upon your Notes I think this is what you require
Scanner input_odd = new Scanner(System.in);
int odd = 0;
while (odd % 2 != 1) { // fails first time && if user enters even number
System.out.println("Enter an odd number");
odd = input_odd.nextInt();
}

Categories