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:
- Capturing the integer from the user e.g.
n in the example given below.
- Store the value of the appended result e.g.
sum in the example given below.
- 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.