Java从其他方法中使用用户输入

huangapple go评论57阅读模式
英文:

Java use user input from other methods

问题

我访问了其他类似问题,但没有找到适用于我的问题的解决方案。

为了减少代码行数,而不是将输入过程复制粘贴到我的if else语句中,我创建了一个名为 UInputs(); 的方法,用于获取用户输入。因此,我只需在需要时调用它,但是我无法在 UInputs() 内部使用用户输入的值。

import java.util.Scanner;

public class Calculator {
    public static void UInputs(){
        double num1, num2, num3, num4, num5;
        Scanner scan = new Scanner(System.in);
        System.out.print("第一个数字:");
        num1 = scan.nextDouble();
        System.out.print("第二个数字:");
        num2 = scan.nextDouble();
        System.out.print("第三个数字:");
        num3 = scan.nextDouble();
        System.out.print("第四个数字:");
        num4 = scan.nextDouble();
        System.out.print("第五个数字:");
        num5 = scan.nextDouble();
    }

    public static void main (String[] args){
        char Choice;
        double num1, num2, num3, num4, num5;

        System.out.println("\t_________________________________\n");
        System.out.println("\t|\t数学运算\t\t|\n\t|\t[+]\t加法\t|\n\t|\t[-]\t减法\t|\n\t|\t[*]\t乘法\t|\n\t|\t[/]\t除法\t|\n");
        System.out.println("\t|_______________________________|\n");
        System.out.print("输入您的选择:");
        Scanner scan = new Scanner(System.in);
        Choice = scan.nextLine().charAt(0);

        if (Choice == '+') {//加法
            System.out.println("================================\n加法\n");
            UInputs();
            double answer = num1 + num2 + num3 + num4 + num5;
            System.out.println("\n总和: " + answer );
            System.out.println("================================\n");
        }
        else if (Choice == '-') {//减法
            System.out.println("================================\n减法\n");
            System.out.print("第一个数字:");
            num1 = scan.nextDouble();
            System.out.print("第二个数字:");
            num2 = scan.nextDouble();
            System.out.print("第三个数字:");
            num3 = scan.nextDouble();
            System.out.print("第四个数字:");
            num4 = scan.nextDouble();
            System.out.print("第五个数字:");
            num5 = scan.nextDouble();
            double answer = num1 - num2 - num3 - num4 - num5;
            System.out.println("\n差值: " + answer );
            System.out.println("================================\n");
        }
    }
}
英文:

I visited other questions similar to mine but did not find the one that is applicable to me.

To lessen my line of codes instead of copy pasting that input process to my if else statement. I created a UInputs(); method that will get user inputs. So I can just call it whenever it is needed but i cant use the user inputted values inside UInputs().

