In this first assignment I have to have the user input some number (ex: 312) then add each number and output something like: "The numbers are 3 1 2 with the sum of 6." Here are the codes:
public static void main(String[] args) {
int Max_Size = 30;
char[] myArray = new char [Max_Size];
String temp = " ";
char parse;
int sum = 0;
int counter = 0;
System.out.print("Please enter a non-negative integer: ");
try{
BufferedReader dataIn = new BufferedReader(
new InputStreamReader(System.in));
temp = dataIn.readLine();
} catch (IOException e) {
System.out.println("Error!");
}
System.out.print("The numbers are ");
//put each character of the string into a char array
for (int i = 0; i < temp.length(); i++){
myArray[i] = temp.charAt(i);
System.out.print(myArray[i] + " ");
}
//take sum of each character as an integer
while (counter != temp.length()){
sum = sum + (myArray[counter] - '0');
counter++;
}
System.out.println("with the sum of " + sum);
}
Here is a sample run:
Please enter a non-negative integer:
312
The numbers are 3 1 2 with the sum of 6
BUILD SUCCESSFUL (total time: 7 seconds)
HOW DO I HAVE IT SO A NEW LINE ISN'T PLACED FOR THE INPUT: 312 ? Meaning I want it so it is like "Please enter a non-negative integer: 312", with the 312 in the same line. Also, is there a better way to parse the input into integers and put it into an integer array?