I have a program that prompts the user for a string, an initial base, and a final base. The program works fine for all digits however, when I enter in a string mixed with digits and characters it does not return the correct answer. For example, when I input the string BDRS7OPK48DAC9TDT4, original base: 30, newBase: 36, it should return ILOVEADVANCEDJAVA, but instead I get ILOVEADVANHSC6LTS. I know it's a problem with my algorithm but I cant figure out why it's returning the incorrect conversion.
import java.util.Scanner;
public class BaseConversion {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String theValue;
String result;
String newNum;
int initialBase;
int finalBase;
String[] parts = args;
if (parts.length > 0) {
theValue = parts[0];
isValidInteger(theValue);
initialBase = Integer.parseInt(parts[1]);
finalBase= Integer.parseInt(parts[2]);
isValidBase(finalBase);
}
else {
System.out.println("Please enter a value: ");
theValue = s.nextLine();
isValidInteger(theValue);
System.out.println("Please enter original base: ");
initialBase = s.nextInt();
System.out.println("Please enter new base: ");
finalBase = s.nextInt();
isValidBase(finalBase);
}
// check it
// isValidInteger(theValue, finalBase);
s.close();
newNum = convertInteger(theValue, initialBase, finalBase);
System.out.println("new number: " + newNum);
}
public static void isValidBase(int finalBase) {
if (finalBase < 2 || finalBase > 36) {
System.out.println("Error: Base must be greater than or equal to 2 & less than or equal to 36");
System.exit(1);
}
}
public static void isValidInteger(String num) {
char chDigit;
num = num.toUpperCase();
for(int d = 0; d < num.length(); d++) {
chDigit = num.charAt(d);
if (!Character.isLetter(chDigit) && !Character.isDigit(chDigit)) {
//System.out.println(chDigit);
System.out.println("Error character is not a letter or number");
System.exit(1);
}
}
}
public static String convertInteger(String theValue, int initialBase, int finalBase) {
double val = 0;
double decDigit = 0;
char chDigit;
// loop through each digit of the original number
int L = theValue.length();
for(int p = 0; p < L; p++) {
// get the digit character (0-9, A-Z)
chDigit = Character.toUpperCase(theValue.charAt(L-1-p));
// get the decimal value of our character
if(Character.isLetter(chDigit)) {
decDigit = chDigit - 'A' + 10;
}
else if (Character.isDigit(chDigit)) {
decDigit = chDigit - '0';
}
else {
System.out.println("Error d");
System.exit(1);
}
// add value to total
val += decDigit * Math.pow(initialBase, p);
}
// determine number of digits in new base
int D = 1;
for( ; Math.pow(finalBase, D) <= val; D++) {}
// use char array to hold new digits
char[] newNum = new char[D];
double pwr;
for(int p = D-1; p >= 0; p--) {
// calculate the digit for this power of newBase
pwr = Math.pow(finalBase, p);
decDigit = Math.floor(val / pwr);
val -= decDigit*pwr;
// store the digit character
if(decDigit <= 9) {
newNum[D - 1 - p] = (char) ('0' + (int)decDigit);
}
else {
newNum[D - 1 - p] = (char) ('A' + (int)(decDigit - 10));
}
}
return new String(newNum);
}
}
The algorithm is correct. Take a closer look instead at the place where you convert the input value to a decimal system and in particular at the limitations of the data type you are using.
Resources that could be helpful:
primitive data types - double point in the list
Floating point arithmetic
Question concerning similar problem
JLS - 4.2.3. Floating-Point Types, Formats, and Values
Hope this points you to the right track.
import java.math.BigInteger;
import java.util.Scanner;
public class BaseConversion {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String theValue;
String result;
String newNum;
int initialBase;
int finalBase;
String[] parts = args;
if (parts.length > 0) {
theValue = parts[0];
isValidInteger(theValue);
initialBase = Integer.parseInt(parts[1]);
finalBase= Integer.parseInt(parts[2]);
isValidBase(finalBase);
}
else {
System.out.println("Please enter a value: ");
theValue = s.nextLine();
isValidInteger(theValue);
System.out.println("Please enter original base: ");
initialBase = s.nextInt();
System.out.println("Please enter new base: ");
finalBase = s.nextInt();
isValidBase(finalBase);
}
// check it
// isValidInteger(theValue, finalBase);
s.close();
newNum = convertInteger(theValue, initialBase, finalBase);
System.out.println("new number: " + newNum);
}
public static void isValidBase(int finalBase) {
if (finalBase < 2 || finalBase > 36) {
System.out.println("Error: Base must be greater than or equal to 2 & less than or equal to 36");
System.exit(1);
}
}
public static void isValidInteger(String num) {
char chDigit;
num = num.toUpperCase();
for(int d = 0; d < num.length(); d++) {
chDigit = num.charAt(d);
if (!Character.isLetter(chDigit) && !Character.isDigit(chDigit)) {
//System.out.println(chDigit);
System.out.println("Error character is not a letter or number");
System.exit(1);
}
}
}
public static String convertInteger(String theValue, int initialBase, int finalBase) {
BigInteger bigInteger = new BigInteger(theValue,initialBase);
String value = bigInteger.toString(finalBase);
value = value.toUpperCase();
return value;
}
}
Here is the correct solution. The problem was with the data type not the algorithm. I hope this helps anyone dealing with the same type of problem.
Related
Though the problem seemed simple, here it is :-
A Kaprekar number is a positive whole number n with d digits, such that when we split its square into two pieces - a right hand piece r with d digits and a left hand piece l that contains the remaining d or d−1 digits, the sum of the pieces is equal to the original number (i.e. l + r = n).
The Task
You are given the two positive integers p and q, where p is lower than q. Write a program to determine how many Kaprekar numbers are there in the range between p and q (both inclusive) and display them all.
Input Format
There will be two lines of input: p, lowest value q, highest value
Constraints:
0<p<q<100000
Output Format
Output each Kaprekar number in the given range, space-separated on a single line. If no Kaprekar numbers exist in the given range, print INVALID RANGE.
I could not clear the test cases in the range
22223
99999
In the above range the follwoing numbers should have been generated :-
77778 82656 95121 99999
Here is my code :-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int p = scan.nextInt();
int q = scan.nextInt();
boolean exist = false;
if(q <= p){
System.out.println("INVALID RANGE");
}
int m = 0,n = 0;
long sqr = 0;
String numb = "";
String[] digits = new String[2];
for(int i = p; i <= q; i++){
if(i == 1)System.out.print(1 + " ");
else{
sqr = i*i;
numb = String.valueOf(sqr);// Changing it into a string.
if(numb.length() % 2 == 0){
digits[0] = numb.substring(0, numb.length()/2);//Splitting it into two parts
digits[1] = numb.substring(numb.length()/2);
}else{
digits[0] = numb.substring(0, (numb.length() - 1)/2);
digits[1] = numb.substring((numb.length() -1)/2);
}
if(digits[0] == "" )
m = 0;
if(digits[1] == "")
n = 0;
if(!digits[1].equals("") && !digits[0].equals("")){
m = Integer.parseInt(digits[0]);
n = Integer.parseInt(digits[1]);
}
if(i == (m + n) ){ //Testing for equality
System.out.print(i + " ");
exist = true;
}
}
}
if(exist == false){// If exist is never modified print Invalid Range.
System.out.println("INVALID RANGE");
}
}
}
import java.util.*;
public class Kaprekar
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int num=sc.nextInt();
int sq=num*num; String sq1=Integer.toString(sq);
int mid=(Integer.toString(sq).length())/2;
int rem=sq%((int)Math.pow(10,sq1.length()-mid));
int quo=sq/((int)Math.pow(10,sq1.length()-mid));
int sum=rem+quo;
if(sum==num)
{System.out.println("Kaprekar");}else{System.out.println("Not Kaprecar");}
}
}
Changing the type of Loop index i from int to long fixed the problem.
The square computation of i*i was overflowing the upper limit of int so by changing it to long we were able to get the required computation done.
Thanks to Rup for pointing this out.
The code which cleared all the test cases is here :-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int p = scan.nextInt();
int q = scan.nextInt();
boolean exist = false;
if(q <= p){
System.out.println("INVALID RANGE");
return;
}
int m = 0,n = 0;
long sqr = 0;
String numb = "";
String[] digits = new String[2];
for(long i = p; i <= q; i++){
if(i == 1)System.out.print(1 + " ");
else{
sqr = i*i;
numb = String.valueOf(sqr);
if(numb.length() % 2 == 0){
digits[0] = numb.substring(0, numb.length()/2);
digits[1] = numb.substring(numb.length()/2);
}else{
digits[0] = numb.substring(0, (numb.length() - 1)/2);
digits[1] = numb.substring((numb.length() -1)/2);
}
if(digits[0] == "" )
m = 0;
if(digits[1] == "")
n = 0;
if(!digits[1].equals("") && !digits[0].equals("")){
m = Integer.parseInt(digits[0]);
n = Integer.parseInt(digits[1]);
}
if(i == (m + n) ){
System.out.print(i + " ");
exist = true;
}
}
}
if(exist == false){
System.out.println("INVALID RANGE");
}
}
}
import java.io.*;
import java.math.*;
import java.util.*;
class Kaprekar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int p = scanner.nextInt();
int q = scanner.nextInt();
long i,n,s,a,c,k,d,e=0;
for(i=p;i<=q;i++)
{
k=i;d=0;
while(k!=0)
{
d++;
k=k/10;
}
c=0;s=0;n=i*i;
while(n!=0)
{
a=n%10;
n=n/10;
s=s+ (int)Math.pow(10,c)*a;
c++;
if(n+s==i&&(c==d||c==d-1)&&s!=0)
{
System.out.print(i+" ");
e++; break;
}
}
}
if(e==0)
{
System.out.println("INVALID RANGE");
}
scanner.close();
}
}
I'm doing an assignment where the goal is to, among other things, to add two large integers. Here is my code, spread out into four files.
Main that we cannot change:
import java.util.*;
import MyUtils.MyUtil;
public class CSCD210HW7
{
public static void main(String [] args)throws Exception
{
int choice;
String num;
LargeInt one, two, three = null;
Scanner kb = new Scanner(System.in);
num = HW7Methods.readNum(kb);
one = new LargeInt(num);
num = HW7Methods.readNum(kb);
two = new LargeInt(num);
do
{
choice = MyUtil.menu(kb);
switch(choice)
{
case 1: System.out.println(one + "\n");
break;
case 2: System.out.println("The value of the LargeInt is: " + two.getValue() + "\n");
break;
case 3: num = HW7Methods.readNum(kb);
one.setValue(num);
break;
case 4: if(one.equals(two))
System.out.println("The LargeInts are equal");
else
System.out.println("The LargeInts are NOT equal");
break;
case 5: three = two.add(one);
System.out.printf("The results of %s added to %s is %s\n", one.getValue(), two.getValue(), three.getValue());
break;
case 6: HW7Methods.displayAscendingOrder(one, two, three);
break;
default: if(two.compareTo(one) < 0)
System.out.printf("LargeInt %s is less than LargeInt %s\n", two.getValue(), one.getValue());
else if(two.compareTo(one) > 0)
System.out.printf("LargeInt %s is greater than LargeInt %s\n", two.getValue(), one.getValue());
else
System.out.printf("LargeInt %s is equal to LargeInt %s\n", two.getValue(), one.getValue());
break;
}// end switch
}while(choice != 8);
}// end main
}// end class
LargeInt Class(Custom Class We Created)
public class LargeInt implements Comparable<LargeInt>
{
private int[]myArray;
private LargeInt()
{
this("0");
}
public LargeInt(final String str)
{
this.myArray = new int[str.length()];
for(int x = 0; x < this.myArray.length; x++)
{
this.myArray[x] = Integer.parseInt(str.charAt(x)+ "");
}
}
public LargeInt add(final LargeInt passedIn)
{
String stringOne = myArray.toString();
String stringTwo = passedIn.myArray.toString();
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
return new LargeInt(""+s);
}
public void setValue(final String arrayString)
{
this.myArray = new int[arrayString.length()];
for(int x = 0; x < myArray.length; x++)
{
this.myArray[x]=arrayString.charAt(x);
}
}
#Override
public int compareTo(LargeInt passedIn)
{
if(passedIn == null)
{
throw new RuntimeException("NullExceptionError");
}
int ewu = 0;
int avs = 0;
if(this.myArray.length != passedIn.myArray.length)
{
return this.myArray.length - passedIn.myArray.length;
}
for(int i = 0; i < this.myArray.length -1; i++)
{
if(this.myArray[i] != passedIn.myArray[i])
{
return this.myArray[i]-passedIn.myArray[i];
}
}
return ewu-avs;
}
public int hashCode()
{
String p = "";
for(int f = 0; f < this.myArray.length; f++)
{
p += myArray[f];
}
return p.hashCode();
}
public String getValue()
{
String h = "";
for(int t = 0; t < this.myArray.length; t++)
{
h += myArray[t];
}
return h;
}
#Override
public boolean equals(Object jbo)
{
if(jbo == null)
{
return false;
}
if(!(jbo instanceof LargeInt))
{
return false;
}
LargeInt k =(LargeInt)jbo;
if(k.myArray.length != this.myArray.length)
{
return false;
}
for(int d = 0; d < this.myArray.length; d++)
{
if(k.myArray[d] != myArray[d])
{
return false;
}
}
return true;
}
#Override
public String toString()
{
String c = "";
for(int q = 0; q < this.myArray.length; q++)
{
c += myArray[q];
}
return "The LargeInt is: " + c;
}
}
HW7Methods File
import java.util.*;
import java.io.*;
public class HW7Methods
{
public static String readNum(Scanner kb)
{
String num = "";
System.out.print("Enter Your Large Int: ");
num = kb.nextLine();
return num;
}
public static void displayAscendingOrder(final LargeInt first, final LargeInt second, final LargeInt third)
{
String highestInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) >= 0)
{
highestInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) >= 0)
{
highestInt = second.getValue();
}
else
{
highestInt = third.getValue();
}
String middleInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) <= 0)
{
middleInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) <= 0)
{
middleInt = second.getValue();
}
else
{
middleInt = third.getValue();
}
String lowestInt;
if(first.compareTo(second) <= 0 && first.compareTo(third) <= 0)
{
lowestInt = first.getValue();
}
else if(second.compareTo(first) <= 0 && second.compareTo(third) <= 0)
{
lowestInt = second.getValue();
}
else
{
lowestInt = third.getValue();
}
System.out.println("The LargeInts in order are: " + lowestInt + ", " + middleInt + ", " + highestInt);
}
}
MyUtil file
package MyUtils;
import java.io.*;
import java.util.Scanner;
public class MyUtil
{
public static int menu(Scanner kb)
{
int userChoice;
System.out.println("1) Print First Int");
System.out.println("2) Print Second Int");
System.out.println("3) Add Different Int");
System.out.println("4) Check If Equal");
System.out.println("5) Add Large Ints");
System.out.println("6) Display In Ascending Order");
System.out.println("7) Compare Ints");
System.out.println("8) Quit");
kb = new Scanner(System.in);
System.out.print("Please Select Your Choice: ");
userChoice = kb.nextInt();
while(userChoice < 1 || userChoice > 8)
{
System.out.print("Invalid Menu Choice. Please Re-Enter: ");
userChoice = kb.nextInt();
}
return userChoice;
}
}
When I go to run this code, it prompts me for two Large Integers like it's supposed to. However, when I choose option 5 to add them, this is what I get:
Exception in thread "main" java.lang.NumberFormatException: For input string: "[I#55f96302"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at LargeInt.add(LargeInt.java:24)
at CSCD210HW7.main(CSCD210HW7.java:41)
I've never seen that type of error before. Can someone tell me what is going on?
For input string: "[I#55f96302
That is not a "proper" String you are trying to parse here.
This is what an int[] looks like when you call toString() on it.
String stringOne = myArray.toString();
Why do you do that? What is that supposed to do?
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
From the looks of it, you try to handle "large" ints with your LargeInt class by somehow storing them in an array of ints. That's okay, BigInteger also works like that (more or less), but you cannot just do calculations by trying to convert back to int (after all those numbers are too big for int arithmetic to handle, even if you do the string parsing properly).
So I have to read a sequence of numbers from the console ( 1 to 50 numbers), none of which are equal and print out the numbers for which is true that a|b == c|d (example: 5|32 == 53|2), but I get an NubmferFormatException each time. Why?
import java.util.Scanner;
public class StuckNumbers {
public static void main(String[] args) {
// create Scanner
Scanner input = new Scanner(System.in);
// input count and declare array
System.out.println("input number of numbers");
int count = input.nextInt();
int[] numbers = new int[count];
// check if count is between 1 and 50
if (count < 1 && count > 50) {
System.out.println("Wrong input. Input a number between 1 and 50");
count = input.nextInt();
}
// input n numbers
for (int i : numbers) {
i = input.nextInt();
// check if i = j
for (int j : numbers) {
if (i == j) {
System.out
.println("All numbers must be dist75inct. Try again.");
i = input.nextInt();
}
}
}
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
if (stuckNumbers(numbers[i], numbers[j]) == stuckNumbers(
numbers[j], numbers[i])) {
System.out.println(i + "|" + j + " == " + j + "|" + i);
}
}
}
input.close();
}
public static int stuckNumbers(int a, int b) {
String firstNum = "a";
String secondNum = "b";
String res = "ab";
int result = Integer.parseInt(res);
return result;
}
}
Look at these lines:
String res = "ab";
int result = Integer.parseInt(res);
"ab" is not a number, so you're going to get a NumberFormatException when you try to parse it as an integer.
Change the firstNum and SecondNum variables from "a" and "b" to Integer.toString(a); OR String.valueOf(a); and similar for b.
public static int stuckNumbers(int a, int b) {
String firstNum = String.valueOf(a);
String secondNum = String.valueOf(b);
String res = "";
res.concat(firstNum);
res.concat(secondNum);
int result = Integer.parseInt(res);
return result;
}
I hope this will remove any Exception being thrown.
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.