Add two strings containing binary numbers - java

I'm teaching myself how to code with java and I use exercises I find in the Internet to practice what I learn.
Anyway, I'm in a middle of an exercise that asks me to build a method that get two strings containing only the characters "0" and "1" from the user and returns one string of them both (binary)combined
example:
BinaryAdder("0","0") - > "0"
BinaryAdder("1","1") - > "10"
BinaryAdder("10100","111") - > "11011"
what I did is:
import java.util.Scanner;
public class assigment03
{
private static String whichIsBigger(String a, String b)
{
if(a.length()>b.length())
return a;
if(a.length()<b.length())
return b;
if(a.length()==b.length())
return a;
else return null;
}
private static String binaryAdder(String a,String b)
{
int[] binaryResult= new int[maxlength(a,b)+1];
String result="";
if(whichIsBigger(a,b)==a)
{
for(int i=0;i<b.length();i++)
{
binaryResult[i]=a.charAt(i)+b.charAt(i);
}
for(int i=b.length();i<a.length();i++)
{
binaryResult[i]+=a.charAt(i);
}
}
else
{
for(int i=0;i<a.length();i++)
{
binaryResult[i]=b.charAt(i)+a.charAt(i);
}
for(int i=a.length();i<b.length();i++)
{
binaryResult[i]+=b.charAt(i);
}
}
for(int i=0;i<binaryResult.length-1;i++)
{
if(binaryResult[i]>=2)
{
binaryResult[i]=binaryResult[i]%2;
binaryResult[i+1]++;
}
}
for(int i=binaryResult.length-1;i>=0;i--)
{
result+=Integer.toString(binaryResult[i]);
}
return result;
}
private static int maxlength(String a, String b)
{
if(a.length()>b.length())
return a.length();
else
return b.length();
}
public static void main(String[] args)
{
Scanner temp= new Scanner(System.in);
System.out.print(binaryAdder(temp.next(),temp.next()));
}
}
But it doesn't return the right result.
Do you mind help me out here?
thanks a lot!

Reading your question, I understood that you might be looking for some help implementing the methods to actually add two binary numbers, and then giving back the result in base two (which btw might be complicated in Java). However, I believe that this exercise lacks of a very important restriction like the what is max length allowed for the binary numbers to be read (overflows can arise while processing the values with primitive data types like int or String). Also this exercise needs some planning when dealing with none significant zeroes like in these cases because "00110b" = "0110b" = "0110b" and when dealing with rolling over the carry of any addition that yields 2 ("10b") or 3 ("11b"). More information on those topics can be found here, in chapter 2.
At least in Java, when tackling these type of exercises, an option is to avoid dealing with such restrictions and conditions. Java provides a class called BigInteger that takes care of huge values, none significant zeroes, and the carries taking away the burden of dealing with those things from the programmers. Java BigInteger also offers a constructor that can initialize their objects in any base. (Well not any, there are some restrictions to this too, please see this link for more information).
With that said, here is my solution to this exercise:
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigInteger;
public class BinaryAdder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> numbers = new ArrayList<String>();
String number = "";
int count = 1;
System.out.print("Instructions:\nPlease enter a set of binary numbers. When you are ready to calculate their addition, enter \"done\",\n\n");
System.out.print("Number " + count + ": ");
while(!(number = scanner.next()).equals("done")){
numbers.add(number);
count++;
System.out.print("Number " + count + ": ");
}
System.out.print("Result = " + binaryAdder(numbers) + "b");
scanner.close();
}
public static String binaryAdder(ArrayList<String> numbers){
BigInteger accumulator = new BigInteger("0");
for(String number: numbers){
accumulator = accumulator.add(new BigInteger(number, 2));
}
return accumulator.toString(2);
}
}
Example:
Instructions: Please enter a set of binary numbers. When you are ready
to calculate their addition, enter "done",
Number 1: 00001
Number 2: 011
Number 3: done
Result = 100b
Between lines 8-11 some variables are declared: a scanner to read the binary numbers entered, an array list to store the binary numbers entered, a string to hold a number once is entered, and a int to keep track of how many numbers have been entered, since I extended this solution to add 0,1,2,3,...,n numbers).
Line 13 prints the instructions of this solution. Line 14 only prints "Number 1: ".
The while loop between lines 16-20 sets the value entered to the variable number and checks if it is equal to "done". Given the case it steps out of the loop, otherwise, it adds the number to the array list.
Line 22 prints the result of the addition of all the binary numbers entered.
But the "magic" really happens between lines 27-35 in the method "binaryAdder" (Note that "binaryAdder" receives that ArrayList holding all the numbers entered as a parameter). At line 28 an accumulator of type BigInteger is initialized to zero to hold the addition of all the numbers in the ArrayList. Then, a for loop travels through all the numbers in the array list to add them to the accumulator. Finally, the accumulated value is returned in base two.

