Ok, so I am a little lost with Processing Programming Language again, so wondering if anyone can help my brain become unblocked?
This is the question - "Write a program which compares two numbers, if one of the numbers is larger than the other then the two numbers are added together and the result is printed in the console window."
So I have got this, but im getting errors on just the 'int' value code which is making me think ive completely misunderstood this?.. possibly misunderstood how the language works :/
Here is my code;
void setup() {
int a = 30
int b = 20
if (a > b) {printIn("a+b");}
}
Generally it helps if you post what errors you're getting. However, in this case you have a very basic syntax problem: you need to terminate your statements with semicolons - including the assignments. Eg: int a = 30;
Oh, and it's println (with a lowercase L) not printIn. And, as noted by logoff, you're doing the sum inside a quoted string, which will just print as a literal.
If I understad it correctly you have to declare the variables outside the setup() method. Intialization can be done inside the method.
The l in println(); should be lowercase.
There is no need for the quotes around the variables.
This works:
void setup() { int a = 30; int b = 20; if(a > b) {println(a + b); }}
Related
Thank you in advance for your time and help.
Exercise:
Write the code for sumDigitsInNumber(int number). The method takes a three-digit whole number. You need to calculate the sum of the digits of this number, and then return the result.
Consider this example:
The sumDigitsInNumber method is called with argument 546.
Example output:
15
CODE:
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
}
}
This is a solution and the task has been passed. The problem is the solution had been implemented by someone (not by me) therefore I can't understand How this function does its job.
I tried to test the function parts separately, just to see what would happen, and here is the result:
number%10 = 546%10;
546/10 = 54;
output:
6+sumDigitsInNumber(546/10) - which is totally wrong.
I don't understand HOW sumDigitsInNumber is treated by the ternary operator in there and how this short line of code:
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
makes such a complicated calculation?
Can anyone explain it to me in a way it would have explained to a Java-child?
TYVM in advance.
So, using the example number of 546, let's step through the code.
In the first run, it does indeed return 6+sumDigitsInNumber(546/10), that is all correct.
Because sumDigitsInNumber's parameter (number) is int, the decimal portion of the division is truncated, resulting in essentially a floor operation (forced round down). And we recursively call sumDigitsInNumber's, so we just keep "looping" that section of code. So for the second run, it is equivalent to sumDigitsInNumber(54), plus the additional 6 from the first run (6+sumDigitsInNumber(54)).
The second call returns 4+sumDigitsInNumber(54/10) by following the same logic as the first call. This is equivalent to 4+sumDigitsInNumber(5).
Then we run the whole process again, which returns 5+sumDigitsInNumber(5/10), equivalent to 5+sumDigitsInNumber(0).
The final call, sumDigitsInNumber(0), will return 0 because of the ternary operator in the return statement.
To expand this all out:
sumDigitsInNumber(546)
= 6+sumDigitsInNumber(546/10) = 6+sumDigitsInNumber(54)
= 6+(4+sumDigitsInNumber(54/10)) = 6+(4+sumDigitsInNumber(5))
= 6+(4+(5+sumDigitsInNumber(5/10))) = 6+(4+(5+sumDigitsInNumber(0)))
= 6+(4+(5+0))
= 6+(4+(5))
= 6+(9)
= 15
I try to get an integer (right after "PLAYING:STATION\nID:"out of the String shown in my screenshot by using the following code:
int zahl = Integer.parseInt(sentence.substring(sentence.indexOf("PLAYING:STATION\n
ID:")+1).trim());
But all I get is a NumberFormatException. How can I tell the trim()-method that it has to stop right after the number?
Screenshot of the complete String
Since you must select a specific ID: entry among several ones, I think the best way to proceed is using a regular expression. Using your output sample, I wrote the following code:
String text = "PLAYING_MODE\nID:\nPLAYING:STATION\nID:2\nNAME:wazee.org";
Pattern p = Pattern.compile("PLAYING:STATION\nID:(\\d+)");
Matcher m = p.matcher(text);
if (m.find()) {
int number = Integer.parseInt(m.group(1));
System.out.println(number);
}
which correctly parses the ID number that immediately follows PLAYING_STATION.
You could as well repeatedly work with the overloaded String.indexOf() method (find PLAYING:STATION, then the following ID:, then the following \n). I think the code might be harder to read, but it would still do the job.
I hope this will be helpful...
Cheers,
Jeff
I suppose this:
public static string abc()
{
return "abc";
}
Is better to call this function in this way:
string call = abc();
Console.writeline(call);
Than this?
console.writeline(abc());
is there any reason to prefer one to the other?
Both are valid. However, out of experience I have concluded that the first option is more suitable for readability and ease of maintenance. I can't count how many times I have changed from the "compact" style to the first one as a help for a debugging session.
For example, this style makes it easy to check the correctness intermediate of an intermediate result:
string call = abc();
assert(!call.empty()); // Just an example.
Console.writeline(call);
Also, it helps to make the code more robust later, adding a conditional check before the subsequent action that checks call's value, for example if the design does not guarantee that the condition of the previous assert holds but you still need to check it.
string call = abc();
if (!call.empty())
{
Console.writeline(call);
}
Note also that with this style you will be able to easily inspect the value of call in your debugger.
Given your exact example (one parameter, value not used elsewhere, no side effects), it's just a matter of style. However, it gets more interesting if there are multiple parameters and the methods have side effects. For example:
int counter;
int Inc() { counter += 1; return counter }
void Foo(int a, int b) { Console.WriteLine(a + " " + b); }
void Bar()
{
Foo(Inc(), Inc());
}
What would you expect Foo to print here? Depending on the language there might not even be a predictable result. In this situation, assigning the values to a variable first should cause the compiler (depending on language) to evaluate the calls in a predictable order.
Actually I don't see a difference if you don't have any error checking.
This would make a difference
string call = abc();
# if call is not empty
{
Console.writeline(call);
}
The above method could avoid empty string being written.
Preface: I'm working with Processing and I've never used Java.
I have this Processing function, designed to find and return the most common color among the pixels of the current image that I'm working on. the last line complains that "The method color(int) in the type PApplet is not applicable for the arguments (String)." What's up?
color getModeColor() {
HashMap colors = new HashMap();
loadPixels();
for (int i=0; i < pixels.length; i++) {
if (colors.containsKey(hex(pixels[i]))) {
colors.put(hex(pixels[i]), (Integer)colors.get(hex(pixels[i])) + 1);
} else {
colors.put(hex(pixels[i]),1);
}
}
String highColor;
int highColorCount = 0;
Iterator i = colors.entrySet().iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
if ((Integer)me.getValue() > highColorCount) {
highColorCount = (Integer)me.getValue();
highColor = (String)me.getKey();
}
}
return color((highColor);
}
The Processing docs that I'm looking at are pretty sparse on the HashMap so I'm not really sure what's going on inside it, but I've been augmenting what's available there with Java docs they point to. But I'm not really grokking what's happening with the types. It looks like the key in the HashMap needs to be a string and the value needs to be an integer, but they come out as objects that I have to cast before using. So I'm not sure whether that's causing this glitch.
Or maybe there's just a problem with color() but the docs say that it'll take a hex value which is what I was trying to use as the key in the HashMap (where I'd rather just use the color itself).
Now that I've talked through this, I'm thinking that the color() function sees the hex value as an int but the hex() function converts a color to a string. And I don't seem to be able to convert that string to an int. I guess I could parse the substrings and reconstruct the color, but there must be some more elegant way to do this that I'm missing. Should I just create a key-value-pair class that'll hold a color and a count and use an arraylist of those?
Thanks in advance for any help or suggestions you can provide!
I'll dig deeper into this, but an initial thought is to employ Java generics so that the compiler will complain about type issues (and you won't get runtime errors):
HashMap<String,Integer> colors = new HashMap<String,Integer>();
So the compiler will know that keys are Strings and elements are Integers. Thus, no casting will be necessary.
I didn't figure it out, but I did work around it. I'm just making my own string from the color components like:
colors.put(red(pixels[i]) + "," + green(pixels[i]) + "," + blue(pixels[i]),1)
and then letting the function drop a color out like this:
String[] colorConstituents = split(highColor, ",");
return color(int(colorConstituents[0]), int(colorConstituents[1]), int(colorConstituents[2]));
This doesn't really seem like the best way to handle it -- if I'm messing with this long-term I guess I'll change it to use an arraylist of objects that hold the color and count, but this works for now.
Is there a programming language that supports chained notation a < b < c to be used instead of a < b and b < c in conditional statements?
Example:
if ( 2 < x < 5 )
if ( 2 < x && x < 5 )
First statementlooks better to me, it's easier to understand and the compiler could use transitivity property to warn about mistakes (e.g. 5 < x < 2 would give a warning).
Python does that.
Icon does this, and it is not part of any hacky special-case "chaining"; it is part of Icon's goal-directed evaluation model. Any comparison either succeeds or fails. If it succeeds, it produces the right-hand side. So you can write
if 0 <= i <= j < n then ...
and it works exactly the way you would expect. But it works not just for comparisons but for any expression; this means you can write your own functions that "chain" in exactly the same way. I love this aspect of Icon and wish more languages could incorporate goal-directed evaluation.
N.B. In Guido's paper introducing Python at VHLL (middle 1990s) he mentions Icon explicitly as a source of inspiration in the design of Python.
This sounds like a simple request (and clearly it is simple enough that python implemented it) but it is not necessarily that easy to use. It actually opens up the ability for a lot of errors to be caused.
Specifically, any time that you use functions (or properties in the case of C#, Getters for Java)
So
public int GetX()
{
return 4;
}
(2 < GetX() < 5);
(2 < GetX() > 5);
(5 < GetX() < 2);
Seems like it would be really simple. But problems occur if GetX() has side effects.
private int val = 10;
public int GetCountdown()
{
return val--;
}
(2 < GetCountdown() < 5);
(2 < GetCountdown() > 5);
(5 < GetCountdown() < 2);
In this situation, is "GetCountdown()" decremented twice or just once?
Would the "chained-if-statement" ever shortcut?
Consider the last statments, which roughly evaluates (in english) to "Is 5 less than some value which is less than 2) which should be impossible, but depending on the implementation and side effects, it is possible that some function (Random.NextInt()) could pass both of those tests.
So, for that reason, it would be required that each of the items is only evaluated once, the saved into a local variable for the next comparison. But then you get into shortcutting problems.
public int GetOne()
{
return 1;
}
public int GetVar()
{
return -1;
}
(GetOne() < GetVar() < GetDBVal() < GetUserInput())
Generally, you would want to first check constants and variables before doing a database hit. But if we said (as we said earlier) that all the values must be saved into local variables ahead of time, this means that it might be calling a database hit, and asking the user for information even though "GetVar()" is -1, and so the first comparison fails)
As I said earlier, clearly Python allows this syntax, so it is clearly possible. But, regardless of the technical implications which I have laid out (all of which are easy to design around) it means that your code is less clear because the next person who reads it does not know whether or not you have considered all of this. Whereas, if(x > 2 && x < 5) { } seems clear to me, I know what it does, and I know what the coder intends.