Java "For" loop output repeats - java

I am a beginner trying to program a java code to produce output numbers that is a prime factor of two and five.
For example, if input is 8, then output should be 2 4 5 8.
However, whenever I print my output, the result will be 2 5 4 5 8 5.
Please advice on where I have gone wrong.
Thank you
import java.util.Scanner;
class twofive {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n:");
int n = sc.nextInt();
double num = 0;
double num2 = 0;
for (int i = 1; (((Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) {
if (( Math.pow(2,i)) <= n)
num = (Math.pow(2,i));
int convert = (int) num;{
System.out.print(convert + " ");
}
if ((Math.pow(5,i)) <= n)
num2 = (Math.pow(5,i));
int convert2 = (int) num2;
{System.out.print(convert2 + " ");
}
}
}
}

After you review #AmedeeVanGasse 's comment, you need to fix your braces.
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n:");
int n = sc.nextInt();
double num = 0;
double num2 = 0;
for (int i = 1; Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) {
if (( Math.pow(2,i)) <= n) {
num = (Math.pow(2,i));
int convert = (int) num;
System.out.print(convert + " ");
}
if ((Math.pow(5,i)) <= n) {
num2 = (Math.pow(5,i));
int convert2 = (int) num2;
System.out.print(convert2 + " ");
}
}
}
You should also review the logic in your for loop and if statements. They are full of unneeded redundancies.

Related

if condition is not working.when i try to execute if conditon,else is working

what's wrong with this?
if condition is not executing.
import java.util.Scanner;
public class ArmstrongNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int n = sc.nextInt();
int temp = n;
int rem = 0;
int sum = 0;
while (n != 0) {
rem = n % 10;
sum = sum + (rem * rem * rem);
n = n / 10;
}
if (temp == n) {
System.out.println("number is a AMSTRONG");
} else {
System.out.println("NUMBER IS NOT AMSTRONG");
}
}
}
Your logic is wrong. if(temp==n) { is after while(n!=0) { so the only way it could be true is if temp == 0.
Your Calcualtion is fine but your compare is wrong. For example the number 153, which is a armstrong number, your variables will have the following values at the end of the loop:
temp = 153
rem = 1
sum = 153
n = 0
So you should not compare temp to n temp == n , how you currently do but temp to sum temp == sum
Also take in mind that your check will only work for three digits numbers, because your power is allways three. So for other armstrong numbers it simply won't work, for example:
54748 = 55 + 45 + 75 + 45 + 85 = 3125 + 1024 + 16807 + 1024 + 32768
In this solution i used the Math libary and the power but there are more ways if you don't like this to calc the length of an number
public class ArmstrongNum {
private static final Scanner SC = new Scanner(System.in);
private static boolean isArmstrongNumber(int n){
int temp = n;
int rem;
int length = (int) (Math.log10(n) + 1);
int sum = 0;
while (n != 0) {
rem = n % 10;
sum = sum + (int) Math.pow(rem, length);
n = n / 10;
}
return temp == sum;
}
public static void main(String[] args) {
System.out.print("ENTER THE NUMBER: ");
int n = SC.nextInt();
if (isArmstrongNumber(n)) {
System.out.printf("%d is a Armstrong number", n);
} else {
System.out.printf("%d is no Armstrong number", n);
}
}
}
Try another way
public static void main(String[] args) {
try {
Scanner sc= new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int n = sc.nextInt();
if (n == 0) {
throw new Exception("Number is 0");
}
int sum = 0;
String number = String.valueOf(n);
char[] chars = number.toCharArray();
double length = chars.length;
for (char item : chars) {
double result = Math.pow(Double.parseDouble(String.valueOf(item)), length);
sum = sum + (int) result;
}
if (sum == n ) {
System.out.println("number is a AMSTRONG");}
else {
System.out.println("NUMBER IS NOT AMSTRONG");
}
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}

count all numbers in range having a specific digit

I want to count how many numbers have digit number 4 in a range of numbers
e.g 1-100 count all numbers having digit number
i.e 4,14,24,34,40,41,42,43,44,45,46,47,48,49,54,64,74,84 and 94 total 19 numbers
I am having problems with counting number of integers with digit 4 in them please help!!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int count = 0;
while (true) {
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
if (num1 != 0 || num2 != 0) {
for (int num = num1; num <= num2; num++) {
while (num != 0) {
int i = num % 10;
if (i == 4) {
count++;
break;
}
num = num / 10;
}
}
System.out.println(count);
}
else
break;
}
}
}
To check if a number contains a specific digit or not, here is a trick you can use :
Convert both number and digit to String and use String::contains (Simple)
Here is a piece of code you can use If you are using Java 8 :
int number = 4, min = 0, max = 100;
String numberToString = String.valueOf(number);
long count = IntStream.rangeClosed(min, max) //Range of numbers between min and max
.filter(n -> String.valueOf(n).contains(numberToString)) // Use the filter
.count();// Then count the result
System.out.println(count); // 19
//a few changes were needed into your code.. here is the solution...
public class MaxOccurance {
public static void main(String[] args) {
int count = 0;
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt(), temp;
if (num1 != 0 || num2 != 0) {
for (int num = num1; num <= num2; num++) {
temp = num;
while (temp != 0) {
int i = temp % 10;
if (i == 4) {
count++;
// break;
}
temp = temp / 10;
}
}
System.out.println(count);
}
}
}

How to sum the digits of two integers?

How could I use the following method to sum the integers of two numbers in a separate method? I'm trying to teach myself how to use overloaded methods but this is starting to confuse me. Thanks!
public static void sumNUmber(){
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
System.out.println(sum);
public static void main(String[] args) throws ClassNotFoundException {
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
System.out.println(sumDigits(num));
}
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
output
Enter a number
234
9
You probably want to take your core algorithm and put it into a single function and then call it twice, once for each number. For example,
// Core algorithm.
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
public static void sumNumber() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int numA = in.nextInt();
System.out.println("Enter another number");
int numB = in.nextInt();
int totalDigits = sumDigits(numA) + sumDigits(numB);
System.out.println(totalDigits);
}
//Merry Xmas :D
public int sumNumbers(int num) {
int returnval;
if (num < 10) {
return num;
} else if (num < 100) {
returnval = Math.floor(num/10) + (num%10);
} else if (num < 1000) {
returnval = Math.floor(num/100) + Math.floor(num/10) + (num%10);
} //repeat as needed
return 0;
}

How can I terminated the program when nextInt equals zero?

I populate an Arraylist<Integer> with palindromic numbers. I then retrieve a user-specified element from the list via its get() method, and print that number. I am trying to use a while loop to allow the user to select multiple elements, until he enters "0", but instead the program exits after the first selection. How can I make it repeat?
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
ArrayList<Integer> str = new ArrayList<Integer>();
for (int i = 1; i <= 1000; i++) {
int a = i;
int b = inverse(a);
if (a == b) {
str.add(a);
}
}
int num = cin.nextInt();
do {
int getnum = str.get(num - 1);
System.out.println(getnum);
}
while(num == 0);
}
public static int inverse(int x) {
int inv = 0;
while (x > 0) {
inv = inv * 10 + x % 10;
x = x / 10;
}
return inv;
}
Your loop test should probably be while it's not equal to zero. Also, you need to get num again.
// int num = cin.nextInt();
int num;
do{
num = cin.nextInt();
System.out.println("num is " + num);
if (num > 0 && num <= str.size()) {
System.out.println(str.get(num - 1));
}
} while(num != 0);

How to display individual digits of integer input?

I am working on an assignment which prompts the user to input an integer, and displays that integer with the digits separated by spaces, and provides the sum of those digits. I have this working, but my individual digit display is form the last digit to the first. How can I make it display the digits from first to last?
Here is what I have so far:
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
System.out.print(" " + temp + " ");
}while (num > 0);
System.out.println("The sum of the digits = " + sum);
}
}
One option would be to use the String#valueOf(Integer) method.
Example
int input = 12345;
String inputStr = String.valueOf(input);
for(char c : inputStr.toCharArray()) {
// Print out each letter.
}
if you use the method String.valueOf(12345)
you can easily reverse the String with the method in this library:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverse(java.lang.String)
StringUtils.reverse(String.valueOf(input));
Here is the solution
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
ArrayList<Integer> values = new ArrayList<>();
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
values.add(temp);
}while (num > 0);
Collections.reverse(values);
Iterator<Integer> it = values.iterator();
while(it.hasNext()){
System.out.println(" "+it.next()+" ");
}
System.out.println("The sum of the digits = " + sum);
}
}
BTW you should have to import ArrayList etc.
I would highly recommend putting the number into a String and then reading it, parsing it, and use the number however you want. As follows,
int input = 12345;
String inputString = input + "";
int sum = 0;
for (int i = 0; i < inputString.length(); i++) {
sum += Integer.parseInt(inputString.charAt(i) + "");
}
System.out.println(sum);
However an alternative way, not as pretty is..
int input = 12345;
int sum = 0;
while (input > 0) {
int i = (input + "").length() - 1;
int n = (int) (input / Math.pow(10, i));
input -= (int) (n * Math.pow(10, i));
sum += n;
}
System.out.println(sum);

Categories