Add binary values with points without shortcut [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have got a school project to add 2 binary numbers in java. The binary numbers can also have decimal values.
Example - 10.01 + 10.01 = 100.1
I cannot use short cuts like Integer.parseInt(str,radix); (These projects really suck)... :'(
I just have to use strings and stuff. I tried the following code but I am getting lost in the mid and especially to overcome the decimal factor is becoming next to impossible for me:-
String a = "101";
String b = "101";
for(int i=0;i<a.length() || i<b.length();i++){
int digit1 = Integer.parseInt(a.substring(a.length()-1));
int digit2 = Integer.parseInt(b.substring(b.length()-1));
if(digit1 == 0 && digit2 ==0 && carry == 0) {sum = 0;carry = 0;}
if(digit1 == 0 && digit2 ==1 && carry == 0) {sum = 1;carry = 0;}
if(digit1 == 1 && digit2 ==0 && carry == 0) {sum = 1;carry = 0;}
if(digit1 == 1 && digit2 ==1 && carry == 0) {sum = 0;carry = 1;}
if(digit1 == 0 && digit2 ==0 && carry == 1) {sum = 1;carry = 0;}
if(digit1 == 0 && digit2 ==1 && carry == 1) {sum = 0;carry = 1;}
if(digit1 == 1 && digit2 ==0 && carry == 1) {sum = 0;carry = 1;}
if(digit1 == 1 && digit2 ==1 && carry == 1) {sum = 1;carry = 1;}
...//could not continue further
Please help me...I am stuck very badly. Any help will be gladly appreciated! :)

This is the working code:
Note: I have just shown you how to add thses numbers. IF your 1st binary number has (say) 4 digits and 2nd binary number has (say) 10 digits then obviously this code won't work!you have to check that condition and add respective code.I have assumed that both numbers have same digits.
Also note the change in for loop conditions!
public class ADDBinary {
public static void main(String[] args) {
// TODO Auto-generated method stub
String num1 = "1101";
String num2 = "1010";
String sum = "";
int carry = 0;
for (int i = 0; i < num1.length() && i < num2.length(); i++) {
System.out.println("In for loop");
char digit1, digit2;
digit1 = num1.charAt(num1.length() - i - 1);
digit2 = num2.charAt(num2.length() - i - 1);
System.out.println("Digits="+digit1+digit2);
if (digit1 == '0' && digit2 == '0' && carry == 0) {
sum = sum + "0";
carry = 0;
} else if (digit1 == '0' && digit2 == '1' && carry == 0) {
sum = sum + "1";
carry = 0;
} else if (digit1 == '1' && digit2 == '0' && carry == 0) {
sum = sum + "1";
carry = 0;
} else if (digit1 == '1' && digit2 == '1' && carry == 0) {
sum = sum + "0";
carry = 1;
} else if (digit1 == '0' && digit2 == '0' && carry == 1) {
sum = sum + "1";
carry = 0;
} else if (digit1 == '0' && digit2 == '1' && carry == 1) {
sum = sum + "0";
carry = 1;
} else if (digit1 == '1' && digit2 == '0' && carry == 1) {
sum = sum + "0";
carry = 1;
} else if (digit1 == '1' && digit2 == '1' && carry == 1) {
sum = sum + "1";
carry = 1;
}
}
if(carry == 1)
sum = sum + "1";
System.out.println(new StringBuilder(sum).reverse().toString());
}
}
I have used same conditions!

First of all, some tips.
Looking at your code, I can see eight if's with the same format. This is called code duplication and it is to be avoided. You are basically typing the same lines over and over again, which is more work for you and makes your code less readable, adaptable and maintanable. If you encounter something that needs to be done multiple times, in slightly different ways, make a new method that does that thing.
You say they can have decimal values. That's not really good terminology, decimal implies base10. Radix point is what we call the decimal point in base10, but since we're working with base2, decimal doesn't apply, so we call it radix point instead.
As for your question:
(Deleted this because NullPointer beat me to it.)

Related

How to convert for loop into streams?

How would I use streams to achieve the same result as below? I am trying to find the average of this 'tot' value by first iterating through TickQueue (a queue implementation) and summing tot, and then afterwards dividing by the counter value to find the average.
int counter = 0;
double tot = 0;
for (Tick t: TickQueue)
{
if ((t.getAskPrice() == 0 && t.getBidPrice() == 0) || (t.getAskPrice() == 0) || (t.getBidPrice() == 0))
{
tot += 0;
}
else
{
tot += (t.getAskPrice() - t.getBidPrice());
counter++;
}
}
double avg = tot/counter;
Use a DoubleStream for sum/average/count:
double avg = tickQueue.stream()
.filter(t -> t.getAskPrice() != 0 && t.getBidPrice() != 0)
.mapToDouble(t -> t.getAskPrice() - t.getBidPrice())
.average()
.orElse(0.0);
TickQueue.stream().
filter(t -> !((t.getAskPrice() == 0 && t.getBidPrice() == 0) || (t.getAskPrice() == 0) || (t.getBidPrice() == 0)).
forEach(t -> {
tot += (t.getAskPrice() - t.getBidPrice());
counter++;
});
You first filter out the values where ((t.getAskPrice() == 0 && t.getBidPrice() == 0) || (t.getAskPrice() == 0) || (t.getBidPrice() == 0)), and then for the remaining values calculate tot and counter.

I'm facing an issue with control structures

My problem is with output of my code. When I enter 20, the output must be weird, but I am getting not weird. Same with the value 18.
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 2 && n >= 5){
ans="Not weird";
} else if(n <= 6 && n >= 20){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}
the output must be weird,but i am getting not weird
Because, if(n%2 == 1) return false and fall to else block where
if(n <= 2 && n >= 5) is `false`
and
else if(n <= 6 && n >= 20) is also `false`
So, again falls to else block. You probably change
if(n <= 2 && n >= 5)
to
if(n >= 2 && n <= 5)
and
else if(n <= 6 && n >= 20)
to
else if(n >= 6 && n <= 20)
Otherwise, they will never be true and always falls to else.
In your program last else is being executed. Change && (logical AND) to || (logical OR) which will check if number is less than something OR higher than something, instead of checking if something is less or equal 5 AND higher or equal to 20 in the same time as it doesn't have a possibility to evaluate in any case.
I have come up with two solutions and also i see a flaw:
1. if(n%2 == 1) this code can be altered to if(n%2 == 0)
2. The flaw is **(n <= 2 && n >= 5)** . No number can be <2 and >5 at the same time. Try changing that to (n <= 2 || n >= 5) and same goes for (n <= 6 && n >= 20)
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 6 || n >= 20){
ans="Not weird";
} else if(n <= 2 || n >= 5){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}

