java中如何连接int值?

发布于 2024-08-29 04:58:32 字数 261 浏览 8 评论 0原文

我有以下值:

int a=1; 
int b=0;
int c=2;
int d=2;
int e=1;

如何连接这些值,以便最终得到一个 10221 的字符串; 请注意,将 a 乘以 10000、b 乘以 1000......以及 e 乘以 1 将不起作用,因为 b= 0,因此当我将这些值相加时我会丢失它。

I have the following values:

int a=1; 
int b=0;
int c=2;
int d=2;
int e=1;

How do i concatenate these values so that i end up with a String that is 10221;
please note that multiplying a by 10000, b by 1000.....and e by 1 will not working since b=0 and therefore i will lose it when i add the values up.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

难理解 2024-09-05 04:58:32

最简单(但有点肮脏)的方法:

String result = "" + a + b + c + d + e

编辑:我不推荐这个并同意乔恩的评论。添加这些额外的空字符串可能是简短和清晰度之间的最佳折衷方案。

The easiest (but somewhat dirty) way:

String result = "" + a + b + c + d + e

Edit: I don't recommend this and agree with Jon's comment. Adding those extra empty strings is probably the best compromise between shortness and clarity.

满身野味 2024-09-05 04:58:32

这对我有用。

int i = 14;
int j = 26;
int k = Integer.valueOf(String.valueOf(i) + String.valueOf(j));
System.out.println(k);

结果是1426

This worked for me.

int i = 14;
int j = 26;
int k = Integer.valueOf(String.valueOf(i) + String.valueOf(j));
System.out.println(k);

It turned out as 1426

缱绻入梦 2024-09-05 04:58:32

Michael Borgwardt 的解决方案最适合 5 位数字,但如果您的数字位数可变,则可以使用如下所示的解决方案:

public static String concatenateDigits(int... digits) {
   StringBuilder sb = new StringBuilder(digits.length);
   for (int digit : digits) {
     sb.append(digit);
   }
   return sb.toString();
}

Michael Borgwardt's solution is the best for 5 digits, but if you have variable number of digits, you can use something like this:

public static String concatenateDigits(int... digits) {
   StringBuilder sb = new StringBuilder(digits.length);
   for (int digit : digits) {
     sb.append(digit);
   }
   return sb.toString();
}
蹲墙角沉默 2024-09-05 04:58:32

只是不要忘记 format 方法

String s = String.format("%s%s%s%s%s", a, b, c, d, e);

%1.1s%1.1s%1.1s%1.1s%1.1s 如果您只想要每个数字的第一个数字...... )

just to not forget the format method

String s = String.format("%s%s%s%s%s", a, b, c, d, e);

(%1.1s%1.1s%1.1s%1.1s%1.1s if you only want the first digit of each number...)

吃→可爱长大的 2024-09-05 04:58:32

事实上,

int result = a * 10000 + b * 1000 + c * 100 + d * 10 + e;
String s = Integer.toString(result);

起作用。

注意:仅当 a 大于 0 且 bcd 和 < code>e 位于 [0, 9] 中。例如,如果 b 为 15,Michael 的方法将为您提供您可能想要的结果。

Actually,

int result = a * 10000 + b * 1000 + c * 100 + d * 10 + e;
String s = Integer.toString(result);

will work.

Note: this will only work when a is greater than 0 and all of b, c, d and e are in [0, 9]. For example, if b is 15, Michael's method will get you the result you probably want.

給妳壹絲溫柔 2024-09-05 04:58:32

根本不使用字符串怎么样...

这应该适用于任意数量的数字...

int[] nums = {1, 0, 2, 2, 1};

int retval = 0;

for (int digit : nums)
{
    retval *= 10;
    retval += digit;
}

System.out.println("Return value is: " + retval);

How about not using strings at all...

This should work for any number of digits...

int[] nums = {1, 0, 2, 2, 1};

int retval = 0;

for (int digit : nums)
{
    retval *= 10;
    retval += digit;
}

System.out.println("Return value is: " + retval);
稀香 2024-09-05 04:58:32
StringBuffer sb = new StringBuffer();
sb.append(a).append(b).append(c)...

正如其他答案所示,您最好将值保留为 int 。

StringBuffer sb = new StringBuffer();
sb.append(a).append(b).append(c)...

Keeping the values as an int is preferred thou, as the other answers show you.

帥小哥 2024-09-05 04:58:32

如果将 b 乘以 1000,您将不会丢失任何值。请参阅下面的数学。

10000
    0
  200
   20
    1
=====
10221

If you multiply b by 1000, you will not lose any of the values. See below for the math.

10000
    0
  200
   20
    1
=====
10221
極樂鬼 2024-09-05 04:58:32

其他人指出,将 b 乘以 1000 不会产生问题 - 但如果 a 为零,您最终会丢失它。 (您将得到一个 4 位数字字符串,而不是 5 位数字。)

这是另一种(通用)方法 - 假设所有值都在 0-9 范围内。 (如果事实证明情况并非如此,您很可能应该输入一些代码来抛出异常,但为了简单起见,我将其留在这里。)

