简体   繁体   English

从字符串输入中声明变量(Java)

[英]Declaring a variable from a string input (Java)

When I previously asked a question, it got many downvotes because I was not very specific. 当我之前问一个问题时,它被否决了很多,因为我不是很专一。 I will do my best to be clear this time. 这次我会尽力澄清。 I have read questions with similar titles, but none have made it clear to me. 我读过类似标题的问题,但没有一个对我清楚。

Basically, I have been assigned to make a fractional calculator for my AP comp sci class. 基本上,我已被分配为我的AP comp sci类制作分数计算器。 The first checkpoint for this assignment is to be able to read fractions inputted by the user without the code crashing. 此分配的第一个检查点是能够读取用户输入的分数,而不会导致代码崩溃。 For example, "1_1/2" "1/2" or just 1. 例如,“ 1_1 / 2”,“ 1/2”或仅1。

So far, I've gotten the following - 到目前为止,我得到了以下内容-

public static void identify() {
        Scanner console = new Scanner(System.in);
        String fraction = console.next();

        if(fraction.contains("_")) {
            int wholenumber = console.nextInt();
            int numerator = console.nextInt();
            int denomenator = console.nextInt();
            System.out.print(wholenumber + "_" + numerator + "/" + denomenator);
        }
        else if(fraction.contains("/")) {
            int numerator = console.nextInt();
            int denomenator = console.nextInt();
            System.out.print(numerator + "/" + denomenator);

        } 
        else {                                                                          
            System.out.print(fraction);
        }

        }

I thought it was working at first, but then I realized that if I inputted 1_1/2 or 1/2, the code would wait for inputs for the numerator, denominator, and whole number. 我以为它起初是可以的,但是后来我意识到,如果我输入1_1 / 2或1/2,代码将等待分子,分母和整数的输入。 So my problem is that I want the previously mentioned values to be declared from the originally inputted string, and not from different inputs. 所以我的问题是我希望从原始输入的字符串而不是从不同的输入声明前面提到的值。

I understand this might be confusing to read, so basically I if input 1_1/2, I want my code to declare 1 as wholenumber, 1 as numerator, and 2 as denominator. 我知道这可能会使您感到困惑,因此,基本上,如果我输入1_1 / 2,我希望我的代码将1声明为整数,1声明为分子,2声明为分母。 How would I achieve this? 我将如何实现?

int[] numbers = Arrays.asList(fraction.split("_|/")).stream()
            .mapToInt(s -> Integer.parseInt(s))
            .toArray();

Then, 然后,
If entry is of type 1_1/2 : 如果输入的类型为1_1/2

  • wholenumber = numbers[0] 整数=数字[0]
  • numerator = numbers[1] 分子=数字[1]
  • denomenator = numbers[2] denomenator =数字[2]

If entry is of type 1/2 : 如果输入的类型为1/2

  • numerator = numbers[0] 分子=数字[0]
  • denomenator = numbers[1] denomenator =数字[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM