public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+"!="+factorial(n));
}
public static int factorial(int num) {
return (num == 0) ? 1 : num * factorial (num - 1);
}
}
how make this code to text in console 3! = 1*2*3 = 6?
Don't use recursion for this. Besides, it isn't really efficient or necessary.
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int fact = 1;
String s = n + "! = 1";
for (int i = 2; i <= n; i++) {
fact *= i;
s += "*" + i;
}
s += " = ";
System.out.println(s + fact);
There can be many ways to do it e.g. you can build the required string or print the trail while calculating the factorial. In the following example, I have done the former.
As an aside, you should check the input whether it is a positive integer.
import java.util.Scanner;
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = in.nextInt();
if (n >= 0) {
StringBuilder strFact = new StringBuilder();
int fact = factorial(n, strFact);
if (strFact.length() > 0) {
// Delete the last '*'
strFact.deleteCharAt(strFact.length() - 1);
System.out.println(n + "!= " + strFact + " = " + fact);
} else {
System.out.println(n + "!= " + fact);
}
} else {
System.out.println("This is an invalid input.");
}
}
public static int factorial(int num, StringBuilder strFact) {
int fact;
if (num == 0) {
fact = 1;
} else {
fact = num * factorial(num - 1, strFact);
strFact.append(num + "*");
}
return fact;
}
}
A sample run:
Enter an integer: 3
3!= 1*2*3 = 6
Related
I am writing a simple code in Java that is using recursion. I want to show the product of two numbers that a user will enter. I managed to do that using recursion, but stuck at the point where I want to show that the product could be written as (example) 10*5 = 5+5+5+5+5+5+5+5+5+5 (10 times), or 12*3 = 3+3+3+3+3+3+3+3+3+3+3+3 (12 times). Here is my code so far. In the code i put a comment where it should be written (example). Thanks.
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a, b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.println("The product of " + a + " and "
+ b + " is: " + multiRec(a, b));
System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
return x + (multiRec(x, y - 1));
}
}
}
}
A StringBuilder should be defiend as
StringBuilder buf = new StringBuilder (a);
Pass this StringBuilder paramater into multiRec
and then change multiRec to be
public static int multiRec(int x, int y, StringBuilder buf) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
buf.append (" + ").append (x);
return x + (multiRec(x, y - 1, buf));
}
}
}
}
Then when completed simply printout its value
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a , b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.printf("%d %s %d %s",a , "*" , b ,"= ");
System.out.println("\nThe product of " + a + " and "
+ b + " is: " + multiRec(b, a));
// System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
System.out.print(x+" ");
if (y == 1) {
return x;
} else {
System.out.print(" + ");
return x + (multiRec(x, y - 1));
}
}
}
}
this is my program:
public class ArmstrongNumber {
public static void main(String args[]) {
int n = 0, temp = 0, r = 0, s = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number ");
if (in.hasNextInt()) {
n = in.nextInt(); // if there is another number
} else {
n = 0;
}
temp = n;
while (n != 0) {
r = n % 10;
s = s + (r * r * r);
n = n / 10;
}
if (temp == s) {
System.out.println(n + " is an Armstrong Number");
} else {
System.out.println(n + " is not an Armstrong Number");
}
}
}
output:
Exception in thread "main" java.lang.NoClassDefFoundError
I tried it using DataInputStream but still getting same error.
// To check the given no is Armstrong number (Java Code)
class CheckArmStrong{
public static void main(String str[]){
int n=153,a, b=0, c=n;
while(n>0){
a=n%10; n=n/10; b=b+(a*a*a);
System.out.println(a+" "+n+" "+b); // to see the logic
}
if(c==b) System.out.println("Armstrong number");
else System.out.println(" Not Armstrong number");
}
}
Find any digit is Armstrong number or not using loop
for(int arm_num = 0 ; arm_num < 100000 ; arm_num++)
{
String[] data = String.valueOf(arm_num).split("(?<=.)");
int lngth = String.valueOf(arm_num).length();
int arm_t_num = 0;
int ary[] = new int[lngth];
for(int i = 0 ; i < lngth ; i++)
{
ary[i] = Integer.parseInt(data[i]);
for(int x = 0 ; x < lngth-1 ; x++)
{
ary[i] = ary[i] * Integer.parseInt(data[i]);
}
arm_t_num+=ary[i];
}
if(arm_num == arm_t_num)
{
System.out.println("Number is ArmStrong : "+arm_num);
}
}
you need to set CLASS_PATH variable and point it to where ever your class file is
then this should work
I have tried it locally, refer my answer to check how to set class path and how to compile and run java code using command prompt
//This is my program to check whether the number is armstrong or not!!
package myprogram2;
public class Myprogram2 {
public static void main(String[] args)
{
String No="407";
int length_no=No.length();
char[] S=new char[length_no];
int[] b = new int[length_no];
int arm=0;
for(int i=0;i<length_no;i++)
{
S[i]=No.charAt(i);
b[i]=Character.getNumericValue(S[i]);
//System.out.print(b[i]);
arm=arm + (b[i]*b[i]*b[i]);
System.out.println(arm);
}
//System.out.println(" is the number \n now Checking for its Armstrong condition");
int orgno = Integer.parseInt(No);
if (orgno==arm)
System.out.println("YESm its an armstrong");
else
System.out.println("\n<<Not an armstrong>>");
//System.out.println(length_no);
System.out.println("Original number is "+orgno);
System.out.println("Sum of cubes "+arm);
}
}
There are a couple of nice String-based solutions and numeric solutions with single-letter variable names.
Consider this to make sense of how it works numerically, which includes a couple of interesting numeric tricks:
import java.io.*;
public class Armstrong
{
public static void main(String args[]) throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int modifiedNumber, originalNumber, modifiedNumberWithUnitsDigitZero,
unitsDigit, runningSum;
System.out.println("Enter your number:");
modifiedNumber = Integer.parseInt(in.readLine());
runningSum = 0;
originalNumber = modifiedNumber;
while(modifiedNumber > 0)
{
modifiedNumberWithUnitsDigitZero = modifiedNumber / 10 * 10;
unitsDigit = modifiedNumber - modifiedNumberWithUnitsDigitZero;
runningSum += unitsDigit * unitsDigit * unitsDigit;
modifiedNumber = modifiedNumber / 10;
}
System.out.println("The number " + originalNumber
+ (originalNumber == runningSum ? " IS" : " is NOT")
+ " an Armstrong number because sum of cubes of digits is " + runningSum);
}
}
import java.util.Scanner;
public class Amst {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter The No. To Find ArmStrong Check");
int i = sc.nextInt();
int sum = 0;
for(int j = i; j>0 ; j = j/10){
sum = sum + ((j%10)*(j%10)*(j%10));
}
if(sum == i)
System.out.println("Armstrong");
else
System.out.println("Not Armstrong");
}
}
For 'N' digit amstrong number
package jjtest;
public class Amstrong {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=54748;
int c=0;
int temp=num;
int b=1;
int length = (int)(Math.log10(num)+1);
while(num>0){
int r = num%10;
num=num/10;
int a =1;
for(int i=1;i<=length;++i){
b=b*r;
}
c = c + b;
b=1;
}
System.out.println(c);
if(c==temp){
System.out.println("its an amstrong number");
}else{
System.out.println("its not an amstrong number");
}
}
}
This is the simple logic for Armstrong number program :
for (int i = number; i > 0; i = i / 10)
{
remainder = i % 10;
sum = sum + remainder * remainder * remainder;
}
if(sum == number)
{
System.out.println("\n" + number + " is an Armstrong Number\n");
}
Reference :
http://topjavatutorial.com/java/java-programs/java-program-to-check-if-a-number-is-armstrong-number/
import java.util.Scanner;
/* a number is armstrong if the sum of cubes if individual digits of
a number is equal to the number itself.for example, 371 is
an armstrong number. 3^3+7^3+1^3=371.
some others are 153,370,407 etc.*/
public class ArmstrongNumber {
public static void main(String args[]) {
int input, store, output=0, modolus;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a number for ckecking.");
input = in.nextInt();
store = input;
while(input != 0) {
modolus = input % 10;
output = output + (modolus * modolus * modolus);
input = input / 10;
}
System.out.println(output);
if(store == output) {
System.out.println("This is an armstrong number.");
} else {
System.out.println("This is not an armstrong number.");
}
in.close();
}
}
import java.util.*;
public class ArmstrongNumber
{
public static void main( String[] args )
{
int n = 0, temp = 0, r = 0, s = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number ");
if (in.hasNextInt()) {
n = in.nextInt(); // if there is another number
} else {
n = 0;
}
temp = n;
while (n != 0) {
r = n % 10;
s = s + (r * r * r);
n = n / 10;
}
if (temp == s) {
System.out.println(temp + " is an Armstrong Number");
} else {
System.out.println(temp + " is not an Armstrong Number");
}
}
}
You missed to import java.util package
Change n to temp in S.O.P
import java.util.Scanner;
public class AmstrongNumber {
public static void main(String[] args) {
System.out.println("Enter the number");
Scanner scan=new Scanner(System.in);
int x=scan.nextInt();
int temp2=0;
String s1 = Integer.toString(x);
int[] a = new int[s1.length()];
int[] a1 = new int[s1.length()];
for (int i = 0; i < s1.length(); i++){
a[i] = s1.charAt(i)- '0';
int temp1=a[i];
a1[i]=temp1*temp1*temp1;
}
for (int i = 0; i < s1.length(); i++){
temp2=temp2+a1[i];
if(i==s1.length()-1){
if(x==temp2){
System.out.println("Amstrong num");
}else{
System.out.println("Not !");
}
}
}
}
}
private static boolean isArmstrong(int num) {
int totalSum = 0;
int copyNum = num;
while (num != 0) {
int reminder = num % 10;
int cubeOfReminder = reminder * reminder * reminder;
totalSum = totalSum + cubeOfReminder;
num = num / 10;
}
if (copyNum == totalSum)
return true;
return false;
}
public class Testamstrong
{
public static void main(String...strings) {
int num = 153,temp;
temp = num;
if(temp == amstrongNumber(num)) {
System.out.println("Number is amstrong number...");
}
else {
System.out.println("Number is not amstrong number...");
}
}
public static int amstrongNumber(int num) {
int count=0,sum=0;
count = String.valueOf(num).length();
char[] ch = String.valueOf(num).toCharArray();
for(char ch1:ch) {
int num1 = Character.getNumericValue(ch1);
sum += Math.pow(num1, count);
}
return sum;
}
}
Find Armstrong number using for loops (with example)
import java.util.*;
public class ArmstorngNumber {
public static void main(String args[]) {
int cube, num, quo, n;
int s = 0;
do
{
System.out.println("Enter Your Number");
Scanner sc = new Scanner(System.in);
num = sc.nextInt();//153
n = num;
for (int i = 0; i < 10; i++) {
int rem = num % 10;//3
quo = num / 10; //15
cube = rem * rem * rem;//9
s = s + cube;//0+9
num = quo;//0
}
System.out.println(s);
System.out.println(n);
if (s == n) {
System.out.println("The number is Armstrong");
System.out.println("-------------------------------------");
}
else {
System.out.println("The number is not Armstrong");
System.out.println("-------------------------------------");
}
}
while (n > 0);
}
}
Check the Armstrong number of any number [java] [Armstrong]
import java.util.*;
public class Armstrong {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("enter any number?");
int x = sc.nextInt();
int n=0;
int number = x;
int j =x;
int result = 0 ,remainder;
while (x!=0) {
x/=10;
++n;
}
for(;j>0 ;j=j/10) {
remainder=j%10;
result+=Math.pow(remainder, n);
}
if (number==result) {
System.out.print(number +" is Armstrong ");
}
else
System.out.print(number +" is not Armstrong");
}
}
here is my code, please check if this works for you!
import java.util.Scanner;
public class Armstromg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the number: ");
int num = sc.nextInt();
int length = 0;
int temp1 = num;
while(temp1 != 0) {
temp1/=10;
length+=1;
}
int result = 1;
int temp2 = num;
for(int i = 1; i <= length; i++) {
temp2 = temp2 % 10;
result*=Math.pow(temp2,length);
}
if(result == num) {
System.out.print("The number is an armstrong number!");
} else {
System.out.print("The number is not an armstrong number");
}
}
}
package Loops;
public class ArmStrongNumber {
public static void main(String[] args) {
int digit1, digit2, digit3;
int number = 153;
int temp = number;
digit1 = number % 10;
number = number / 10;
digit2 = number % 10;
number = number / 10;
digit3 = number % 10;
if ((digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3) == temp) {
System.out.println(+temp + " Number is Armstrong ");
} else {
System.out.println("Number is not Armstrong");
}
}
}
//Not limited to 3 digit integers
public static void main(String[] args)
{
int num = 54748,a,sum=0;
int x = num;
int p =Integer.toString(num).length();
while (num !=0)
{
a = num%10;
num = num/10;
sum = sum + (int) Math.pow(a, p);
}
if (x==sum)
System.out.println("Its an Armstrong number");
else
System.out.println("Not an Armstrong number");
}
}
Scanner input = new Scanner (System.in);
int num , counter = 0 ,temp;
System.out.print("Enter Nmber :");
num = input.nextInt();
int lnum = num;
while ( num != 0 ){
num = num/10 ;
counter++;
}
int store_num_keyboard_input = lnum;
int new_tot = 0;
int c = counter;
while(lnum > 0){
temp = lnum % 10;
lnum = lnum / 10 ;
int m = 0; //m is counter
int tot = 1;
while (m != c){
tot = tot * temp;
m++;
}
new_tot = new_tot + tot;
}
System.out.println("new total "+ new_tot );
if(new_tot == store_num_keyboard_input){
System.out.println(store_num_keyboard_input + " is an Armstrong number" );
}
else{
System.out.println(store_num_keyboard_input + " is not an Armstrong number" );
}
My answer using JAVA 8
tested for..[1, 153, 370, 371, 407]
public class Armstrong {
public static boolean isArmstrong(int num) {
return num == getArmstrongSum(num);
}
public static int getArmstrongSum(int num) {
int pow = String.valueOf(num).length();
return IntStream.iterate(num, i -> i / 10)
.limit(pow)
.map(i -> (int) Math.pow(i % 10, 3))
.sum();
}
public static void main(String[] args) {
System.out.println(isArmstrong(153));
}
}
Thank you.
I wrote the following program which displays if a number is a prime and if not a prime it display its prime factors and the next prime number.
However, I am not sure how to have the program ask the user if he/she wishes to input another number.
The user must answer either yes, no, y or n using any combination of lower and upper case letters.
If an invalid answer is given, the program must be informed that the answer was not acceptable, and then be prompted again for another answer. The program will only prompt up to three tries otherwise the program will exit.
If the answer is Yes (in any allowed form), the program must continue from step in the main function.
The program is written in prototype methods because that is what is called for.
If anyone can assist a newbie with the last part, i would greatly appreciate it.
code:
package primefactors;
import java.util.Scanner;
public class Primefactors {
//------------------three tries check method-------------------
public static int getNumberWithThreeTries(int m) {
int count = 1;
int number;
String s = "tries";
while (count <= 3) {
number = getInputNumber(m); //getScore returns -1 for invalid inputs
if (number <= 1) {
if ((3 - count) < 2) {
s = "try"; //just make sure that singular /plural form in the next statme is correct
}
if (count == 3) {
System.out.println("No more tries remaining!\n");
} else {
System.out.println((3 - count) + " " + s + " remaining! Try Again! \n");
}
count = count + 1;
} else {
return number;
}
}
return -1;
}
//-------------------boolean try again---work in progress---------------
public boolean askRunAgain() {
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean askRunAgain = scanner.nextBoolean();
return askRunAgain;
}
//----------------------------------boolen prime check method------------------
public static boolean isPrime(int m) {
for (int i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
}
return true;
}
//------------------------next prime method-----------------
private static int nextPrime(int m) {
if (m % 2 == 0) {
m = m + 1;
}
for (m = m; !isPrime(m); m = m + 2)
;
return m;
}
//---------------------primefactors----------------------
public static String getPrimeFactors(int m) {
String ans = "";
for (int i = 2; i <= m; i = i + 1) {
if (m % i == 0) {
ans += i + "*";
m = (m / i);
i--;
}
}
return (ans.substring(0, ans.length() - 1));
}
//----------------------------------------------------------
public static int getInputNumber(int m) {
Scanner n = new Scanner(System.in);
int number = 0;
System.out.println("Enter an Integer greater than 1");
if (!n.hasNextInt()) {
System.out.print("That's not a number! you have ");
n.next();
return -1;
}
number = n.nextInt();
if (number <= 1) {
return -1;
}
return number;
}
//------------------------------main method ----------------------
public static void main(String[] args) {
int number;
int count = 0;
number = getNumberWithThreeTries(1);
if (number <= 1) {
System.out.println("Program Terminated");
System.exit(0);
}
if (isPrime(number)) {
System.out.println(number + ": Is a Prime Number \n\n"
+ getPrimeFactors(number) + ": Is its prime factor");
} else {
System.out.println(number + " Is not a Prime number\n\n"
+ getPrimeFactors(number) + " Are its prime factors \n\n"
+ nextPrime(number) + " Is the next Prime number\n ");
}
}
}
You need to place the getNumberWithThreeTries within a while loop, which at the end, ask if the user wants to try again. If they say yes, then your while loop should then continue to execute again, otherwise, it should exit.
I am creating a code that allows you to convert a binary number to a decimal number and vice versa. I have created a code that converts decimal to binary but can not workout how to implement the binary to decimal aspect.
My code for decimal to binary is below:
import java.util.*;
public class decimalToBinaryTest
{
public static void main (String [] args)
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive interger");
n=in.nextInt();
if(n < 0)
{
System.out.println("Not a positive interger");
}
else
{
System.out.print("Convert to binary is: ");
binaryform(n);
}
}
private static Object binaryform(int number)
{
int remainder;
if(number <= 1)
{
System.out.print(number);
return " ";
}
remainder= number % 2;
binaryform(number >> 1);
System.out.print(remainder);
{
return " ";
}
}
}
An explanation to how the binary to decimal code work would help as well.
I have tried the method of the least significant digit*1 then the next least *1*2 then *1*2*2 but can not get it to work.
Thank you #korhner I used your number system with arrays and if statements.
This is my working code:
import java.util.*;
public class binaryToDecimalConvertor
{
public static void main (String [] args)
{
int [] positionNumsArr= {1,2,4,8,16,32,64,128};
int[] numberSplit = new int [8];
Scanner scanNum = new Scanner(System.in);
int count1=0;
int decimalValue=0;
System.out.println("Please enter a positive binary number.(Only 1s and 0s)");
int number = scanNum.nextInt();
while (number > 0)
{
numberSplit[count1]=( number % 10);
if(numberSplit[count1]!=1 && numberSplit[count1] !=0)
{
System.out.println("Was not made of only \"1\" or \"0\" The program will now restart");
main(null);
}
count1++;
number = number / 10;
}
for(int count2 = 0;count2<8;count2++)
{
if(numberSplit[count2]==1)
{
decimalValue=decimalValue+positionNumsArr[count2];
}
}
System.out.print(decimalValue);
}
}
sample:
00000100
0 - 1
0 - 2
1 - 4
0 - 8
0 - 16
0 - 32
0 - 64
0 - 128
Sum values with bit 1 = 4
Good luck!
int decimal = Integer.parseInt("101101101010111", 2);
or if you prefer to doit your self
double output=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)== '1')
output=output + Math.pow(2,str.length()-1-i);
}
Here is a program which does that.
Make sure the integers you give to int and not too large.
import java.util.Scanner;
public class DecimalBinaryProgram {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true){
System.out.println("Enter integer in decimal form (or # to quit):");
String s1 = in.nextLine();
if ("#".equalsIgnoreCase(s1.trim())){
break;
}
System.out.println(decimalToBinary(s1));
System.out.println("Enter integer in binary form (or # to quit):");
String s2 = in.nextLine();
if ("#".equalsIgnoreCase(s2.trim())){
break;
}
System.out.println(binaryToDecimal(s2));
}
}
private static String decimalToBinary(String s){
int n = Integer.parseInt(s, 10);
StringBuilder sb = new StringBuilder();
if (n==0) return "0";
int d = 0;
while (n > 0){
d = n % 2;
n /= 2;
sb.append(d);
}
sb = sb.reverse();
return sb.toString();
}
private static String binaryToDecimal(String s){
int degree = 1;
int n = 0;
for (int k=s.length()-1; k>=0; k--){
n += degree * (s.charAt(k) - '0');
degree *= 2;
}
return n + "";
}
}
Of course for this method binaryToDecimal you can just do:
private static String binaryToDecimal(String s){
int n = Integer.parseInt(s, 2);
return n + "";
}
but I wanted to illustrate how you can do that explicitly.
do you want this?
private double dec(String s, int i) {
if (s.length() == 1) return s.equals("1") ? Math.pow(2, i) : 0;
else return (s.equals("1") ? Math.pow(2, i) : 0) + dec(s.substring(0, s.length() - 1), i - 1);
}
dec("101011101",0);
This is a version of a binary to decimal converter. I have used plenty of comments also. Just taught I would like to share it. Hope it is of some use to somebody.
import java.util.Scanner;
public class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine(); // store input from user
int[] powers = new int[16]; // contains powers of 2
int powersIndex = 0; // keep track of the index
int decimal = 0; // will contain decimals
boolean isCorrect = true; // flag if incorrect input
// populate the powers array with powers of 2
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
// if 1 add to decimal to calculate
if(binary.charAt(i) == '1')
decimal = decimal + powers[powersIndex]; // calc the decimal
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false; // flag the wrong input
break; // break from loop due to wrong input
} // else if
// keeps track of which power we are on
powersIndex++; // counts from zero up to combat the loop counting down to zero
} // for
if(isCorrect) // print decimal output
System.out.println(binary + " converted to base 10 is: " + decimal);
else // print incorrect input message
System.out.println("Wrong input! It is binary... 0 and 1's like.....!");
} // main
} // BinaryToDecimal
I've written a converter that accepts both strings and ints.
public class Main {
public static void main(String[] args) {
int binInt = 10110111;
String binString = "10110111";
BinaryConverter convertedInt = new BinaryConverter(binInt);
BinaryConverter convertedString = new BinaryConverter(binString);
System.out.println("Binary as an int, to decimal: " + convertedInt.getDecimal());
System.out.println("Binary as a string, to decimal: " + convertedString.getDecimal());
}
}
public class BinaryConverter {
private final int base = 2;
private int binaryInt;
private String binaryString;
private int convertedBinaryInt;
public BinaryConverter(int b) {
binaryInt = b;
convertedBinaryInt = Integer.parseInt(Integer.toString(binaryInt), base);
}
public BinaryConverter(String s) {
binaryString = s;
convertedBinaryInt = Integer.parseInt(binaryString, base);
}
public int getDecimal() {
return convertedBinaryInt;
}
}
public static void main(String[] args)
{
System.out.print("Enter a binary number: ");
Scanner input = new Scanner(System.in);
long num = input.nextLong();
long reverseNum = 0;
int decimal = 0;
int i = 0;
while (num != 0)
{
reverseNum = reverseNum * 10;
reverseNum = num % 10;
decimal = (int) (reverseNum * Math.pow(2, i)) + decimal;
num = num / 10;
i++;
}
System.out.println(decimal);
}
So I am having this strange output in which only the first number is checked twice while the second number is not even considered.Please help.
Code :-
import java.util.Scanner;
public class Amicable
{
private static int a,b;
private static String m,n;
public static void main()
{
acceptNumbers();
if (firstNumber() == secondNumber())
{
System.out.println(a+" and "+b+" are amicable numbers");
}
else System.out.println(a+" and "+b+" are not amicable numbers");
}
public static void acceptNumbers()
{
Scanner sc = new Scanner(System.in);
int count=0;
System.out.print("Enter two numbers [ separated by a ',' ] : ");
String input = sc.nextLine();
System.out.println();
for (int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
if (c == ',')
{
count++;
if (count == 1)
{
m = input.substring(0,i);
n = input.substring(0,i);
}
break;
}
}
if (count == 0)
{
System.out.println("Invalid operation : You have entered only 1 number");
}
m = m.trim(); n = n.trim();
a = Integer.valueOf(m);
b = Integer.valueOf(n);
}
public static int firstNumber()
{
int a1,a2=0;
for (int i = 0; i < m.length()-1; i++)
{
a1 = Integer.valueOf(m.charAt(i));
if (a%a1 == 0) a2 = a2+a1;
}
return a2;
}
public static int secondNumber()
{
int b1,b2=0;
for (int i = 0; i < n.length()-1; i++)
{
b1 = Integer.valueOf(n.charAt(i));
if (b%b1 == 0) b2 = b2+b1;
}
return b2;
}
}
And here is the output :-
Enter 2 numbers [ separated by a ',' ] : 248 , 222
248 and 248 are amicable numbers
your m and n are equal, because you have:
m = input.substring(0,i);
n = input.substring(0,i);
change it to:
m = input.substring(0,i);
n = input.substring(i+1);
Btw you are doing a lot of unnecessary stuff, complete solution (I don't care about exceptions):
import java.util.Scanner;
public class Amicable {
public static void main(String args[]) {
try {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers [ separated by a ',' ] : ");
String input = sc.nextLine();
String[] numbers = input.split(",");
int num1 = Integer.parseInt(numbers[0].trim());
int num2 = Integer.parseInt(numbers[1].trim());
int sum1 = 0, sum2 = 0;
for (int i = 1; i <= num1; i++) {
if (num1 % i == 0)
sum1 += i;
}
for (int i = 1; i <= num2; i++) {
if (num2 % i == 0)
sum2 += i;
}
if (sum1 == sum2)
System.out.println(num1 + " and " + num2
+ " are amicable numbers");
else
System.out.println(num1 + " and " + num2
+ " are not amicable numbers");
} catch (Exception e) {
e.printStackTrace();
}
}
}
parts of code from: http://www.daniweb.com/software-development/java/code/304600/amicable-numbers
a and b are derived from m and n, and the latter are initialized to exactly the same value:
m = input.substring(0,i);
n = input.substring(0,i);
Did you mean to set n to
n = input.substring(i+1);
?
m = input.substring(0,i);
n = input.substring(0,i);
m and n are having the same value.
n should be:
n = input.substring(i+1);
And now the second number will be assigned to n.