a) Write an integer function Input as follows:
function Input(s)
The function takes in a String parameter that will be used as part of the input prompt, e.g. "Please enter 1st integer" and "Please enter 2nd integer". It returns an integer value corresponding to the user input.
b) Write a function bigger that takes in 2 integer values first and second. It compares which number is bigger and returns one of the following string values:
"1st number is bigger"
"2nd number is bigger"
"The 2 numbers are equal"
c) In the main part of the program, invoke Input(“1st”) and Input(“2nd”) to get the values of first and second. Invoke bigger and display the string returned.
I encountered some problem with my code as it doesn't seem to work as i do not know how to link the inputs together. This is one of my practical questions.
i tried linking the input together but i am unsure of how to do it because the question is kind of confusing.
i do not know how to describe my problem as i do not quite understand the question requirements
I suspect that you're overthinking this.
According to the description, your main program doesn't need to be more complicated than this:
let a = Input("1st");
let b = Input("2nd");
console.log(bigger(a, b));
Now, you "just" need to implement Input and bigger.
Addendum: putting the code you already have in functions is not very complicated:
function Input(prompt)
{
return parseInt(input.question("Please enter " + prompt + " number:"));
}
function bigger(a, b)
{
if (a > b) {
return "1st number is bigger";
}
else if (a < b) {
return "2nd number is bigger";
}
else {
return "The two numbers are equal";
}
}
Use with the code above.
Related
We have a "user script" where the goal is to check if a value is in a list.
The input values can be either int or double:
int i = 5
double d = 5
println i==d // gives true
But
println d in [5] // gives false
I understand why, int.equals(double ..) is false.
But is there a solution where the user can put ints or doubles in the list without considering the type?
But is there a solution where the user can put ints or doubles in the
list without considering the type?
There are, and what is the right thing to do would depend on understanding more about the data, but one option is instead of d in [5] you could do something like [5].any{ it == d }.
In the documentation of compareTo function, I read:
Returns zero if this object is equal to the specified other object, a
negative number if it's less than other, or a positive number if it's
greater than other.
What does this less than or greater than mean in the context of strings? Is -for example- Hello World less than a single character a?
val epicString = "Hello World"
println(epicString.compareTo("a")) //-25
Why -25 and not -10 or -1 (for example)?
Other examples:
val epicString = "Hello World"
println(epicString.compareTo("HelloWorld")) //-55
Is Hello World less than HelloWorld? Why?
Why it returns -55 and not -1, -2, -3, etc?
val epicString = "Hello World"
println(epicString.compareTo("Hello World")) //55
Is Hello World greater than Hello World? Why?
Why it returns 55 and not 1, 2, 3, etc?
I believe you're asking about the implementation of compareTo method for java.lang.String. Here is a source code for java 11:
public int compareTo(String anotherString) {
byte v1[] = value;
byte v2[] = anotherString.value;
if (coder() == anotherString.coder()) {
return isLatin1() ? StringLatin1.compareTo(v1, v2)
: StringUTF16.compareTo(v1, v2);
}
return isLatin1() ? StringLatin1.compareToUTF16(v1, v2)
: StringUTF16.compareToLatin1(v1, v2);
}
So we have a delegation to either StringLatin1 or StringUTF16 here, so we should look further:
Fortunately StringLatin1 and StringUTF16 have similar implementation when it comes to compare functionality:
Here is an implementation for StringLatin1 for example:
public static int compareTo(byte[] value, byte[] other) {
int len1 = value.length;
int len2 = other.length;
return compareTo(value, other, len1, len2);
}
public static int compareTo(byte[] value, byte[] other, int len1, int len2) {
int lim = Math.min(len1, len2);
for (int k = 0; k < lim; k++) {
if (value[k] != other[k]) {
return getChar(value, k) - getChar(other, k);
}
}
return len1 - len2;
}
As you see, it iterated over the characters of the shorter string and in case the charaters in the same index of two strings are different it returns the difference between them. If during the iterations it doesn't find any different (one string is prefix of another) it resorts to the comparison between the length of two strings.
In your case, there is a difference in the first iteration already...
So its the same as `"H".compareTo("a") --> -25".
The code of "H" is 72
The code of "a" is 97
So, 72 - 97 = -25
Short answer: The exact value doesn't have any meaning; only its sign does.
As the specification for compareTo() says, it returns a -ve number if the receiver is smaller than the other object, a +ve number if the receiver is larger, or 0 if the two are considered equal (for the purposes of this ordering).
The specification doesn't distinguish between different -ve numbers, nor between different +ve numbers — and so neither should you. Some classes always return -1, 0, and 1, while others return different numbers, but that's just an implementation detail — and implementations vary.
Let's look at a very simple hypothetical example:
class Length(val metres: Int) : Comparable<Length> {
override fun compareTo(other: Length)
= metres - other.metres
}
This class has a single numerical property, so we can use that property to compare them. One common way to do the comparison is simply to subtract the two lengths: that gives a number which is positive if the receiver is larger, negative if it's smaller, and zero of they're the same length — which is just what we need.
In this case, the value of compareTo() would happen to be the signed difference between the two lengths.
However, that method has a subtle bug: the subtraction could overflow, and give the wrong results if the difference is bigger than Int.MAX_VALUE. (Obviously, to hit that you'd need to be working with astronomical distances, both positive and negative — but that's not implausible. Rocket scientists write programs too!)
To fix it, you might change it to something like:
class Length(val metres: Int) : Comparable<Length> {
override fun compareTo(other: Length) = when {
metres > other.metres -> 1
metres < other.metres -> -1
else -> 0
}
}
That fixes the bug; it works for all possible lengths.
But notice that the actual return value has changed in most cases: now it only ever returns -1, 0, or 1, and no longer gives an indication of the actual difference in lengths.
If this was your class, then it would be safe to make this change because it still matches the specification. Anyone who just looked at the sign of the result would see no change (apart from the bug fix). Anyone using the exact value would find that their programs were now broken — but that's their own fault, because they shouldn't have been relying on that, because it was undocumented behaviour.
Exactly the same applies to the String class and its implementation. While it might be interesting to poke around inside it and look at how it's written, the code you write should never rely on that sort of detail. (It could change in a future version. Or someone could apply your code to another object which didn't behave the same way. Or you might want to expand your project to be cross-platform, and discover the hard way that the JavaScript implementation didn't behave exactly the same as the Java one.)
In the long run, life is much simpler if you don't assume anything more than the specification promises!
I have the following code to check if the value is Int or null and further check if it is below a certain number:
binding.RootLayout.forEach {
if (it is EditText) {
val intOrNull = it.text.toString().toIntOrNull()
if (intOrNull == null) {
count += 1
} else if (intOrNull > 100000) {
overTheLimitExist = true
}
}
}
The problem is, when I enter some number like 123456789 or below, it correctly identify it as (1) Int and (2) above the preset limit. However, if I enter a larger number such as 12345678900 it incorrectly identify it as null.
I search online for the toIntOrNull but they didn't say anything about a limit to the function.
12345678900 is larger than Integer's max value (2^31-1) , hence the implementation of toIntOrNull returns null, as 12345678900 doesn't fit in 4 bytes.
You can use toLongOrNull or toBigIntegerOrNull for really big numbers.
I think this problem is for limit of int type
(-2,147,483,648 to 2,147,483,647) you should use another type such as "Long" or BigNumber java class.
you can test 1 bigger than this range (2147483648) or 1 smaller (2147483646) and see the result.
I hope this help to you.
sorry for my English.
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 am working on an application that churns output based on comparison of string input. I realize however that most modes of comparison are not applicable to strings. By these I am referring to:
less than(<)
less than and equal to(<=)
greater than(>)
greater than and equal to(>=)
equal to(==)
Is there a workaround that anyone might know about? I would appreciate any advice.
Thanks.
[RE-EDIT]
My application is a form that includes various fields. For instance when one enters a value in one textfield, that value is compared against a target value based on the conditions I listed above. And based on the result, execution can proceed.
I hope this sheds some light.
You can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
String a="myWord";
if(a.compareTo(another_string) <0){
//a is strictly < to another_string
}
else if (a.compareTo(another_string) == 0){
//a equals to another_string
}
else{
// a is strictly > than another_string
}
What comparison do you need to do? The compareTo() method on String might do the trick.
If you have strings containing nummeric values you should try parsing them to a nummeric representation first. I.e.:
try {
long number1 = Long.parseLong(myString1);
long number2 = Long.parseLong(myString2);
if(number1 <= number2) {
// dosomething
}
} catch(NumberFormatException e) {
Log.e(TAG, "can not parse string to long",e);
}
for simple equals comparision there is the String.equals method:
if(myString1.equals(myString2)) {
// dosomething