Why doesn't it output and show in red in Java?

  • 0
    Just started learning Java

    package com.company;
    
    public class Main {
    
        public static void main(String[] args) {
    
            class Square {
                Square(int i) {
                    int x =i ;
    }
            }
    
            class TestSquare {
                Square S1 = new Square(10);
                System.out.println(S1.x);
            }
        }
    }
    Java Anonymous, Oct 16, 2019

  • 4 Answers
  • 0
    One main tip can be given to the author:



    Take the resource you are currently working on, throw it out of your head and never remember it again. The code is cosmically bad, and not because you are a beginner, but because you are taught don't get it.



    Classes in Java serve for some purpose, for what purpose you create classes is completely incomprehensible, except that, as mentioned above, creating classes in main is nonsense.



    // Class declaration
    public class Test {

    // number exponentiation
    public int squareNumber(int i) {
    return i *= i;
    }

    // factorial
    public int factorial(int i) {
    return (i <= 1) ? 1 : (i * factorial(i - 1));
    }

    // main method
    public static void main(String[] args) {
    Test test = new Test(); // new instance
    System.out.println(test.squareNumber(5)); // 25
    System.out.println(test.factorial(5)); // 120
    }
    }




    Also familiarize yourself with what camelCase is, how it is done in java, and so on. This is a simple but extremely important question to understand.
    Anonymous

  • 0
    Firstly, it is better to read the very basics first than to go in with stupid questions.

    Second, edit your code by adding the
    tag


    Shl

    1. Move the variable x from the constructor to the class level

    2. There is no println8 method

    3. And in general, creating classes in the main method is a complete game
    Daphne Conner

  • 0
    Because in presumably a function
    Square (int i)
    you are assigning x = i instead of squaring i and writing the result to x.
    Anonymous

  • 0
    A normal question, not at all stupid. The question is clearly being asked by a beginner, and he has already been sprayed with toxins.

    It makes no sense to explain the error, it makes sense to advise you to review the videos on the basics of java.

    To do this: Square.x , you need to learn what the fields of the class are.
    Eliana Morse

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!