简体   繁体   中英

Two lines of my System.out.println code do not work and I cannot figure out why

I recently made a simple calculator that calculates the perimeter and area of a rectangle when you give it the measurements of two sides. However, two of my lines of System.out.println are not working. How can I fix this?

Here is the code:

import java.util.Scanner;

class Rectangle
{
    static int n;
    static int m;
    Scanner s= new Scanner(System.in);
//The below two System.out.println lines do not work. How do I fix this?
    System.out.println("Enter the width:")
    n = s.nextInt();
    System.out.println("Enter the length:");
    m = s.nextInt();
    public static void main(String args[])
    {
        int Area;
        Area=n*m;
        System.out.println("Area = " + Area);
        return;
    }
    private static int solvePerimeter;
    {   
        int Perimeter; 
        Perimeter = 2*(m+n);
        System.out.println("Perimeter = " + Perimeter);

Print statements should be inside a function.
Change your code to:

import java.util.Scanner;

class Rectangle
{
    static int n;
    static int m;
    public static void main(String args[])
    {
    Scanner s= new Scanner(System.in);
    System.out.println("Enter the width:")
    n = s.nextInt();
    System.out.println("Enter the length:");
    m = s.nextInt();
    }

You also need to declare two separate functions for area and perimeter and call from main method.

Your System.out.println("Enter the width:"); should be inside a method. Other than any variable declaration, everything should be inside methods.

import java.util.Scanner;

class Rectangle
{
    static int n;
    static int m;

    Scanner s= new Scanner(System.in);
//The below two System.out.println lines do not work. How do I fix this?
    public void readArguments() {
       System.out.println("Enter the width:");
       n = s.nextInt();
       System.out.println("Enter the length:");
       m = s.nextInt();
   }

    public static void main(String args[])
    {
        int Area;
        readArguments();
        Area=n*m;
        System.out.println("Area = " + Area);
        return;
    }
    private static int solvePerimeter;
    {   
        int Perimeter; 
        Perimeter = 2*(m+n);
        System.out.println("Perimeter = " + Perimeter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM