I have started java a while ago and for practice I tried to code a program which takes numbers as inputs in a loop and when the user tells the program to stop, it will display sum of all even and sum of all odd numbers. However it skipped the part where the program asks for user wether they would like to add more numbers or stop, it just kept repeating the input number again and again.

import java.util.*;
public class EvenOdd_sum{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int sum1=0;
        int sum2=0;
        boolean ch=true;
        while(ch){
            System.out.println("Enter the number:");
            int n=sc.nextInt();
            if(n%2==0){
                sum1+=n;
            }
            else{
                sum2+=n;
            }
            System.out.println("Enter yes or no for more inputs:");
            String s = sc.nextLine(); 

            if (s == "no"){
                ch=false;
            }else if(s == "yes"){
                ch=true;
            }
        }
        System.out.println("Sum of even numbers="+sum1);
        System.out.println("Sum of odd numbers="+sum2);
    }

I tried to rewrite the code but got no avail as problem persisted, even asked bard for help but even they gave the wrong answer.

0

There are 0 best solutions below