JOptionPane error-- Tortoise and Hair race

I am new to my Intro to Java course and am struggling with a program. I have posted about this program before but this is a different question. My program is supposed to model a race between a hare and a tortoise. I think I have everything I need but I am having trouble with my JOptionPane phrase. I think my phrase is Ok, but I am experiencing problems with the while portion of my statement. Here is the error message: cannot find symbol - Variable OK.
I use Blue J to write and compile my program. Is there any reason why its not working? I thought the variable OK was the thing that the program user chooses to start the program. Am I mistaken? Can anyone help with this problem? Is there anything else you see in my program that needs fixing? Thanks
import java.util.Random;
import javax.swing.JOptionPane;
class Race
{
int [] race = new int[70];
int tortoise;
int hare;
Random randomGenerator = new Random();
public boolean again = true;
public void StartRace()
{
tortoise = 1;
hare = 1;
System.out.println("AND THEY'RE OFF!!!!");
while (tortoise < race.length && hare < race.length)
{
moveHare();
moveTortoise();
DisplayCurrentLocation();
String request;
}
if
(tortoise > hare)
{
System.out.println("\n TORTOISE WINS!!");
}
else if
(hare > tortoise)
{
System.out.println("\n HARE WINS!!!");
}
else if
(hare == tortoise)
{
System.out.println("TIE!!!");
}
}
public void moveTortoise()
{
int n = randomGenerator.nextInt(10) + 1;
//fast plod
if ( n > 0 && n< 6)
tortoise += 3;
//slip
else if (n > 10 && n< 11)
tortoise -= 6;
//slow plod
else if (n > 6 && n< 9)
++tortoise;
// protect from going past start
if (tortoise < 1)
tortoise = 1;
// to make sure game ends
else if (tortoise > 70)
tortoise = 70;
}// end tortoise
public void moveHare()
{
int m = randomGenerator.nextInt(10) + 1;
//big hop
if (m > 0 && m<3)
hare += 9;
//big slip
else if (m < 6)
hare -= 12;
// small hop
else if (m > 3 && m< 5)
++hare;
// )small slip
else if (m < 9)
hare -= 2;
else if (m < 11)
hare += 0;
//ensure hare doesn't go past start
if (hare < 1)
hare = 1;
// ensure hare doesnt go past end
else if (hare > 70)
hare = 70;
} // end movehare
public void DisplayCurrentLocation()
{
//this is the location of each on the array
for (int count = 1; count <= 70; count++)
// when at same location
if (count ==tortoise && count ==hare)
{
System.out.println("OUCH");
}
else if (count == hare)
{
System.out.println("H");
}
else if (count == tortoise)
{
System.out.println("T");
}
else
System.out.println();
}
public static void main ( String[] args)
{
Race Application = new Race();
int startRaceRequest;
while(startRaceRequest != JOptionPane.OK_OPTION)
{
JOptionPane.showConfirmDialog(null, "Select OK To Begin the Race!:");
}
do
{
Application.StartRace();
} while(startRaceRequest != JOptionPane.OK_OPTION);
}
}
To your question with the JOptionPane: I suggest you to use
JOptionPane.showConfirmDialog(null, "Message");
instead of
JOptionPane.showMessageDialog(null, "Message");
because it allows you to do this:
int startRaceRequest;
while(startRaceRequest != JOptionPane.OK_OPTION)
JOptionPane.showConfirmDialog(null, "Hit OK to start the race!");
I don't really understand what you mean by "Ok" later on in your code, but if you refer to the confirmed dialog, try using JOptionPane.OK_OPTION wich represents an int.
Also some help with your code: At the beginning you initialize the int[] race with the length of 70. Whenever you check if one of the racers is at or above 70, you do it like this
if(tortoise < 70 && hare < 70){}
wich is called hard-coding and you should try to avoid that as much as possible, to keep your code as dynamic as possible.
If you do this
if(tortoise < race.length && hare < race.length)
you don't have to rewrite half your code just because you changed the length of the race.
Another thing to the methods MoveTortoise and MoveHare. Conventionally the should be named moveTortoise and moveHare because method ins Java begin with lower case (that goes for all your methods!). Within those two methods inside your if conditions you write way too much code. for example this:
if (m == 1 || m == 2)
hare += 9;
else if (m == 6)
hare -= 12;
else if (m == 3 && m == 5) //there is something wrong here, m cant be 5 and 3 ;)
++hare;
else if (m == 7 || m == 8)
hare -= 2;
else if (m == 9 || m == 10)
hare += 0;
could be cut to this:
if(m > 0 && m < 3){ // if a number is > 0 and < 3 -> number is 1 or 2
} else if(m < 6){ // if a number is > 0 and > 3 -> if number is < 6 -> number could be 3, 4 or 5
} else if(m == 6){
} else if(m < 9){ // -> 7 or 8
} else if(m < 11){ // 9 or 10
}
In Addition, you use a random number generator and I think you are aiming for a number between 1 to 10, however this
int m = randomGenerator.nextInt(11);
will return a number from 0 to 10. Instead, try this:
int m = randomGenerator.nextInt(10) + 1;
wich will return a number from 0 to 9, adding one will result in a number between 1 and 10.
Hope this helps. Please remember to give feedback and mark a solution if your question was answered.

