在循环中将int转换为string

Convert int to string in a loop

我想问一下如何在循环中运行时将 int 值转换为字符串假设我首先得到一个 int 值 1 运行 循环然后我得到 2 最后我想要 3值为“123”的字符串.. 你的回答会很有帮助..谢谢

int sum = 57;
            int b = 4;
            String denada;
            while(sum != 0)
            {
                int j = sum % b;
                sum = sum / b
                denada = (""+j);
            }

how to convert an int value to string

String.valueOf 函数 returns int 值的字符串表示,例如String x = String.valueOf(2) 会将 "2" 存储到 x.

lets say i got an int value 1 at first running of loop then i got 2 and then 3 in the end i want a string with value "123"

您的做法不正确。您需要以下变量:

  1. 从用户那里获取整数,例如n 在下面给出的示例中。
  2. 存储附加结果的值,例如sum 在下面给出的示例中。
  3. 捕获用户的选择,如果他想继续,例如reply 在下面给出的示例中。

按如下操作:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String reply = "Y";
        String sum = "";
        while (reply.toUpperCase().equals("Y")) {
            System.out.print("Enter an integer: ");
            int n = Integer.parseInt(scan.nextLine());
            sum += n;
            System.out.print("More numbers[Y/N]?: ");
            reply = scan.nextLine();
        }
        System.out.println("Appnded numbers: " + sum);
    }
}

一个样本运行

Enter an integer: 1
More numbers[Y/N]?: y
Enter an integer: 2
More numbers[Y/N]?: y
Enter an integer: 3
More numbers[Y/N]?: n
Appnded numbers: 123

接下来您应该尝试处理当用户提供非整数输入时可能抛出的异常。