import java.util.Scanner;
public class Calculator {
public static void UInputs(){
double num1, num2, num3, num4, num5;
Scanner scan = new Scanner(System.in);
System.out.print("1st Number: ");
num1 = scan.nextDouble();
System.out.print("2nd Number: ");
num2 = scan.nextDouble();
System.out.print("3rd Number: ");
num3 = scan.nextDouble();
System.out.print("4th Number: ");
num4 = scan.nextDouble();
System.out.print("5th Number: ");
num5 = scan.nextDouble();
}
public static void main (String[] args){
char Choice;
double num1, num2, num3, num4, num5;
System.out.println("\t_________________________________\n");
System.out.println("\t|\tMATH OPERATIONS\t\t|\n\t|\t[+]\tAddition\t|\n\t|\t[-]\tSubtraction\t|\n\t|\t[*]\tMultiplication\t|\n\t|\t[/]\tDivision\t|\n");
System.out.println("\t|_______________________________|\n");
System.out.print("\nEnter you Choice: ");
Scanner scan = new Scanner(System.in);
Choice = scan.nextLine().charAt(0);
if ( Choice == '+') {//ADDITION
System.out.println("================================\nAddition\n");
UInputs();
double answer = num1 + num2 + num3 + num4 + num5;
System.out.println("\nSum : " + answer );
System.out.println("================================\n");
}
else if (Choice == '-') {//SUBTRACTION
System.out.println("================================\nSubtraction\n");
System.out.print("1st Number: ");
num1 = scan.nextDouble();
System.out.print("2nd Number: ");
num2 = scan.nextDouble();
System.out.print("3rd Number: ");
num3 = scan.nextDouble();
System.out.print("4th Number: ");
num4 = scan.nextDouble();
System.out.print("5th Number: ");
num5 = scan.nextDouble();
double answer = num1 - num2 - num3 - num4 - num5;
System.out.println("\nDifference : " + answer );
System.out.println("================================\n");
}

答案1

得分: 1

以下是翻译好的代码部分:

import java.util.Scanner;

public class Calculator {
    private static final Scanner scan = new Scanner(System.in);

    /**
     * 我最初的想法是UInputs应该返回值,
     * 这些值应该累积总和。
     * 没有必要将输入保留在内存中,因为
     * 一旦使用,就不再需要它们。
     */
    public static double calculate(char functionToApply) {
        double[] inputs = new double[5];

        // 对最多20个输入有效,这里只需打印“第i个数字: ”以保持简单。
        for (int i = 0; i < inputs.length; i++) {
            String promptMessage = (i + 1) + "号";  // 数字
            // 后缀 (st, nd, rd, th)
            switch (i + 1) {
                case 1:
                    promptMessage = promptMessage + "st";
                    break;
                case 2:
                    promptMessage = promptMessage + "nd";
                    break;
                case 3:
                    promptMessage = promptMessage + "rd";
                    break;
                default:
                    promptMessage = promptMessage + "th";
                    break;
            }
            System.out.print(promptMessage + " 数字: ");
            inputs[i] = scan.nextDouble();
        }

        double result = 0;
        for (int i = 0; i < inputs.length; i++) {
            switch (functionToApply) {
                case '+':
                    result = result + inputs[i];
                    break;
                case '-':
                    result = result - inputs[i];
                    break;
            }
        }
        return result;
    }

    public static void main(String[] args) {

        displayMenu();

        char function;
        System.out.print("\n请输入您的选择: ");
        function = scan.nextLine().charAt(0);

        String heading = "";
        String lineLabel = "";
        switch (function) {
            case '+':
                heading = "加法";
                lineLabel = "总和";
                break;
            case '-':
                heading = "减法";
                lineLabel = "差";
                break;
        }

        System.out.println("================================\n" + heading + "\n");
        System.out.println("\n" + lineLabel + " : " + calculate(function));
        System.out.println("================================\n");
    }

    private static void displayMenu() {
        System.out.println("\t_________________________");
        System.out.println("\t|    数学运算    |");
        System.out.println("\t|    [+]    加法    |");
        System.out.println("\t|    [-]    减法    |");
        System.out.println("\t|    [*]    乘法    |");
        System.out.println("\t|    [/]    除法    |");
        System.out.println("\t|_______________________|\n");
    }
}

希望这对您有所帮助!

英文:

Not the best answer I could have come up with but certainly some improvements to make the code easier to digest...

I changed UInputs to a method called calculate(). It now takes the function selected as input and then asks the user for 5 numbers. The function is then applied to the 5 numbers. Another way to perform this calculation would be to request a number from the user, return it, and sequentially apply the function to the returned number(s) to get a result... this would be nicer.

import java.util.Scanner;

public class Calculator {
    private static final Scanner scan = new Scanner(System.in);

    /**
    * My initial thought here was that UInputs should return values
    * and these should be cumulatively totalled. 
    * There&#39;s no need to hold the inputs in memory since 
    * once they&#39;re consumed, they&#39;re not longer needed.
    */
    public static double calculate(char functionToApply) {
        double[] inputs = new double[5];

        // works for number of inputs up to 20 - could just print &quot;number i: &quot; here for simplicity. 
        for (int i=0; i&lt;inputs.length; i++) {
            String promptMessage = (i+1) + &quot;&quot;;  // number
            // postfixture (st, nd, rd, th)
            switch (i+1) {
                case 1: promptMessage = promptMessage+&quot;st&quot;; break;
                case 2: promptMessage = promptMessage+&quot;nd&quot;; break;
                case 3: promptMessage = promptMessage+&quot;rd&quot;; break;
                default: promptMessage = promptMessage+&quot;th&quot;; break;
            }
            System.out.print(promptMessage + &quot; Number: &quot;);
            inputs[i] = scan.nextDouble();
        }

        double result = 0;
        for (int i=0; i&lt;inputs.length; i++) {
            switch (functionToApply) {
                case &#39;+&#39;: result = result + inputs[i]; break;
                case &#39;-&#39;: result = result - inputs[i]; break;
            }
        }
        return result;
    }

    public static void main(String[] args) {

        displayMenu();
        
        char function;
        System.out.print(&quot;\nEnter your Choice: &quot;);
        function = scan.nextLine().charAt(0);

        String heading = &quot;&quot;;
        String lineLabel = &quot;&quot;;
        switch (function) {
            case &#39;+&#39;:
                heading = &quot;Addition&quot;;
                lineLabel = &quot;Sum&quot;;
                break;
            case &#39;-&#39;:
                heading = &quot;Subtraction&quot;;
                lineLabel = &quot;Difference&quot;;
                break;
        }

        System.out.println(&quot;================================\n&quot; + heading + &quot;\n&quot;);
        System.out.println(&quot;\n&quot; + lineLabel + &quot; : &quot; + calculate(function));
        System.out.println(&quot;================================\n&quot;);
    }

    private static void displayMenu() {
        System.out.println(&quot;\t_________________________&quot;);
        System.out.println(&quot;\t|\tMATH OPERATIONS\t\t|&quot;);
        System.out.println(&quot;\t|\t[+]\tAddition\t\t|&quot;);
        System.out.println(&quot;\t|\t[-]\tSubtraction\t\t|&quot;);
        System.out.println(&quot;\t|\t[*]\tMultiplication\t|&quot;);
        System.out.println(&quot;\t|\t[/]\tDivision\t\t|&quot;);
        System.out.println(&quot;\t|_______________________|\n&quot;);
    }
}

This should be easier for you to extend/edit though.

Output:

	_________________________
	|	MATH OPERATIONS		|
	|	[+]	Addition		|
	|	[-]	Subtraction		|
	|	[*]	Multiplication	|
	|	[/]	Division		|
	|_______________________|


Enter your Choice: +
================================
Addition

1st Number: 1
2nd Number: 2
3rd Number: 3
4th Number: 4
5th Number: 5

Sum : 15.0
================================


Process finished with exit code 0

Similarly for subtraction:


Enter your Choice: -
================================
Subtraction

1st Number: 10
2nd Number: 9
3rd Number: 1
4th Number: 0
5th Number: 0

Difference : -20.0
================================

答案2

得分: 0

你可以创建某种包装类:

class MyNumberWrapper {

  double num1;
  double num2;

}

然后UInput 将会是这样:

public static MyNumberWrapper UInputs(){
    MyNumberWrapper wrapper = new MyNumberWrapper();
    Scanner scan = new Scanner(System.in);
    System.out.print("1st Number: ");
    wrapper.num1 = scan.nextDouble();
    System.out.print("2nd Number: ");
    wrapper.num2 = scan.nextDouble();
    return wrapper;
}

然后在你的主函数中,你只需使用 MyNumberWrapper wrapper = UInput(),并使用 wrapper.num1wrapper.num2 等来访问所有变量。

英文:

you can create some kind of wrapper class

class MyNumberWrapper {
double num1;
double num2;
}

then UInput will look like this

public static MyNumberWrapper UInputs(){
MyNumberWrapper wrapper = new MyNumberWrapper();
Scanner scan = new Scanner(System.in);
System.out.print(&quot;1st Number: &quot;);
wrapper.num1 = scan.nextDouble();
System.out.print(&quot;2nd Number: &quot;);
wrapper.num2 = scan.nextDouble();
return wrapper;
}

then in your main function you can just use MyNumberWrapper wrapper = UInput() and access all variables with wrapper.num1, wrapper.num2 etc

huangapple
  • 本文由 发表于 2020年10月2日 20:25:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/64171500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定