+ 1

How to make a method using for loop?

I'm trying to make a method that counts and prints all the element of array. https://code.sololearn.com/cDl4q1Zd30SU/?ref=app

19th Oct 2022, 2:28 AM
Mozzie
Mozzie - avatar
15 Answers
+ 2
Kim Jonas Cabugayan public static void printArray(char[] arr) { //write your code here } Now call this method inside main method public static void main(String[] args) { char[] arr = {'a', 'b'}; //Calling method printArray(arr); }
19th Oct 2022, 2:41 AM
A͢J
A͢J - avatar
+ 1
Just make a method and put for loop code inside that then call that method in main method. You can pass an array as an arguments in that method
19th Oct 2022, 2:33 AM
A͢J
A͢J - avatar
+ 1
Kim Jonas Cabugayan Yes void doesn't return anything so you can not print method like that. do this System.out.println("***"); printArray(arr1); System.out.println("***");
19th Oct 2022, 4:23 AM
A͢J
A͢J - avatar
+ 1
Kim Jonas Cabugayan Anything except void like int, double, long, Objects , list, map
19th Oct 2022, 5:15 AM
A͢J
A͢J - avatar
+ 1
19th Oct 2022, 7:53 AM
A͢J
A͢J - avatar
0
A͢J Can you make a simple example?
19th Oct 2022, 2:37 AM
Mozzie
Mozzie - avatar
0
A͢J I forgot to add[] in char for my method. No wonder it doesnt work. 😅😅 Thank you
19th Oct 2022, 2:43 AM
Mozzie
Mozzie - avatar
0
A͢J /*I tried replacing void with char[] but I don't know what to place between return ; */ class A { public static void printArray(char[] arr) { for (int i=0; i<arr.length; i++){ System.out.println("*" + arr[i] + "*"); } } public static void main(String[] args) { char[] arr1 = {'a', 'b'}; System.out.println("***" + printArray(arr1) + "***"); } } //void type is not allowed https://code.sololearn.com/cxjxdU7DowT3/?ref=app
19th Oct 2022, 3:03 AM
Mozzie
Mozzie - avatar
0
A͢J What to do so the function return any value?
19th Oct 2022, 4:38 AM
Mozzie
Mozzie - avatar
0
A͢J How to count character sequince and not elements? https://code.sololearn.com/c020K8GqYNQy/?ref=app
19th Oct 2022, 5:52 AM
Mozzie
Mozzie - avatar
0
@What you want to try to do?
19th Oct 2022, 6:32 AM
A͢J
A͢J - avatar
0
A͢J Count the character sequence of a string element. Add asterisk depending in the total no. counted. i.e {"Mozzie"} (6) ****** Mozzie ****** {"Moon"} (4) **** Moon **** and use the highest value {"Mozzie", "Moon"} ****** Mozzie Moon ******
19th Oct 2022, 6:38 AM
Mozzie
Mozzie - avatar
0
A͢J Why there's no error at line 23 at your code? Isn't it supposed to ask for identifier?
19th Oct 2022, 8:27 AM
Mozzie
Mozzie - avatar
0
Identifier for what?
19th Oct 2022, 8:39 AM
A͢J
A͢J - avatar
0
Before if I used System.out.println(); It always run into error then ask for identifier. But it suddenly okay now don't know what happened there😅😅
19th Oct 2022, 8:43 AM
Mozzie
Mozzie - avatar