Home > Software engineering >  i want to display every number entered in my while loop.so how can i do this
i want to display every number entered in my while loop.so how can i do this

Time:05-26

must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows e.g say the user enters 3 numbers 10 12 3=25

and you must use a while loop

CodePudding user response:

Here's a function to do just that. Just call the function whenever you need.

Ex: System.out.println(parseSum("10 12 3"))25

public static int parseSum(String input) {
  // Removes spaces
  input = input.replace(" ", "");
  
  int total = 0;
  String num = "";
  int letter = 0;

  // Loop through each letter of input
  while (letter < input.length()) {
    // Checks if letter is a number
    if (input.substring(letter, letter 1).matches(".*[0-9].*")) {
      // Adds that character to String
      num  = input.charAt(letter);
    } else {
      // If the character is not a number, it turns the String to an integer and adds it to the total
      total  = Integer.valueOf(num);
      num = "";
    }
    letter  ;
  }
  total  = Integer.valueOf(num);
  return total;
}

The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?

CodePudding user response:

There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number). Please for the next time, post what you have tried and where you stuck on.

public static void main (String[] args) {
    boolean playAgain = true;
    while(playAgain) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the first number : ");
        int nb1 = sc.nextInt();
        System.out.println("Ok! I got it! Please enter the second number : ");
        int nb2 = sc.nextInt();
        System.out.println("Great! Please enter the third and last number : ");
        int nb3 = sc.nextInt();
        int sum = nb1 nb2 nb3;
        System.out.println("result==>" nb1 " " nb2 " " nb3 "=" sum);
        boolean validResponse = false;
        while(!validResponse) {
            System.out.println("Do you want to continue ? y/n");
            String response = sc.next();
            if(response.equals("n")) {
                System.out.println("Thank you! see you next time :)");
                playAgain = false;
                validResponse = true;
            } else if(response.equals("y")) {
                playAgain = true;
                validResponse = true;
            } else {
                System.out.println("Sorry, I didn't get it!");
            }
        }
    }
    
}
  • Related