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! While you're at it, check out some resources Treehouse students have shared here.

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


Allen C
Allen C
1,448 Points

I can't declare a string in IntelliJ IDEA

As the title says, I can't declare the String datatype. It doesn't even turn blue like the other datatypes.


This is the current code:

import java.util.Scanner;
public class Example {

    public static void main(String[] args) {
        Scanner user = new Scanner(System.in);
        int numberOfItems;

        String merchandise;
        double payment;
        double tax = 0.13;
        double purchasePrice;
        double total= 0;
        double change= 0;
        double beforeTaxPrice = 0;
        int counter = 0;

        System.out.println("Please enter the number of items you have: ");
        numberOfItems = user.nextInt();

        while (counter < numberOfItems){
            System.out.println("Please enter the item purchased: ");
            merchandise = user.nextLine();

            System.out.println("Please enter the item price: ");
            purchasePrice = user.nextDouble();

            beforeTaxPrice += purchasePrice;
            counter += 1;
        total = beforeTaxPrice + beforeTaxPrice*tax;

        System.out.println("Your total is: " + total);

When I run the program, it works fine until the while loop; which it prints both:

Please enter the item purchased: and Please enter the item price:

at the same time. How do I avoid that error?

Thanks in advance!

Edit: it doesn't seem to work here either, so I'm pretty sure I'm doing something wrong, i just don't know what :-/

2 Answers

Allen C
Allen C
1,448 Points

I found the answer to both problems. Regarding the String not being formatted specially, that's because only primitive types are formatted in that blue bold colour. It still works as it's supposed to.

Regarding both Please enter the item purchased: and Please enter the item price: being printed at the same time, that is because that the nextDouble(); does not consume the last /newline, therefore, you should add an additional line calling nextLine(), inbetween the nextLine() and nextDouble().

Normally you are supposed to set local String variables equal to something; so try doing this:

String merchandise = "";

See if that helps you.