2

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
  • Please give an example of what you want and what you actually get. Something like: When sum = 15, I want "6,7,8" to be printed. BTW: denada is always "". You're not updating it. Commented Jul 10, 2020 at 15:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@saka1029 - The description he has provided is, 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".. I'll wait for his comment and update the answer if required.
thanks man it was very helpful the statement sum += n was the thing i didnt knew

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.