Related

Calling methods within methods, Calling methods with multiple parameters to main. Mixing String and double

I'm struggling with an assignment. I need help figuring out how to call the right methods within each other and eventually in main. My whole code might need work at this point, what am I doing wrong? I've been stuck on this for a week.. (Guidelines at the bottom) Thanks!
import java.util.Scanner;
public class AverageWithMethods {
static Scanner in = new Scanner(System.in);
public static void main(String[]args)
{
userPrompt(); //Can't figure out how I'm supposed to set this up.
}
public static String userPrompt()
{
System.out.println("Enter 5 to 10 numbers separated by spaces, then press enter: ");
String num = in.nextLine();
return num; //I think I'm supposed to call the averager method here somehow?
}
public static double averager(String userPrompt)
{
double nums = Double.parseDouble(userPrompt);
double average = 0;
int counter = 0;
char c = ' ';
for (int i = 0; i < userPrompt.length(); i++)
{
if(userPrompt.charAt(i) == c)
{
counter++;
}
average = nums / counter;
}
return average;
}
public static void result(double average, String userPrompt)
{
System.out.println("The average of the numbers" + userPrompt + "is" + average);
}
}
GUIDELINES:
The program prompts the user for five to ten numbers, all on one line, and separated by spaces. Then the user calculates the average of those numbers, and displays the numbers and their average to the user.
The program uses methods to:
Get the numbers entered by the user Calculate the average of the numbers entered by the user Print the results with the whole number, a decimal, and two decimal positions The first method should take no arguments and return a String of numbers separated by spaces.
The second method should take a String as its only argument and return a double (the average).
The third method should take a String and a double as arguments but have no return value.
For example, if the user input is... 20 40 60 80 100
...the program should give as output... The average of the numbers 20 40 60 80 100 is 60.00.
I will not exactly provide complete solution to your questions but guide you in solving the problem:
User input : 1 2 3 4 5
Thus, now you need to read it in a String which you are already doing in your userPrompt() method.
Post that you need to call your averager() method to get the average
of the numbers. In that averager method you can need to split the
String to get the numbers. Check : String.split() method
documentation on how to achieve that. Then, you need to call
Double.parseDouble() for your String array of numbers.
Finally , you need to make a call to result method in you main()
method.
I hope it helps you on how to approach the problems and has sufficient hints to get the correct solution

No output from program to find all palindrome numbers within a given range

