Reputation: 27
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);
Upvotes: 0
Views: 41
Reputation: 391
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);
Upvotes: 0
Reputation: 420
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.
Upvotes: 1