Home > Mobile >  Why doesn't my code compile and ask for a return statement?
Why doesn't my code compile and ask for a return statement?

Time:05-27

Why doesn't this code compile?

import javafx.util.Pair;
import java.util.Scanner;

public class Solution {
    public static Pair < Integer, Integer > swap(Pair < Integer, Integer > swapValues) {
        Scanner scanner =new Scanner(System.in);
        
        int a; //lets say a=2
        int b; //and b=3
        a= scanner.nextInt();
        b= scanner.nextInt();
        Pair pr =new Pair 
        int swap=a; //swap =a i.e swap is now 2
        a=b; //a was 0 now its 3 
        b=swap; //b was 0 now its 2
        //swap complete now a=3,b=2
    }
}

error:

Compilation Failed
./Solution.java:17: error: missing return statement
    }
    ^
1 error

What does the compiler want from me?

CodePudding user response:

Its bit unclear, but based on my understanding, this is what you are looking for:

import javafx.util.Pair;
import java.util.Scanner;

public class Solution {
    public static Pair < Integer, Integer > swap(Pair < Integer, Integer > swapValues) {
        Scanner scanner =new Scanner(System.in);
        
        int a; //lets say a=2
        int b; //and b=3
        a= scanner.nextInt();
        b= scanner.nextInt();
        int swap=a; //swap =a i.e swap is now 2
        a=b; //a was 0 now its 3 
        b=swap; //b was 0 now its 2
        //swap complete now a=3,b=2
       Pair<Integer,Integer> pr =new Pair<Integer,Integer>(a,b);
       return pr;
    }
}

CodePudding user response:

When creating methods you should (I think) always know if you want this method to return something or not. In this occasion, if I am right, you haven't mentioned what your return type is. Is it void? Is it an object? Is it an int e.t.c.The aforementioned solution returns the Pair class object that you assigned as or. If this is your desired return, then you may be OK. Thank you for your time.

  • Related