Napisałem dobrze kod, ale na czuja bardziej niż wiedzowo.
package pl.codegym.task.task02.task0201;
/*
Zaimplementuj metodę print
*/
public class Solution {
public static void main(String[] args) {
print("Javy łatwo się nauczyć!");
print("Java otwiera wiele możliwości!");
}
public static void print(String s) {
//tutaj wpisz swój kod
System.out.println(s);
System.out.println(s);
System.out.println(s);
System.out.println(s);
}
}
Czym jest print i gdzie jest zdefiniowany String s ?
Nie rozumiem do końca jak to działa.
Rozwiązane
Komentarze (2)
- Popularne
- Najnowsze
- Najstarsze
Musisz się zalogować, aby dodać komentarz
Paweł P
18 lutego 2020, 16:50przydatny
Tak na chłopski rozum.
public static void main(String[] args) { tutaj wywołujesz metodę którą masz zdefiniwaną w public static void print(String s)
Czyli rownie dobrze możesz napisać public static void metoda_napisz(String s) {
i wtedy zamiast print("Javy łatwo się nauczyć!"); dajesz metoda_napisz ("Javy łatwo się nauczyć!")
public static void print(String s) tu też masz zdefiniowane że print ma otrzymać Stringa czyli jakiś tekst
czyli to 1 print to odwołanie się do klasy poniżej a tekst "Javy łatwo się nauczyć!" jest przekazywany jako zmienna czy String s
Mam nadzieje że nie zakręciłem ci tego jeszcze bardziej ;)
+1
Guadalupe Gagnon
18 lutego 2020, 16:03rozwiązanie
A method is a stub of code that can be called from any where else in code. So the print method is defined as:
public static void print(String s) {
System.out.println(s);
System.out.println(s);
System.out.println(s);
System.out.println(s);
}
Where "public" means it can be accessed from outside the class - "static" isn't important for now, just know that it is needed - "void" is its return value (void means no return value) - "print" is the method name and can be changed to anything that you want following the Java naming rules - and finally "(String s)" is/are the method's parameters.
When calling a method from code you MUST use the methods name and parameters, neglecting to do so is an error where the code will not compile.
Because the method has one parameter, a String, when you call the method from code you have to pass in a String. These 2 lines do so:
print("Javy łatwo się nauczyć!");
print("Java otwiera wiele możliwości!");
This is what happens: The parameters that are passed in become the parameters that are defined in the method. Each method call can literally be translated to that call being that method. So for example this line:
print("Javy łatwo się nauczyć!");
becomes:
} // this is the method
String s = "Javy łatwo się nauczyć!";
System.out.println(s);
System.out.println(s);
System.out.println(s);
System.out.println(s);
}
and your entire code becomes this:
+2