Create a java program to find and print all palindrome numbers within b and a
such that a<3000, b<3000and b<a.
My approach:-
import java.util.*;
class PalinDrome_Within_A_Range_Of_Two_Numbers{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter an upper limit<3000");
int a=sc.nextInt();
System.out.println("Enter a lower limit <3000,upper limit");
int b=sc.nextInt();
int c=0;
int d,e,f,j;
for(int i=b;i<=a;i++){
j=(int)(Math.log10(i) + 1);
e=0;
f=0;
d=i;
for(int k=1;k<=j;k++){
f=i%10;
f=(int)(f*(Math.pow(10,(j-k))));
i=(i-(i%10))/10;
e=e+f;
}
if(e==d){
c=c+1;
System.out.println("The "+c+"th Palindrome number between "+b+" and "+a+" is "+d);
}
else{
break;
}
}
}
}
In this program, nothing appears in the output after giving the two integers.
The reason is that the first number, if it is not a palindrome, will end the loop at the else break; statement. To fix the problem, you should also not manipulate i within its loop, but rather a copy of it.
You may think about debugging. Shows you the point of failure faster than Stackoverflow.
Are you absolutely sour you enter uper limit before entering the lower limit because I by intuition added lower limit first and it did not work any way here is a simpler soultion if you want
public class PalinDrome_Within_A_Range_Of_Two_Numbers {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter an upper limit<3000");
int a=sc.nextInt();
System.out.println("Enter a lower limit <3000,upper limit");
int b=sc.nextInt();
int c=0;
int d,e,f,j;
for(int i=b;i<=a;i++){
String num = String.valueOf(i);
String reversNum = getReversStr(num);
if(num.equals(reversNum)){
System.out.println(num);
}
}
}
private static String getReversStr(String num) {
char[] chars = num.toCharArray();
char[] revers = new char[chars.length];
for(int i = chars.length;i>0;i--)
revers[chars.length-i]=chars[i-1];
return new String(revers);
}
}
Others already suggested to use a debugger. That makes sense because your code is quite complicated. (By the way, you should keep the scope of your variables as small as possible to make your code more readable. It makes no sense to declare and initialize a variable outside a loop when it is used only inside the loop body.)
A better approach would be to simplify your code. You could split it into multiple functions and give each of these a meaningful name.
Or you could use a completely different approach. Being a palindrome is not so much a property of the number itself but of its string representation. So why not base the whole algorithm on strings:
for (int i = b; i <= a; i++) {
String num = String.valueOf(i);
String reverse = new StringBuilder(num).reverse().toString();
if (num.equals(reverse)) {
System.out.println(i);
}
}
I see two issues with your code (no guarantee that they are the only two, but solving them should get you a step further at the least).
You are using i as control variable in your outer loop, and then you are modifying i inside your inner loop (i=(i-(i%10))/10;). Since you are taking a copy of i into d anyway, there is a simple fix: do the modification on d instead of on i.
The break; statement in you else part will break out of the outer loop if the first number tried (b) is not a palindrome. I think you can just delete the else part.
I tried entering 102 as upper limit and 99 as lower. Your program correctly prints The 1th Palindrome number between 99 and 102 is 99, but then because i has been modified goes into an infinite loop. So you are on the way.
I agree with what others have said about breaking your code up in less comlex methods. This will also allow unit testing each method, which will help to locate bugs. Better variable names will help understanding the code, not least when you ask others to take a look. Finally, don’t declare a variable until you need it, this will also help readability.

java, correct number of inputs on one line entry

Forgive me if this has already been asked, but I am trying to fill an array of user defined size, but I want to make sure any extra input is either dumped or triggers an error to reprompt for input. My assignment requires that all input for an array is done on one line, with spaces separating individual values. The program works fine, and seeing how we are still in the beginning of the class I don't think that we are expected to know how to filter the quantity of inputs on a single line, but it is something that still bugs me.
I have searched for some time now for a solution, but everything thing I find is not quite what I am looking for. I thought doing a while(scannerVariable != "\n") would work, but once I thought about it more I realized that wouldn't do anything for my problem since the new line character is only being encountered once per array regardless of the number of inputs. The snippet with the problem is below:
public static double[] getOperand(String prompt, int size)
{
System.out.print(prompt);
double array[];
array = new double[size];
for(int count = 0; count < size; count++)
{
array[count] = input.nextDouble();
}
return array;
}
All I need is some way of validating the number of inputs or dumping/ignoring extra input, so that there is no trash in the buffer to skip input that follows. The only way I can think of is counting the number of spaces and comparing that against the size of the array -1. I don't think that would be reliable though, and I'm not sure how to extract a whitespace character for the count unless I were to have all the input go into a string and parse it. I can post more code or provide more details if needed. As always, thanks for any help!
This can help you. Function that allows the entry of numbers on a line separated by spaces. Valid numbers are stored in a list of type Double.
public static void entersDouble () {
Scanner input = new Scanner(System.in);
String s;
ArrayList<Double> numbers= new ArrayList<>();
System.out.print("Please enter numbers: ");
s=input.nextLine();
String [] strnum = s.split("\\s+");
int j=0;
while(j<strnum.length){
try {
numbers.add(Double.parseDouble(strnum[j++]));
}
catch(Exception exception) {
}
}
for (Double n : numbers)
System.out.println(n);
}
It seems to me that rather than trying to work out the number of inputs up front you would be better off trying to read them one by one and then taking appropriate action if it's too long or too short.
For example
public static double[] getOperands(String prompt, int size) {
double[] operands = new operands[size];
while (true) {
System.out.println(prompt);
Scanner scanner = new Scanner(System.in);+
int operandCount = 0;
while (scanner.hasNextDouble()) {
double val = scanner.nextDouble();
if (operandCount < size)
operands[operandCount++] = val;
}
if (operandCount == size)
return operands;
else
System.out.println("Enter " + size + " decimals separated by spaces.");
}
}

