Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Basics Perfecting the Prototype Parsing Integers

David Orlow
David Orlow
1,011 Points

Type casting, what am I doing wrong?

So, the project is asking me to take a string of whatever and feed it into an integer for the answer to life. I cannot get it to compile within TreeHouse. But, I downloaded Net Beans and got it to compile. It worked just fine. What am I doing wrong on the website?

public class Main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    String answerToLife = "42";
    Integer answer;
    answer = Integer.parseInt(answerToLife);
    System.out.print(answer);
}

}

Output

JAVA_HOME="C:\Program Files\Java\jdk1.8.0_301" cd G:\My Drive\Documents\NetBeansProjects\gradleproject1; .\gradlew.bat --configure-on-demand -x check run Configuration on demand is an incubating feature.

Task :compileJava UP-TO-DATE Task :processResources NO-SOURCE Task :classes UP-TO-DATE

Task :run 42 BUILD SUCCESSFUL in 741ms 2 actionable tasks: 1 executed, 1 up-to-date

But Tree House gives me an error.

ParsingInts.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gradleproject1;

/**
 *
 * @author dmorl
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String answerToLife = "42";
        Integer answer;
        answer = Integer.parseInt(answerToLife);
        System.out.print(answer);
    }

}

2 Answers

The challenge is not expecting you to create a class. You only need to declare the variable answer and set its value.

In your code, answer is an Integer rather than an int. To make it an int variable, you could change Integer answer; to int answer;.

To create a variable with the integer data type, you use a lowercase int. If you use Integer, you are creating an Integer object, rather than a primitive variable.

    public static void main(String[] args) {
        String answerToLife = "42";
        int answer;
        answer = Integer.parseInt(answerToLife);
        System.out.print(answer);
    }