Self-Made BCD Class - Multiplying BCDs Error - multiplication

I am making a BCD class as an exercise for school, and am encountering some issues. Below is my BCD class.
My problem is with the multiplyBCDs method.
It works fine with smaller numbers such as 4,329 * 4, however, with larger products, such as the product of 4,329 and 29,385, I receive a NullPointerException error at the first line of my addBCDs method:
int[] added = new int[other.numberOfDigits()];
I have tried retracing the problem and could not find the issue. Why am I receiving this error and how could I fix it?
Thanks for the help!

In the method:
public BCD multiplyBy(int num)
In the last else statement, the following condition is never met:
if (x == digits.length - 1 && carry != 0)
and so "ans" is never set and remains null.

int[] added = new int[other.numberOfDigits()];
The only way you can get an NPE on that line is if other is null.

Related

Pine throws syntax error on first line of for loop

I have a pine strategy:
//#version=5
strategy("Elie's strategy", overlay=true, margin_long=100, margin_short=100)
var float[] overSRLs = na
var IDCounter = 0
int[] removeFromOver = na
for int i = 0 to (array.size(overSRLs) - 1) // line 8
if low < array.get(overSRLs, i)
orderID = str.tostring(IDCounter)
exitID = str.tostring(IDCounter + 1)
IDCounter += 2
strategy.order(orderID, strategy.long, 1)
strategy.exit(exitID, from_entry=orderID, stop = (array.get(overSRLs, i) * (1 - ATR5[1])), limit = (array.get(overSRLs, i) * (1 + ATR5[1]))
array.push(removeFromOver, i)
I know it's not much of a strategy, but I cut out the irrelevant parts to make a smaller reproductible example. When just the code above is saved, it throws the following error:
line 8: Syntax error at input 'int'.
Now, even though line 8 is the init of the for, I think the problem is in the code block in the for, and the compiler/interpreter just has bad error handling. Is there something I'm missing here? Everything looks fine to me
I think the problem is in the code block in the for, and the compiler/interpreter just has bad error handling.
Yes, the issue is in the strategy.exit -- you need one extra closing bracket in the end there. Compiler does not always provide correct lines for errors in loops. Comment out the loop and move everything one tab to the left and you'll see that the new error is line 14: Syntax error at input '('., which indicates that there is an issue with the opening bracket (because it can't find its pair).
P.S. The script will not compile after that because of the undeclared ATR5 variable, but I assume it's due to the fact that you trimmed the example code for readability.

chip Mux4way16 not run ontil the end on ‏HardwareSimulator (VHDL)

I'm tryng to build this chip:
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/01/Mux4Way16.hdl
/**
* 4-way 16-bit multiplexor:
* out = a if sel == 00
* b if sel == 01
* c if sel == 10
* d if sel == 11
*/
CHIP Mux4Way16 {
IN a[16], b[16], c[16], d[16], sel[2];
OUT out[16];
PARTS:
// Put your code here:
And that what i wrote ontil now -
PARTS:
// Put your code here:
Xor(a=sel[0], b=sel[1], out=finalSel);
Not(in=finalSel, out=notFinalSel);
Mux16(a=a, b=b, sel=finalSel, out=aAndB);
Mux16(a=c, b=d, sel=notFinalSel, out=cAndd);
Mux16(a=aAndB, b=cAndd, sel=sel[0], out=out);
}
And for some reason it's not working..
Screenshot from the ‏‏HardwareSimulator
someone know why?
Your logic for selecting what input to pass through appears to be incorrect. You should test it by creating a truth table for finalSel, notFinalSel, aAndB, cAndd and out for each of the 4 control conditions.
In general, when doing these kinds of problems, the KISS principle holds; Keep It Simple and Stupid. You don't need any fancy logical manipulation of your sel[] bits, you can just use them directly. So once you get your version fixed (and understand where you went wrong), try doing a version that just consists of 3 Mux16's and nothing else. Once you have both versions working, you'll then understand the error that caused you to go down the wrong path in your first attempt, and that will be a valuable lesson going forward.
Have fun!

I keep getting stuck in an infinite loop java

I am writing a battleship program. Right now I am testing a couple lines of code to see if it will place the boat going in the up direction. How my program is set up is that if, for example, the user clicks on the aircraft carrier button to set his aircraft carrier, the program should also set the ai's aircraft carrier. The boats are placed on a button array, called tlba. aifirstclicki is set by a random generator so that it will choose a random row. aifirstclickj chooses a random column, in conjunction the two pinpoint a spot on the button array (which is 10x10). I wrote the following code to try to make it so that if the program has an outofboundsexception error,or in other words if the program chooses a first spot that will eventually cause an outofbounds exception error because the for loop will keep adding spots until aiclickcount = 5, it should start over and pick a different spot until it finds a spot that will allow it to place all 5 spots. I keep getting stuck in an infinite loop though.
int aiclickcount = 0;
while (directiondecider == 0)
{//up
aifirstclicki = generator.nextInt(10);
aifirstclickj = generator.nextInt(10);
while (aifirstclicki != 3 &&
aifirstclicki != 2 &&
aifirstclicki != 1 &&
aifirstclicki != 0)
{
for(int k=0; k<shiplength; k++)
{
tlba[aifirstclicki - k][aifirstclickj].setBackground(Color.RED);
aistringarray[aifirstclicki - k][aifirstclickj] = "aircraftcarrier";
aioccupied2d[aifirstclicki - k][aifirstclickj] = true;
aiclickcount++;
}
if (aiclickcount == 5)
{
shipset = true;
break;
}
}
System.out.println(shipset);
}
Does anyone know what's wrong or have a different solution to my problem?
You never have aiclickcount == 5 if your shiplength is not 5. Put if into your for loop. You don't need the second while at all, you don't break out of it as well. Just generate number greater than 3 by nextInt(6) + 4.
Your code does not tell us, which value the variable shiplength has. If it's 0 the for-loop will never be entered thus aiclickcount will remain 0 and your break statement is never reached (under the premise that the random value of aifirstclicki is greater than 3).
Try to step through your code with a debugger and let it display the values for the variables to you to find out what's going on.
Your break; is only going to get you out of the second while loop, not the first as it only works on the inner-most loop that it is part of.
Java allows you to specify multi-level breaks, rather than having to complicate your loop conditions:
Breaking out of nested loops in Java

very basic objective-c question

I wrote a simple program to understand how objective-c works. This program is the i-ching, an ancient divination based on six lines response, calculated after launching three coins for six times, and then build an hexagram which is the reponse.
I am stuck at this, that I am sure has simple solution. This is how I defined the lines, I know it's not the best design, but I am trying to use as much technology as possible.
Supposing you launch a coin, it can be 3 or 2 depending on the side, three coins result in possible value 6,7,8,9.
/**
* identifying a coin
*/
typedef enum {
head=3,
tail=2
} Coin;
/**
identify a line, three coins with a side value of
2 and 3 can result in 6,7,8,9
*/
typedef enum {
yinMutable=tail+tail+tail, // 6 --> 7
yang=tail+tail+head, // 7
yin=head+head+tail, // 8
yangMutable=head+head+head // 9 --> 8
} Line;
/**
The structure of hexagram from bottom "start" to top "end"
*/
typedef struct {
Line start;
Line officer;
Line transit;
Line minister;
Line lord;
Line end;
} Hexagram;
The first problem I encounter with this design is to assign a value at each line in Hexagram. The first launch should fill value in start, the second in officer....and so on.
But can be easily solved with a switch case...altough I don't like it.
1) First question: I wonder if there is some function like in javascript or c# like
foreach (property in Hexagram) that let me browse the properties in their declaration order, that would solve my problem.
2) Second question: as an alternative way I used an array of Line:
Controller.m
....
Line response[6]
....
-(id) buildHexagram:... {
for(i =0.....,i++).....
response[i]=throwCoins;
// I omit alloc view and the rest of the code...then
[myview buildSubview:response];
}
----------------------
subView.m
-(id) buildSubView:(Line[]) reponse {
NSLog(#"response[0]=%o",[response objectAtIndex[0]]); <--- HERE I GOT THE ERROR
}
but then, whit this solution I got an error EXC_BAD_ACCESS
So obviously I am misunderstanding how array works in objective-c or c !
In the hope I have made myself clear enough, can someone point out the solution to the first question, and what I am doing wrong in the second option.
thanks
Leonardo
You've created a C array of Line - to access the elements you need to use C style array accessors.
So instead of
[response objectAtIndex[0]]
use
response[0]

== Operator and operands

I want to check whether a value is equal to 1. Is there any difference in the following lines of code
Evaluated value == 1
1 == evaluated value
in terms of the compiler execution
In most languages it's the same thing.
People often do 1 == evaluated value because 1 is not an lvalue. Meaning that you can't accidentally do an assignment.
Example:
if(x = 6)//bug, but no compiling error
{
}
Instead you could force a compiling error instead of a bug:
if(6 = x)//compiling error
{
}
Now if x is not of int type, and you're using something like C++, then the user could have created an operator==(int) override which takes this question to a new meaning. The 6 == x wouldn't compile in that case but the x == 6 would.
It depends on the programming language.
In Ruby, Smalltalk, Self, Newspeak, Ioke and many other single-dispatch object-oriented programming languages, a == b is actually a message send. In Ruby, for example, it is equivalent to a.==(b). What this means, is that when you write a == b, then the method == in the class of a is executed, but when you write b == a, then the method in the class of b is executed. So, it's obviously not the same thing:
class A; def ==(other) false end; end
class B; def ==(other) true end; end
a, b = A.new, B.new
p a == b # => false
p b == a # => true
No, but the latter syntax will give you a compiler error if you accidentally type
if (1 = evaluatedValue)
Note that today any decent compiler will warn you if you write
if (evaluatedValue = 1)
so it is mostly relevant for historical reasons.
Depends on the language.
In Prolog or Erlang, == is written = and is a unification rather than an assignment (you're asserting that the values are equal, rather then testing that they are equal or forcing them to be equal), so you can use it for an assertion if the left hand side is a constant, as explained here.
So X = 3 would unify the variable X and the value 3, whereas 3 = X would attempt to unify the constant 3 with the current value of X, and be equivalent of assert(x==3) in imperative languages.
It's the same thing
In general, it hardly matters whether you use,
Evaluated value == 1 OR 1 == evaluated value.
Use whichever appears more readable to you. I prefer if(Evaluated value == 1) because it looks more readable to me.
And again, I'd like to quote a well known scenario of string comparison in java.
Consider a String str which you have to compare with say another string "SomeString".
str = getValueFromSomeRoutine();
Now at runtime, you are not sure if str would be NULL. So to avoid exception you'll write
if(str!=NULL)
{
if(str.equals("SomeString")
{
//do stuff
}
}
to avoid the outer null check you could just write
if ("SomeString".equals(str))
{
//do stuff
}
Though this is less readable which again depends on the context, this saves you an extra if.
For this and similar questions can I suggest you find out for yourself by writing a little code, running it through your compiler and viewing the emitted asembler output.
For example, for the GNU compilers, you do this with the -S flag. For the VS compilers, the most convenient route is to run your test program in the debugger and then use the assembeler debugger view.
Sometimes in C++ they do different things, if the evaluated value is a user type and operator== is defined. Badly.
But that's very rarely the reason anyone would choose one way around over the other: if operator== is not commutative/symmetric, including if the type of the value has a conversion from int, then you have A Problem that probably wants fixing rather than working around. Brian R. Bondy's answer, and others, are probably on the mark for why anyone worries about it in practice.
But the fact remains that even if operator== is commutative, the compiler might not do exactly the same thing in each case. It will (by definition) return the same result, but it might do things in a slightly different order, or whatever.
if value == 1
if 1 == value
Is exactly the same, but if you accidentally do
if value = 1
if 1 = value
The first one will work while the 2nd one will produce an error.
They are the same. Some people prefer putting the 1 first, to void accidentally falling into the trap of typing
evaluated value = 1
which could be painful if the value on the left hand side is assignable. This is a common "defensive" pattern in C, for instance.
In C languages it's common to put the constant or magic number first so that if you forget one of the "=" of the equality check (==) then the compiler won't interpret this as an assignment.
In java, you cannot do an assignment within a boolean expression, and so for Java, it is irrelevant which order the equality operands are written in; The compiler should flag an error anyway.