如何为多个变量分配一个值

时间:2022-05-18 19:33:24

I want to receive one value, which represents multiple variables. for example I receive 110200john This value goes directly without any code to multiple variables like

我想收到一个代表多个变量的值。例如,我收到110200john这个值直接没有任何代码到多个变量,如

int x = 11
double y = 0200
string name = john

How can I do that ?

我怎样才能做到这一点 ?

Can I use enum

我可以使用枚举吗?

enum data {
 int x ;
double y ;
string name ;

}

Also I am receiving the value in byte format.

此外,我收到字节格式的值。

Thank you for your help guys

谢谢你的帮助

1 个解决方案

#1


You should almost certainly create a class to represent those three values together, if they're meaningful. I'd personally then write a static parse method. So something like:

如果它们有意义,你几乎肯定会创建一个类来表示这三个值。我个人然后编写一个静态解析方法。所以类似于:

public final class Person {
    private final int x;
    private final double y;
    private final String name;

    public Person(int x, double y, String name) {
        this.x = x;
        this.y = y;
        this.name = name;
    }

    public static Person parse(String text) {
        int x = Integer.parseInt(text.substring(0, 2));
        double y = Double.parseDouble(text.substring(2, 6));
        String name = text.substring(6);
        return Person(x, y, name);
    }

    // TODO: Getters or whatever is required
}

This assumes that the format of your string is always xxyyyyname - basically you should adjust the parse method to suit, using substring and the various other parse methods available.

这假设你的字符串的格式总是xxyyyyname - 基本上你应该调整parse方法以适应,使用substring和各种其他可用的解析方法。

#1


You should almost certainly create a class to represent those three values together, if they're meaningful. I'd personally then write a static parse method. So something like:

如果它们有意义,你几乎肯定会创建一个类来表示这三个值。我个人然后编写一个静态解析方法。所以类似于:

public final class Person {
    private final int x;
    private final double y;
    private final String name;

    public Person(int x, double y, String name) {
        this.x = x;
        this.y = y;
        this.name = name;
    }

    public static Person parse(String text) {
        int x = Integer.parseInt(text.substring(0, 2));
        double y = Double.parseDouble(text.substring(2, 6));
        String name = text.substring(6);
        return Person(x, y, name);
    }

    // TODO: Getters or whatever is required
}

This assumes that the format of your string is always xxyyyyname - basically you should adjust the parse method to suit, using substring and the various other parse methods available.

这假设你的字符串的格式总是xxyyyyname - 基本上你应该调整parse方法以适应,使用substring和各种其他可用的解析方法。