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);
Related
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());
}
}
enter image description hereI am trying to solve this question:
a) Write a method with the following header that takes an integer n and
returns the value of n! (pronounced n factorial) computed as follows:
public static int factorial(int n)
Note that 0! = 1 and n! = n * (n-1) * (n-2)*.....*1.
Example: factorial(4) will return 24 which is = 4*3*2*1.
b) Write a method with the following header that takes an integer x and
returns true if x is a Strong number. Otherwise, it returns false.
public static boolean isStrongNumber(int x)
Note that the isStrongNumber method should call the factorial method to compute the factorial of
each digit in x.
public static int factorial(int n) {
int f =1;
for (int i = 1; i <=n; i++)
f=f*i;
return f;
}
public static boolean isStrongNumber(int x) {
int temp = x;
int z;
int q = 0;
int sum = 0;
while (temp > 0) {
x = x % 10;
z = factorial(x);
q += z;
if (q == temp) {
System.out.print(q + " ");
return true;
}
}
}
This is my answer, but I get an error every time I try to run it.
You did not return boolean value at end of the isStrongNumber method
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static boolean isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
sum += factorial(num % 10);
num /= 10;
}
return sum == originalNum;
}
, main function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = Integer.parseInt(scanner.nextLine());
Set<Integer> set = new TreeSet<>();
for (int i = 1; i <= number; i++) {
if (isStrongNumber(i)) {
set.add(i);
}
}
System.out.println("The Strong numbers between 1 and " + number + " are:");
System.out.println(set);
scanner.close();
}
, output for input 100000
Enter a positive integer: 100000
The Strong numbers between 1 and 100000 are:
[1, 2, 145, 40585]
This cannot compile as it lacks a return statement outside the while loop. In fact, you cant be sure to go inside the loop even once if x<=0 for exmaple. You should add return false outside the loop at the end of the method. Also if you get an error and write a question on StackOverflow, copy the error message it's very helpful.
The question is:
Write a java program to print all prime numbers in the interval [a,b] (a and b, both inclusive).
Conditions are:
Input 1 should be lesser than Input 2. Both the inputs should be positive.
Range must always be greater than zero.
If any of the condition mentioned above fails, then display "Provide valid input"
Use a minimum of one for loop and one while loop.
I came up with a code like this:
import java.util.Scanner;
class PrimeNumbers{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int a = Integer.parseInt(sc.nextLine());
int b = Integer.parseInt(sc.nextLine());
if((a > b) || a <= 0 || b <= 0){
System.out.println("Provide valid input");
}
else{
int i = 0, num = 0;
String prime = "";
for(i = a;i <= b;i++){
int counter = 0;
num = i;
while(num >= 1){
if(i % num == 0)
counter++;
num--;
}
if(counter == 2)
prime = prime + i + " ";
}
System.out.println(prime);
}
}
}
I ran it against test cases. One of the hidden test case just gave a hint "Check for equal range"
I am not sure what that means. Can someone help me out?
package monu;
import java.util.Scanner;
public class Test {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int a = Integer.parseInt(sc.nextLine());
int b = Integer.parseInt(sc.nextLine());
int c = b - a;
if(a > b || c < 0 || a < 0|| b <= 0) {
System.out.println("Provide valid input");
}
else{
int i = 0, num = 0;
String prime = "";
for(i = a; i <= b; i++){
int counter = 0;
num = i;
while (num >= 1) {
if (i % num == 0)
counter++;
num--;
}
if (counter == 2)
prime = prime + i + " ";
}
System.out.println(prime);
}
}
}
This code gets an integer n and displays all palindrome numbers less than n.
But seems the for loop doesn't work; because when I enter a number except 0, 1 and negatives, nothing happens.
I tried debugging, but couldn't find the problem!
Sample input: 30
Sample output: 1 2 3 4 5 6 7 8 9 11 22
import java.util.Scanner;
public class PalindromeNumbers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if (n == 0 || n == 1 || n < 0)
System.out.println("There's no Palindrome Number!");
else {
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
while (num > 0) {
// use modulus operator to strip off the last digit
temp = num % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
num = num / 10;
}
if (reversedNum == num)
System.out.println(num);
}
}
}
}
You run into an infinite loop: you use num in your for loop as an index, and reset it to 0 inside the loop. Use different variables, and it should work!
for (int i = 1; i < n; i++) {
int num = i;
...
if (reversedNum == i)
System.out.println(i);
}
You can do it in a more concise way:
public static void main(final String args[]) {
final Scanner input = new Scanner(System.in);
final int max = input.nextInt();
if (max <= 0) {
System.out.println("There's no Palindrome Number!");
} else {
for (int i = 1; i < max; i++) {
if (isPalindrome(i)) {
System.out.println(i);
}
}
}
}
private static boolean isPalindrome(final int num) {
final String temp = "" + num;
return new StringBuilder(temp).reverse().toString().equals(temp);
}
You are changing your num variable inside your for loop. The next time num < n is executed, the value changed (to 0). Try something like this:
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
int temp2 = num;
while (temp2 > 0) {
// use modulus operator to strip off the last digit
temp = temp2 % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
temp2 = temp2 / 10;
}
if (reversedNum == num)
System.out.println(num);
}
This way, you use a temp variable to calculate your reversedNum, and still keeps the value of num for the next loop iteration.
the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for (int i = 1; i < 10; i++) {
if (digits[i] > count) {
count = digits[i];
digit = i;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.