I have a basic code:
public class experiment {
public static void main(String[] args) {
System.out.println(experiment(80));
}
public static int experiment (int number) {
while (number > 10) {
number = number / 2;
return number;
} return -1;
}
}
It returns me 40.
So it means is not looping on the variable number.
I would like it to keep looping on number (80, 40, 20, 10), till it return 10.
Is there a way to do it without using the for loop?
Move the return out of the loop:
public static int experiment (int number) {
while (number > 10) {
number = number / 2;
}
return number;
}
If you need the -1 for a special case, you should check it before entering the loop:
public static int experiment (int number) {
if (number < 0) { // or some condition
return -1;
}
while (number > 10) {
number = number / 2;
}
return number;
}
BTW, start using a debugger, you can step through this kind of code and find the problem easily.
What wrong is that you put return number inside the while loop it will end the iteration and return the value of 40. So you have to,
public static int experiment (int number) {
while (number > 10) {
number = number / 2;
}
return number;
}
If you want all the numbers the loop has passed to print;
public static void experiment (int number) {
while (number > 10) {
number = number / 2;
System.out.println(number);
}
}
using recursion:
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(test.toTen(80));
}
public static int toTen(int k) {
if (k==10) {
return k;
}
else {
return toTen(k/2);
}
}
}
or simply edit the loop like so
while (k > 10) {
k = k / 2;
}
return k;
Related
I have a problem, I have the correct(PART 1) and incorrect code (PART 2). I cant figure out why the incorrect code is incorrect.
the
static int sum = 0
part is the incorrect part of the code in PART 2. If that line of code is moved to the same location at PART 1. The code works.
if the range is from 10 to 20. PART 2 outputs an incorrect sum of 111. The sum should be 75. There are 3 possible combinations to get 111.
18 + 18 + correct sum
17 +19 + correct sum
16 + 20 + correct sum
Im guessing PART 2 passes through 18 + 18? but how?!
PART 1 Correct Code
ublic class SumOddRange {
public static boolean isOdd(int number){
if (number <= 0) {
return false;
}
return number % 2 != 0;
}
public static int sumOdd(int start, int end){
if ( (end < start) || (start < 0) || (end < 0) ){
return -1;
}
int sum = 0;
for (int i = start; i<=end; i++){
if (isOdd(i)){
sum +=i;
}
}
return sum;
}
PART 2 INCORRECT CODE
public class SumOddRange {
public static boolean isOdd(int number) {
if((number > 0) && (number % 2 != 0)) {
return true;
}
else {
return false;
}
}
static int startOne = 0;
static int sum = 0;
public static int sumOdd(int start, int end) {
if ((end >= start) && (end > 0) && (start > 0)) {
for (startOne = start; startOne <= end; startOne++) {
if (isOdd(startOne)) {
sum += startOne;
}
}
return sum;
} else
return -1;
}
The problem is that you are using static variables.
What does static mean?
After creating a class, you can create instances (also called objects) of this class. This is what happens, when you use a command like
SumOddRange a = new SumOddRange();
SumOddRange b = new SumOddRange();
As you probably know, there are methods and variables in a class. These methods and classes can be seperated into
Class methods and variables
Object methods and variables (object variables are most often called attributes)
This means that some methods and variables do belong to the class, so all the instances of this class share this variable or method. This is what static is used for. So if the class in the image above has a static attribute named staticAttributeName, a.staticAttributeName and b.staticAttributeName have to be the same.
If a variable isn't static, this variable is not shared by the instances. All instances have their own instance of this variable. So although their name is the same, the values saved in the variables doen't have to be the same. So if the class in the image above has a non-static attribute named attributeName, a.attributeName and b.attributeName doesn't have to be the same.
An example:
public class Add {
public static int sum = 0;
public static void addOne() {
sum = sum + 1;
}
}
public class Test {
public static void main(String[] args) {
Add a = new Add();
Add b = new Add();
a.addOne();
b.addOne();
System.out.println("a " + a.sum);
System.out.println("b " + b.sum);
}
}
As you can see, the variable sum is static. This means that a.sum and b.sum are the same. In the main-method, we are calling the method addOne two times, so the two outputs are "a 2" and "b 2".
public class Add {
public int sum = 0;
public void addOne() {
sum = sum + 1;
}
}
public class Test {
public static void main(String[] args) {
Add a = new Add();
Add b = new Add();
a.addOne();
b.addOne();
b.addOne();
System.out.println("a " + a.sum);
System.out.println("b " + b.sum);
}
}
We now have a non-static variable sum in the class Add.
a: We are calling the method addOne one time, so the first output is "a 1".
b: The method addOne is called two times, so the output is "b 2".
Solving the problem
public class Test {
public static void main(String[] args) {
SumOddRange s = new SumOddRange(); //Using class given in PART2 of question
SumOddRange t = new SumOddRange();
System.out.println(s.sumOdd(10,20));
System.out.println(s.sumOdd(10,20));
}
}
This class produces the outputs 75 and 150. This is the case, because s and t use the same variable sum, so the first time, the sum is correct, but the second calculation returns 75+sumOdd(10,20) = 75+75 = 150 as the result.
As we now know, the main problem is that the variable(s) are static. This brings up the idea to just use non-static variables, which is the best idea here:
public class SumOddRange {
public boolean isOdd(int number) {
if((number > 0) && (number % 2 != 0)) {
return true;
}
else {
return false;
}
}
int startOne = 0;
int sum = 0;
public int sumOdd(int start, int end) {
sum = 0;
if ((end >= start) && (end > 0) && (start > 0)) {
for (startOne = start; startOne <= end; startOne++) {
if (isOdd(startOne)) {
sum += startOne;
}
}
return sum;
} else {
return -1;
}
}
}
Another option is to just reset the variable sum before actually calculating the sum. The disadvantage of this approach is that you will not be able to access earlier results anymore:
static int startOne = 0;
static int sum = 0;
public static int sumOdd(int start, int end) {
sum = 0;
if ((end >= start) && (end > 0) && (start > 0)) {
for (startOne = start; startOne <= end; startOne++) {
if (isOdd(startOne)) {
sum += startOne;
}
}
return sum;
} else {
return -1;
}
}
I want my isPrimeNumber function to return a null (so it will not print any of the numbers in the isPrimeNumber function), but methods apparently cannot return null. I want the for loop to gloss over the numbers that print and the prime number function and print numbers that are not in the prime number function and one, i.e. the composite number. Here is what my code looks like:
//prints all composite numbers
public class App {
public static void main(String[] args)
{
for(int i = 1; i <= 10000; i++)
{
if (isPrimeNumber(i))
{
return null;
}else{
System.out.println(i);
}
}
}
public static boolean isPrimeNumber(int i) {
int factors = 0;
int j = 1;
while(j <= i)
{
if(i % j == 0)
{
factors++;
}
j++;
}
return (factors == 2);
}
}
The else statement in the main function is supposed to print all the numbers between 1 and 10000 that are composite. How would I fixed this ?
Don't return null when you find a prime number. Yyou can't return a value from a method with a void return type, but even if this code did pass compilation, you wouldn't want to leave the method when you detect a prime number.
Change the condition from
if (isPrimeNumber(i)) {
return null;
} else {
System.out.println(i);
}
to
if (!isPrimeNumber(i)) {
System.out.println(i);
}
input:
123
output:
6 >>> (It is the sum of all digits)
I want the output will:
321
That means each digit separately
What is wrong in the code?
The code:
public class t4 {
public static void main(String[] args) {
System.out.println(ReverseNum(123));
}
public static int ReverseNum(int num) {
int dig = 0;
if (num == 0)
return dig;
dig = dig * 10 + num % 10;
return ReverseNum(num / 10) + dig;
}
}
thank's
Try this.
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
reverseMethod(number/10);
}
}
You can try:
public class t4 {
public static void main(String[] args) {
System.out.println(ReverseNum(123));
}
public static String ReverseNum(int num) {
if (num == 0)
return "";
return "" + num % 10 + ReverseNum(num / 10);
}
}
Find the largest power of ten smaller than the number first and use it to for reversing the number. This allows you to "move the digits to the right places":
public static int findPow10(int num) {
if (num < 10) {
return 1;
} else {
return 10 * findPow10(num / 10);
}
}
private static int reverseHelper(int num, int factor) {
if (num == 0) {
return 0;
} else {
return factor * (num % 10) + reverseHelper(num / 10, factor / 10);
}
}
public static int reverse(int num) {
return reverseHelper(num, findPow10(num));
}
public static void main(String[] args) {
System.out.println(reverse(123));
}
Rather than printing the values, I'm trying to return the number. This is what I could come up with so far. I think someone else might be able to do a better job. It's not that elegant with the while loop inside.
public static int ReverseNum(int num) {
if (num < 10){
return num;
}
int val = 1; int n = num;
while(n > 10){
n = n/10;
val = val * 10;
}
return (num % 10)*val + ReverseNum((num - num % 10)/10);
}
class Solution
{
//A method for reverse
public static void reverseMethod(int number)
{
if (number < 10)
{
System.out.println(number);
}
else {
System.out.print(number % 10); // 123 % 10 = 3
//Method is calling itself: recursion
reverseMethod(number/10); //123/10 = 12 integer ignore decimal number
}
}
public static void main(String args[])
{
reverseMethod(123);
}
}
I have to write a program that takes a number from the user and then displays the prime factors of the number. This is the program I have so far:
public static void main(String[] args) {
int a = getInt("Give a number: ");
int i = 0;
System.out.println("Your prime factors are: " + primeFactorization(a, i));
}
public static int getInt(String prompt) {
int input;
System.out.print(prompt);
input = console.nextInt();
return input;
}
public static int primeFactorization(int a, int i) {
for (i = 2; i <= a ; i++) {
while (a % i == 0) {
a /= i;
}
}
return i;
}
}
I can't figure out how to get it to print out the list of numbers. Any help is appreciated.
You should return a List<Integer> not a single int, and there is no point in i being an argument. A correct method is
public static List<Integer> primeFactorization(int a) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 2; i <= a ; i++) {
while (a % i == 0) {
list.add(i);
a /= i;
}
}
return list;
}
While #Paul Boddington's answer is better in most cases (i.e. if you are using the values afterwards), for a simple program like yours, you could add all of the factors to a string and return the string. For example:
public static String primeFactorization(int a) {
String factors = "";
for (int i = 2; i <= a ; i++) {
while (a % i == 0) {
factors += i + " ";
a /= i;
}
}
return factors;
}
Consider the number 2345.If you multiply the digits of it then you get the number 120.Now if you again multiply the digits of 120 then you will get 0 which is one digit.
import java.util.Scanner;
public class SmallestNum
{
int prod=1,sum=0;
void product(int m)
{
while(m!=0)
{
int a=m%10;
m=m/10;
prod=prod*a;
}
System.out.println(prod);
}
public static void main(String args[])
{
Scanner scn=new Scanner(System.in);
int x=scn.nextInt();
SmallestNum sn=new SmallestNum();
sn.product(x);
}
}
I can get the 120 from this code.But how can i do the same procedure with 120 and get the answer 0.Pls help me.
You can just add an other loop around your while, the end condition being prod < 10, i.e. having only one number.
void product(int m)
{
int prod;
do {
prod = 1;
while(m!=0)
{
int a = m%10;
m = m / 10;
prod *= a;
}
System.out.println(prod);
} while (prod >= 10);
}
public int reduceToOneDigit(int inputNumber){
int result = 1;
while(inputNumber > 0){
result *= (inputNumber % 10);
inputNumber /= 10;
}
if (result > 9)
result = reduceToOneDigit(result);
return result;
}
So basically: multiply the digits of your inputNumber. If the result has more than one digit (so result is > 9, at least 10) call method recursively on the result.
Alternatively, do the same without recursion, using a do-while loop:
public int reduceToOneDigitNoRecursion(int inputNumber){
int result = 1;
do{
while(inputNumber > 0){
result *= (inputNumber % 10);
inputNumber /= 10;
}
}
while(result > 9);
return result;
}
Use recurssion
void product(int m)
{
if(m%10 == 0){
return;
}
while(m!=0)
{
int a=m%10;
m=m/10;
prod=prod*a;
}
System.out.println(prod);
product(prod);//repeat the procedure
}
Recursive call the function
if(String.valueOf(prod).length()>1){
product(prod)
}
complete code
public class SmallestNum
{
int prod=1,sum=0;
void product(int m)
{
while(m!=0)
{
int a=m%10;
m=m/10;
prod=prod*a;
}
if(String.valueOf(prod).length()>1){
product(prod)
}
System.out.println(prod);
}
public static void main(String args[])
{
Scanner scn=new Scanner(System.in);
int x=scn.nextInt();
SmallestNum sn=new SmallestNum();
sn.product(x);
}
}
make member function product return to an int. then instead of sn.product(x);
int p = sn.product(x);
while (p > 9)
{
p = sn.product(t);
}