public static String concatenateDigits(int... digits)
{
    char[] chars = new char[digits.length];
    for (int i = 0; i < digits.length; i++)
    {
        chars[i] = (char)(digits[i] + '0');
    }
    return new String(chars);
}

在这种情况下,您可以使用以下方式调用它:

String result = concatenateDigits(a, b, c, d, e);

Others have pointed out that multiplying b by 1000 shouldn't cause a problem - but if a were zero, you'd end up losing it. (You'd get a 4 digit string instead of 5.)

Here's an alternative (general purpose) approach - which assumes that all the values are in the range 0-9. (You should quite possibly put in some code to throw an exception if that turns out not to be true, but I've left it out here for simplicity.)

public static String concatenateDigits(int... digits)
{
    char[] chars = new char[digits.length];
    for (int i = 0; i < digits.length; i++)
    {
        chars[i] = (char)(digits[i] + '0');
    }
    return new String(chars);
}

In this case you'd call it with:

String result = concatenateDigits(a, b, c, d, e);
诗笺 2024-09-05 04:58:32

为了好玩...如何去做;-)

String s = Arrays.asList(a,b,c,d,e).toString().replaceAll("[\\[\\], ]", "");

在这种情况下,并不是有人真的会考虑这样做 - 但是这说明了为什么授予对某些对象成员的访问权限很重要,否则 API 用户最终会解析对象的字符串表示形式,然后您将无法修改它,或者如果您这样做,则可能会破坏他们的代码。

For fun... how NOT to do it ;-)

String s = Arrays.asList(a,b,c,d,e).toString().replaceAll("[\\[\\], ]", "");

Not that anyone would really think of doing it this way in this case - but this illustrates why it's important to give access to certain object members, otherwise API users end up parsing the string representation of your object, and then you're stuck not being able to modify it, or risk breaking their code if you do.

强辩 2024-09-05 04:58:32

使用 Java 8 及更高版本,您可以使用 StringJoiner< /a>,一种非常干净且更灵活的方式(特别是如果您有一个列表作为输入而不是已知的一组变量 ae):

int a = 1;
int b = 0;
int c = 2;
int d = 2;
int e = 1;
List<Integer> values = Arrays.asList(a, b, c, d, e);
String result = values.stream().map(i -> i.toString()).collect(Collectors.joining());
System.out.println(result);

如果您需要分隔符,请使用:

String result = values.stream().map(i -> i.toString()).collect(Collectors.joining(","));

要获得以下结果:

1,0,2,2,1

编辑:正如 LuCio 所评论的,以下代码更短:

Stream.of(a, b, c, d, e).map(Object::toString).collect(Collectors.joining());

Using Java 8 and higher, you can use the StringJoiner, a very clean and more flexible way (especially if you have a list as input instead of known set of variables a-e):

int a = 1;
int b = 0;
int c = 2;
int d = 2;
int e = 1;
List<Integer> values = Arrays.asList(a, b, c, d, e);
String result = values.stream().map(i -> i.toString()).collect(Collectors.joining());
System.out.println(result);

If you need a separator use:

String result = values.stream().map(i -> i.toString()).collect(Collectors.joining(","));

To get the following result:

1,0,2,2,1

Edit: as LuCio commented, the following code is shorter:

Stream.of(a, b, c, d, e).map(Object::toString).collect(Collectors.joining());
り繁华旳梦境 2024-09-05 04:58:32
int number =0;
int[] tab = {your numbers}.

for(int i=0; i<tab.length; i++){
    number*=10;
    number+=tab[i];
}

你有你的串联号码。

int number =0;
int[] tab = {your numbers}.

for(int i=0; i<tab.length; i++){
    number*=10;
    number+=tab[i];
}

And you have your concatenated number.

沧笙踏歌 2024-09-05 04:58:32

我建议将它们转换为字符串。

StringBuilder concatenated = new StringBuilder();
concatenated.append(a);
concatenated.append(b);
/// etc...
concatenated.append(e);

然后转换回整数:

Integer.valueOf(concatenated.toString());

I would suggest converting them to Strings.

StringBuilder concatenated = new StringBuilder();
concatenated.append(a);
concatenated.append(b);
/// etc...
concatenated.append(e);

Then converting back to an Integer:

Integer.valueOf(concatenated.toString());
顾北清歌寒 2024-09-05 04:58:32

使用字符串生成器

StringBuilder sb = new StringBuilder(String.valueOf(a));
sb.append(String.valueOf(b));
sb.append(String.valueOf(c));
sb.append(String.valueOf(d));
sb.append(String.valueOf(e));
System.out.print(sb.toString());

Use StringBuilder

StringBuilder sb = new StringBuilder(String.valueOf(a));
sb.append(String.valueOf(b));
sb.append(String.valueOf(c));
sb.append(String.valueOf(d));
sb.append(String.valueOf(e));
System.out.print(sb.toString());
笑脸一如从前 2024-09-05 04:58:32

人们担心当 a == 0 时会发生什么。很容易解决这个问题......在它前面加一个数字。 :)

int sum = 100000 + a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.valueOf(sum).substring(1));

最大的缺点:它创建了两个字符串。如果这是一个大问题,String.format 可以提供帮助。

