Skip to content
Advertisement

Can you help me to find out the error in this Java Code

import java.util.*;
import java.lang.*;
public class FindMissingNumbers {
    public static void main(String[] args) {
        String input1="1 2 3 3 5 5";
        String[] input2 = input1.split(" ");
        int l1=0;
        int a=1;
       final int[] l2 = { 0 };
       HashMap<Integer,Integer> has = new HashMap<>();
       for (int i=0;i< input2.length;i++){
           if(input2[i] == null || input2[i] ==" ")
               continue;
           if(Integer.parseInt(input2[i]) != a){
               l1++;
           }
           if(has.containsKey(Integer.parseInt(input2[i]))){
               has.put(Integer.parseInt(input2[i]),has.get(Integer.parseInt(input2[i]))+1);
           }
           else{
               has.put(Integer.parseInt(input2[i]),1);
           }
           a++;
       }
       String ans = String.valueOf(l1);
       has.forEach((k,v)-> {
           if(v>1){
               l2[0]++;
           }
       });

       String final_ans = ans+l2[0];
       return final_ans;
    }

}

Giving error as Void methods cannot return a value. If am trying to change the method as static and removing void it’s not running as java application.

Advertisement

Answer

main is void, so it should not return anything, you cannot have a return statement in the main method.

Every method must contain a return type ( example int, long, double, int[] , and void where void means the method will not return anything).
if you try to run a method without a return type then it will not run.

public static void main(String[] args) {}

this method’s return type is void, it means there should not be a return statement inside this method
but you are returning the ans in the end

return final_ans;

therefore, to run the application you need to remove the return statement and instead you can print the answer to the console like this

System.out.println(ans)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement