为什么我的代码不编译并要求返回语句?

发布于 2025-02-02 11:55:41 字数 802 浏览 1 评论 0原文

为什么不编译此代码?

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
    }
}

错误:

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

编译器想要什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤城病女 2025-02-09 11:55:41

当创建方法时,您应该(我认为)始终知道您是否希望此方法返回某些内容。在这种情况下,如果我是对的,您尚未提及您的返回类型是什么。它是无效的吗?是对象吗?是一个int等,上述解决方案返回您分配为或分配的对对象。如果这是您所需的回报,那么您可能还可以。
谢谢你的宝贵时间。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文