Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Ivan Vasylynyuk
Ivan Vasylynyuk
5,510 Points

I need hint for exercise

Read numbers from keyboard and calculate their total until the user enters the word «total». Display to the screen the total.

public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int sum = 0; String number = reader.readLine(); int one = Integer.parseInt(number);

    while(number != "total") {
        sum += one;
        if(number == "total") {
            System.out.print("total is : " + sum);
            break;
        }
    }
}

}

2 Answers

There is some problem with your formatting, and I didn't try to understand all your code, but one mistake that is immediately apparent:

if(number == "total") can never be true, because in the while condition two lines above you make sure to enter that part of the code only, if number and total are different! (so they can not be the same two lines later)

La Gracchiatrice
La Gracchiatrice
4,615 Points
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Solution {
    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int sum = 0;
        do {//I use do-while loop
            System.out.print("Insert a number or write total: ");//let know the user what to do
            String number = reader.readLine();//this line has to be inside the do-while loop
            if (number.equals("total")) { //the correct method is equals not "=="
                System.out.print("total is : " + sum);
                break;
            }
            int one = Integer.parseInt(number);
            sum += one;
        } while (true);//break keyword stops the loop
    }
}