The simplest answer: just use collate(a, b)
and assign the value back to the variable or print it on the screen ...
The longer answer ends with the same, but begins by indicating that your program will not actually be running at the moment ...
public void main(String[] args){
not a valid entry point for your program. Instead, it should be public static void main(String[] args){
Now, if you do this, you will encounter a number of compiler errors in which some non-static parts of your application will not be accessible from a static context ...
The simplest solution would be to provide a constructor
the Collate
class, which can be called from main
...
public class Collate{ String result; String a; String b; public void main(String[] args){ new Collate(); } public Collate() { System.out.printf("Enter 1st word: "); Scanner in1 = new Scanner(System.in); a = in1.next(); System.out.printf("Enter second word: "); Scanner in2 = new Scanner(System.in); b = in2.next(); String collation = collate(a, b); System.out.println(collation); } public String collate(String a, String b){ String accumulator; this.a = a; this.b = b; for(int i = 0; i < a.length(); i++) { result += a.charAt(i); result += b.charAt(i); } return (result); } }
Update
I seem to be creating a good excitement of responsibility. Although he can argue that the responsibility of classes is to ask the user what they want to do and what to do, it can also be argued that the class itself must contain its task, for example ...
public class Collate{ String result; String a; String b; public void main(String[] args){ System.out.printf("Enter 1st word: "); Scanner in1 = new Scanner(System.in); a = in1.next(); System.out.printf("Enter second word: "); Scanner in2 = new Scanner(System.in); b = in2.next(); Collate collate = new Collate(); String collation = collate.collate(a, b); System.out.println(collation); new Collate(); } public String collate(String a, String b){ String accumulator; this.a = a; this.b = b; for(int i = 0; i < a.length(); i++) { result += a.charAt(i); result += b.charAt(i); } return (result); } }
Since there is a significant lack of context, it is impossible to come to a specific decision ...
source share