gpt4 book ai didi

java - 我如何将 x 和 y 从不同的类返回到 Java 中的 main?

转载 作者:行者123 更新时间:2023-11-29 06:08:55 25 4
gpt4 key购买 nike

如何将我的 x 和 y 变量返回到 main 中以执行加法?在此先感谢您的帮助!

import java.util.Scanner;

public class calling {

public static int x;
public static int y;

public static void num1() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number: ");
x=scanner.nextInt();
}

public static void num2() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number: ");
y=scanner.nextInt();
}

public static void main(String[] args){ **//place to return variables.**

num1();
num2();
System.out.print("The sum of the two numbers is: " + (x+y));
}
}

最佳答案

public static int getInput() {
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}

public static void main(String[] args){
System.out.println("Please enter a number: ");
int x = getInput();

System.out.println("Please enter a second number: ");
int y = getInput();

int sum = x + y;
System.out.print("The sum of the two numbers is: " + sum);
}

或者更面向对象(面向对象)的方法可能看起来像

public class Calculator {

private Scanner scanner;

public Calculator() {
scanner = new Scanner (System.in);
}

public int getInput() {
return scanner.nextInt();
}

public int add(int x, int y) {
return x + y;
}

public static void main(String[] args) {
Calculator calculator = new Calculator();

System.out.println("Please enter a number: ");
int x = calculator.getInput();

System.out.println("Please enter a second number: ");
int y = calculator.getInput();

int sum = calculator.add(x, y);
System.out.print("The sum of the two numbers is: " + sum);
}

请注意 Java naming conventions状态类的首字母应大写。

关于java - 我如何将 x 和 y 从不同的类返回到 Java 中的 main?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7705508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com