在Java中,如何从一个方法的用户输入中获取变量,并在另一方法中使用输出? [英] In Java, how can I take a variable obtained from a user input from one method and use the output in another method?

查看:58
本文介绍了在Java中,如何从一个方法的用户输入中获取变量,并在另一方法中使用输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何将一种方法中的变量带入另一种方法中使用,尤其是用户输入中的变量.例如,此测试程序无效.我将如何运作?

I can't figure out how to bring a variable from one method into another for use, especially that from a user input. For example, this test program doesn't work. How would I make it work?

 
import java.util.*;

public class Test {
    public static void main(String[] args) {
    input();
    output();   
   }

    public static void input() {

        Scanner console = new Scanner(System.in);

        System.out.print("This number multiplied by 7: ");
        int number = console.nextInt();

        int number7 = number * 7;
        System.out.print("The result is: " + number7);

    }
    public static void output() {

        Scanner console = new Scanner(System.in);

        System.out.print("The result multiplied by two: ");
        int number = console.nextInt();

        int number2 = number7 * 2;
        System.out.print("The result is: " + number2);
    }
}

推荐答案

(至少)有两种方法.一种是定义您的input()方法以返回output()方法所需的值:

There are (at least) two ways. One is to define your input() method to return the value needed in the output() method:

import java.util.*;

public class Test {
    public static void main(String[] args) {
    int in = input();
    output(in);   
   }

    public static int input() {

        Scanner console = new Scanner(System.in);

        System.out.print("This number multiplied by 7: ");
        int number = console.nextInt();

        int number7 = number * 7;
        System.out.print("The result is: " + number7);
        return number7;
    }

    public static void output(int number7) {

        Scanner console = new Scanner(System.in);

        System.out.print("The result multiplied by two: ");
        int number = console.nextInt();

        int number2 = number7 * 2;
        System.out.print("The result is: " + number2);
    }
}

另一种是声明一个类变量:

The other is to declare a class variable:

import java.util.*;

public class Test {
    static int number7;
    public static void main(String[] args) {
    input();
    output();   
   }

    public static void input() {

        Scanner console = new Scanner(System.in);

        System.out.print("This number multiplied by 7: ");
        int number = console.nextInt();

        int number7 = number * 7;
        System.out.print("The result is: " + number7);
    }

    public static void output() {

        Scanner console = new Scanner(System.in);

        System.out.print("The result multiplied by two: ");
        int number = console.nextInt();

        int number2 = number7 * 2;
        System.out.print("The result is: " + number2);
    }
}

这篇关于在Java中,如何从一个方法的用户输入中获取变量,并在另一方法中使用输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