int sum = a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.format("%05d", sum));

People were fretting over what happens when a == 0. Easy fix for that...have a digit before it. :)

int sum = 100000 + a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.valueOf(sum).substring(1));

Biggest drawback: it creates two strings. If that's a big deal, String.format could help.

int sum = a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.format("%05d", sum));
魔法唧唧 2024-09-05 04:58:32

你可以使用

String x = a+"" +b +""+ c+""+d+""+ e;
int result = Integer.parseInt(x);

You can Use

String x = a+"" +b +""+ c+""+d+""+ e;
int result = Integer.parseInt(x);
淡水深流 2024-09-05 04:58:32

假设您从变量开始:

int i=12;
int j=12;

这将给出输出 1212

System.out.print(i+""+j); 

这将给出输出 24

System.out.print(i+j);

Assuming you start with variables:

int i=12;
int j=12;

This will give output 1212:

System.out.print(i+""+j); 

And this will give output 24:

System.out.print(i+j);
陌伤浅笑 2024-09-05 04:58:32

最佳解决方案已经讨论过。
无论如何,你也可以这样做:
鉴于您总是处理 5 位数字,

(new java.util.Formatter().format("%d%d%d%d%d", a,b,c,d,e)).toString()

我并不是说这是最好的方法;只是添加一种替代方法来查看类似情况。 :)

Best solutions are already discussed.
For the heck of it, you could do this as well:
Given that you are always dealing with 5 digits,

(new java.util.Formatter().format("%d%d%d%d%d", a,b,c,d,e)).toString()

I am not claiming this is the best way; just adding an alternate way to look at similar situations. :)

岁月流歌 2024-09-05 04:58:32

注意:当您尝试在 (string + int) 上使用 + 运算符时,它会将 int 转换为字符串,并且
连接它们!
所以你只需要将一个 int 转换为 string

public class scratch {

public static void main(String[] args){

    int a=1;
    int b=0;
    int c=2;
    int d=2;
    int e=1;
    System.out.println( String.valueOf(a)+b+c+d+e) ;
}

NOTE: when you try to use + operator on (string + int) it converts int into strings and
concatnates them !
so you need to convert only one int to string

public class scratch {

public static void main(String[] args){

    int a=1;
    int b=0;
    int c=2;
    int d=2;
    int e=1;
    System.out.println( String.valueOf(a)+b+c+d+e) ;
}
别把无礼当个性 2024-09-05 04:58:32
//Here is the simplest way 
public class ConcatInteger{
    public static void main(String[] args) {
      
      int [] list1={1,2,3};
      int [] list2={1,9,6};
      
      String stNum1="";
      String stNum2="";
   
      for(int i=0 ; i<3 ;i++){
        stNum1=stNum1+Integer.toString(list2[i]);   //Concat done with string  
      }
      
      for(int i=0 ; i<3 ;i++){
        stNum2=stNum2+Integer.toString(list1[i]);
      }
      
      int sum= Integer.parseInt(stNum1)+Integer.parseInt(stNum2); // Converting string to int
      
         System.out.println(sum);  
    } 
}
//Here is the simplest way 
public class ConcatInteger{
    public static void main(String[] args) {
      
      int [] list1={1,2,3};
      int [] list2={1,9,6};
      
      String stNum1="";
      String stNum2="";
   
      for(int i=0 ; i<3 ;i++){
        stNum1=stNum1+Integer.toString(list2[i]);   //Concat done with string  
      }
      
      for(int i=0 ; i<3 ;i++){
        stNum2=stNum2+Integer.toString(list1[i]);
      }
      
      int sum= Integer.parseInt(stNum1)+Integer.parseInt(stNum2); // Converting string to int
      
         System.out.println(sum);  
    } 
}
浪推晚风 2024-09-05 04:58:32

难道你不能直接创建数字字符串,连接它们,然后将字符串转换为整数值吗?

Couldn't you just make the numbers strings, concatenate them, and convert the strings to an integer value?

予囚 2024-09-05 04:58:32
public class joining {

    public static void main(String[] args) {
        int a=1; 
        int b=0;
        int c=2;
        int d=2;
        int e=1;

        String j = Long.toString(a);
        String k = Long.toString(b);
        String l = Long.toString(c);
        String m = Long.toString(d);
        String n = Long.toString(e);

       /* String s1=Long.toString(a);    // converting long to String
        String s2=Long.toString(b);
        String s3=s2+s1;
        long c=Long.valueOf(s3).longValue();    // converting String to long
        */

        System.out.println(j+k+l+m+n);  
    }
}
public class joining {

    public static void main(String[] args) {
        int a=1; 
        int b=0;
        int c=2;
        int d=2;
        int e=1;

        String j = Long.toString(a);
        String k = Long.toString(b);
        String l = Long.toString(c);
        String m = Long.toString(d);
        String n = Long.toString(e);

       /* String s1=Long.toString(a);    // converting long to String
        String s2=Long.toString(b);
        String s3=s2+s1;
        long c=Long.valueOf(s3).longValue();    // converting String to long
        */

        System.out.println(j+k+l+m+n);  
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文