How can I get this program to print out ten items per line seperated by 1 space?

Here's my code so far
public class DivisibleBy5and6
{
public static void main (String []args)
{
for (int i = 100; i <= 200; i++)
{
boolean num = (i % 5 == 0 || i % 6 == 0) && !(i % 5 == 0 && i % 6 == 0);
if (num == true)
System.out.println(i + " is divisible");
}
}
}
Like stated previously how can I get the output to print out 10 items per line separated by a space?
How about:
int count = 0;
for (int i = 100; i <= 200; i++) {
boolean num = (i % 5 == 0 || i % 6 == 0) && !(i % 5 == 0 && i % 6 == 0);
if (num == true) {
count++;
System.out.print(i + " is divisible ");
if(count >= 10) {
System.out.println();
count -= 10;
}
}
}

Why isn't my FizzBuzz code processing both if statements when they both match? [duplicate]

This question already has answers here:
Conditional statement true in both parts of if-else-if ladder
(4 answers)
Closed 2 years ago.
For those who don't know, FizzBuzz is the following problem:
Write a program that prints the numbers from 1 to 100. But for
multiples of three print "Fizz" instead of the number and for the
multiples of five print "Buzz". For numbers which are multiples of
both three and five print "FizzBuzz".
Every FizzBuzz solution I find is either some crazy esoteric solution made for the sake of being original, or your basic if-else chain:
for(int i = 1; i <= 100; i++) {
if(i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
I am looking for a simple solution that aims to take out the "FizzBuzz" if statement. I have this in mind:
for(int i = 1; i <= 100; i++) {
if (i % 3 == 0)
System.out.print("Fizz");
if (i % 5 == 0)
System.out.println("Buzz")
else
System.out.println(i);
}
But this doesn't work. I assume it would be able to print FizzBuzz by entering both ifs, for Fizz and for Buzz, but if the number is, for example, 3, it would print Fizz3. How do I avoid this?
What you're trying to do is
if (a)
...
if (b)
...
else // if neigther a nor b
...
This is simply not possible. An else can only belong to a single if. You have to go with the slightly longer variant.
To avoid doing redundant evaluations of the modulo operator, you could formulate the loop body as
boolean fizz = i % 3 == 0;
boolean buzz = i % 5 == 0;
if (fizz)
System.out.print("Fizz");
if (buzz)
System.out.print("Buzz");
if (!(fizz || buzz))
System.out.print(i);
System.out.println();
Another one would be
String result = "";
if (i % 3 == 0) result = "Fizz";
if (i % 5 == 0) result += "Buzz";
if (result == "") result += i;
System.out.println(result);
Your first if statement is all alone.
So, your code hits the first statement, which is ONLY an if statement, and then goes on to the next, which is an if/else statement.
RosettaCode has a good example without using AND operators.
int i;
for (i = 0; i <= 100; i++) {
if ((i % 15) == 0)
cout << "FizzBuzz" << endl;
else if ((i % 3) == 0)
cout << "Fizz" << endl;
else if ((i % 5) == 0)
cout << "Buzz" << endl;
else
cout << i << endl;
}
If your only goal is to avoid using &&, you could use a double negation and DeMorgan's laws:
for(int i = 1; i <= 100; i++) {
if(!(i % 3 != 0 || i % 5 != 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
You can avoid && using the fact that i % 3 == 0 and i % 5 == 0 implies i % 15 == 0, as per RFC1337's answer.
Another solution is to use a switch on the remainder (mod 15, which is 5 times 3):
for(int i = 1; i <= 100; i++) {
final int mod = i % 15;
switch (mod) {
case 0:
case 3:
case 6:
case 9:
case 12:
System.out.print("Fizz");
if (mod != 0) break;
case 5:
case 10:
System.out.print("Buzz");
break;
default:
System.out.print(i);
}
System.out.println();
}
This is my solution. Granted, it's a bit convoluted (as in roundabout), but I believe it suits your requirement.
int main()
{
char fizzpass=0;
unsigned short index=0;
for(index=1;index<=100;index++)
{
if(0 == (index%3))
{
printf("Fizz");
fizzpass = 1;
}
if(0 == (index%5))
{
if(1 == fizzpass)
{
fizzpass = 0;
}
printf("Buzz\n");
continue;
}
if(1 == fizzpass)
{
fizzpass = 0;
printf("\n");
continue;
}
printf("%d\n",index);
}
return 0;
}
Regards.
Just add a flag variable and use System.out.print:
package com.stackoverflow;
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
boolean printed = false;
if (i % 3 == 0) {
printed = true;
System.out.print("Fizz");
}
if (i % 5 == 0) {
printed = true;
System.out.print("Buzz");
}
if (printed) {
System.out.println();
} else {
System.out.println(i);
}
}
}
}
This doesn't take out the if statements but does not use the && (and) operator, you could flip the binary operators.
//FizzBuzz Case
if(!(a % 3 != 0 || a % 5 != 0)){ //flips
result[index] = "FizzBuzz";
index++;
}
Don't use an if statement at all.
import java.util.*;
import java.lang.*;
import java.io.*;
class FizzBuzz
{
public static void main (String[] args) throws java.lang.Exception
{
String[] words = {"", "Fizz", "Buzz"};
String[] nwords = {"", ""};
for(int i = 1; i < 101; ++i)
{
int fp = (i % 3 == 0) ? 1 : 0;
int bp = ((i % 5 == 0) ? 1 : 0) * 2;
int np = ((fp > 0 || bp > 0) ? 1: 0);
nwords[0] = Integer.toString(i);
System.out.print(words[fp]);
System.out.print(words[bp]);
System.out.println(nwords[np]);
}
}
}
See it on ideone.
public class fizzbuzz
{
public static void main(String[] args)
{
String result;
for(int i=1; i<=100;i++)
{
result=" ";
if(i%3==0)
{
result=result+"Fizz";
}
if(i%5==0)
{
result=result+"Buzz";
}
if (result==" ")
{
result=result+i;
}
System.out.println(result);
}
}
}
This is the most efficient way I could come up with. Hope it helps! :)
Crazy albeit unrelated solution done in Python3
#!/usr/bin/python3
for i in range(1,100):
msg = "Fizz" * bool(i%3==0)
msg += "Buzz" * bool(i%5==0)
if not msg:
msg = i
print(msg)

Categories