in java, Ask the user for a bunch of integers. Show the sum of those numbers.
Make your program handle strange input. Specifically, if they didn't enter a number, scan the String to find just the digits and piece those digits together to form a number.
If the user enters something without any digits, end the program.
input:
5ENTER
10ENTER
endENTER
output:
Enter a integer\n Current sum: 5\n Enter a integer\n Current sum: 15\n Enter a integer\n There were no digits in that input.\n Final sum: 15\n
input
5ENTER xxx4xxxENTER z
output:
Enter a integer\n Current sum: 5\n Enter a integer\n Well, that's not a number but here's what I extracted: 4\n Current sum: 9\n Enter a integer\n There were no digits in that input.\n Final sum: 9\n
input
,,4gg3ENTER g6g7g8re7ENTER 2gfENTER jh3ENTER dfd4f5fENTER ff21ENTER ********1x2e3errr4ww5ddd6ENTER g
output:
Enter a integer\n Well, that's not a number but here's what I extracted: 43\n Current sum: 43\n Enter a integer\n Well, that's not a number but here's what I extracted: 6787\n Current sum: 6830\n Enter a integer\n Well, that's not a number but here's what I extracted: 2\n Current sum: 6832\n Enter a integer\n Well, that's not a number but here's what I extracted: 3\n Current sum: 6835\n Enter a integer\n Well, that's not a number but here's what I extracted: 45\n Current sum: 6880\n Enter a integer\n Well, that's not a number but here's what I extracted: 21\n Current sum: 6901\n Enter a integer\n Well, that's not a number but here's what I extracted: 123456\n Current sum: 130357\n Enter a integer\n There were no digits in that input.\n Final sum: 130357\n
Given below is the code for question. Please do rate the answer
if it helped. Thank you.
import java.util.Scanner;
public class SumNumbers {
public static void main(String[] args) {
Scanner keyboard = new
Scanner(System.in);
String str;
int sum = 0;
while(true) {
System.out.print("Enter an integer: ");
if(keyboard.hasNextInt())
sum += keyboard.nextInt();
else {
str = keyboard.next();
str = extractDigits(str);
if(str.equals("")) {
System.out.println("There
were no digits in that input.");
break;
}
else {
System.out.println("Well,
that's not a number but here's what I extracted: " + str);
sum +=
Integer.parseInt(str);
}
System.out.println("Current sum: " + sum);
}
}
System.out.println("Final sum: " +
sum);
}
private static String extractDigits(String s) {
String digits = "";
for(int i = 0; i < s.length();
i++) {
char c =
s.charAt(i);
if(Character.isDigit(c))
digits += c;
}
return digits;
}
}
Get Answers For Free
Most questions answered within 1 hours.