Convert int to string in a loop

Viewed 967

I want to ask how to convert an int value to string while runing in loop 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".. your answers would be very helpful.. THANKS

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

how to convert an int value to string

String.valueOf function returns the string representation of an int value e.g. String x = String.valueOf(2) will store the "2" into 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"

Your approach is not correct. You need variables for:

  1. Capturing the integer from the user e.g. n in the example given below.
  2. Store the value of the appended result e.g. sum in the example given below.
  3. Capturing the user's choice if he wants to continue e.g. reply in the example given below.

Do it as follows:

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);
    }
}

A sample run

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

The next thing you should try is to handle the exception which may be thrown when the user provides a non-integer input.

Related