Comparing an array to two static values

So I am just doing something simple. I made a simple Java program where you enter your guess for what the roll will be which is stored in an array and then compared to two numbers generated randomly. So my question is how would I do the comparison of the array against the two number without referencing the exact index (i.e. not array[0]=number[1])? I am doing this mostly to figure out how array work. Also why is the else erroring?
public static void main (String [] args){
java.util.Scanner input = new java.util.Scanner(System.in);
int [] guess= new int [2];
System.out.print("Enter " + guess.length + " values: ");
for (int i=0; i<guess.length;i++)
guess[i] = input.nextInt();
method(guess);
}
public static String method(int [] that){
int number1 = (int)(Math.random() * 6);
int number2 = (int)(Math.random() * 6);
for (int i =0;i<that.length;i++){
if(that[i]==number1 and that[i]+1==number2)
{
return "You got it";
}
else
{
return "try again";
}//end else
} //end for
}//end method
You cannot write and like that , if you want to AND two conditions write &&. Also in your if condition I think you mean to increment your index that[i+1]==number2 , you were incrementing the random number itself. So your if condition would look like:-
if(that[i]==number1 && that[i+1]==number2)
{
return "You got it";
}
else{
..
}
Also want to add that you output You got it or try again will not be visible to user, since you are just calling the method method(guess); from main() which returns a String but does not do anything with returned String. You have to write it like this to make the ouput visible on console.
System.out.println(method(guess));
You can check whether the array contains the element or not like this
Arrays.asList(that).contains(number1)
It will return true if the array contains the element else as false
if you want comparison of the array against the two number without referencing the exact index then the first thing that you can do is use enhance for loop to avoid indexing of array like this
for(int number: that){
// do your comparison while iterating numbers in that(array) as "number"
}

incompatible types error

import javax.swing.JOptionPane;
public class Result
{
public static void main (String[] args)
{
int numa;
int numb;
int sum;
String num1 = JOptionPane.showInputDialog(null,"Enter 1st Number: ");
numa=Integer.parseInt(num1);
String num2 = JOptionPane.showInputDialog(null,"Enter 2nd Number: ");
numb=Integer.parseInt(num2);
{
sum=num1+num2;
}
if (sum>=10)
JOptionPane.showMessageDialog(null,"Congratulations"+sum);
else if(sum<10)
JOptionPane.showMessageDialog(null,"the sum of the number less than 10");
else if(sum>100)
System.exit(7);
}
}
This line:
sum=num1+num2;
is trying to add two strings together and make an int.
Instead, you want:
sum = numa + numb;
In other words, take the values you've just parsed from the strings, and add those together.
Additionally, I'd suggest:
Where possible, declare variables at the point where you first use them (typically assignment)
Don't add braces just for the sake of it (e.g. for this sum line) but...
... do add braces to all if blocks for clarity
Indent all code appropriately (there should never be two braces lining up as per the end of your method)
Unless you really need to use Swing, don't bother - this app would be simpler if it took input from the console and just wrote the answer to the console, instead of showing a message box.
sum = numa + numb
You were trying to add the two strings.
Edit: skeeted again!

Categories