Rishabh Agarwal Rishabh Agarwal - 4 months ago 13
Java Question

Print even char from a string- error non static method can not reference from static context

I am new to

java
try figuring out but couldn't find a right answer. The program is to print letter on even place.

Input:
2
Hacker
Rank

Output
Hce
Rn

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public char[] printeven(char[] arr1)
{
char[] result1;
int index = 0;
for(int i=1; i<arr1.length; i+=2)
{
result1[index] = arr1[i];
index += 1;
}
System.out.println(result1);
return result1;

}


public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
String s1= scan.next();
String s2= scan.next();
scan.close();

char[] array1 = s1.toCharArray();
char[] array2 = s1.toCharArray();

printeven(array1);
printeven(array2);
}
}


My guess was to remove static from main but than I get the error,

Solution.java:15: error: variable result1 might not have been initialized
result1[index] = arr1[i];
^
Solution.java:18: error: variable result1 might not have been initialized
System.out.println(result1);
^


2 errors

Answer

Simply make your method printeven static:

public static char[] printeven(char[] arr1).

Even if main is in the same class, you're in a static context and you can't access non-static members of Solution class.

You could also initialize a Solution and call the method:

Solution solution = new Solution();
solution.printeven(array1);
solution.printeven(array2);

Finally, you need to initialize your array before using it:

char[] result1 = new char[arr1.length];

Comments