Hello! I'm completely new to Java, and I have small questions I must answer weekly for my class. Here are the questions, along with my answers. Can you please tell me if I did them correctly, and if I didn't, what I did wrong and how to fix them? I tried my best :X I don't want to submit them unless they're right b/c I obviously I won't get any credit if they're wrong.
1. Write a public method called largerStr, which is passed two Strings, s1 and s2, and returns true if s1 is strictly longer than s2, false otherwise.
Example: largerStr("here", "there") --> false
Example: largerStr("there", "here") --> true
Example: largerStr("hear", "here") --> false
A:
I'm pretty sure this one is incorrect.
public bool largerStr(string s1, string s2) { return (s1.length>s2.length); }
2. Write a public method called signFlip, which is passed a double and returns that value with the opposite sign.
Example1: 4.0 --> -4.0
Example2: -3.14 --> 3.14
Note that in this example you must write a complete method, including the method header line.
A:
public double signFlip(double x) { return (x * -1.0) }
3. Write a public method called doubleOut, which is passed a String as a parameter, and which prints to the console that String concatenated with itself. Note that this method does not return anything.
Example: "boo" --> prints out booboo
Note that in this example you must write a complete method, including the method header line.
A:
I'm pretty sure I didn't do this one correctly either.
public void doubleOut(string x) { System.out.println(x + x); }
4. Write a public method called sumNumbers, which is passed a positive int as a parameter and returns the sum of the positive numbers that are less than or equal to the supplied int.
Example: 5 --> 15 since (5 + 4 + 3 + 2 + 1) = 15
Example: 3 --> 6 since (3 + 2 + 1) = 6
Note that in this example you must write a complete method, including the method header line.
A:
public int sumNumbers(int x) { int sum=0; for (int i=x; i>0; i--) {sum+=i;} return sum; }
Thanks for you help!!!
P.S. Sorry if I posted this in the wrong forum :X