Sean
Sean

Reputation: 3450

Java Runtime Error for Calculating Area and Volume of Cylinder

I have a question. This program is supposed to receive two integers R and L (both between 1 and 1000) and calculate the area and volume of a cylinder. My problem is that I keep getting runtime errors. Here's my code:

import java.util.Scanner;
public class Main
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int radius = input.nextInt();
        Scanner input2 = new Scanner(System.in);
        int length = input2.nextInt();

        while ((radius > 1000) || (radius < 1))
        {
            input = new Scanner(System.in);
            radius = input.nextInt();
        }

        while ((length > 1000) || (length < 1))
        {
            input2 = new Scanner(System.in);
            length = input2.nextInt();
        }

        double area = (radius * radius) * 3.14159;
        double volume = area * length;

        System.out.printf("%.1f\n", area);
        System.out.printf("%.1f\n", volume);
    }
}

The error I'm getting is:

Exception in thread "main" java.util.NoSuchElementException at 
    java.util.Scanner.throwFor(Scanner.java:862) at 
    java.util.Scanner.next(Scanner.java:1485) at 
    java.util.Scanner.nextDouble(Scanner.java:2413) at
    Main.main(Main.java:10)

Upvotes: 0

Views: 147

Answers (1)

Shriyansh Gautam
Shriyansh Gautam

Reputation: 1082

Before calling netInt() on input you need to check if it has some input. Also you do not need to reinitialise input and input2 every time. In fact you should use only one input Scanner

import java.util.Scanner;
public class Main
{

 public static void main(String[] args)
 {
    Scanner input = new Scanner(System.in);
    int radius = 0;
    if(input.hasNextInt() ){
        radius = input.nextInt();
    }
    int length = 0;
    //Scanner input2 = new Scanner(System.in);
    if(input.hasNextInt() ){
        length = input.nextInt();
    }
    while ((radius > 1000) || (radius < 1))
    {
       // input = new Scanner(System.in);
        if(input.hasNextInt() ){
          radius = input.nextInt();
        }
    }

    while ((length > 1000) || (length < 1))
    {
        //input2 = new Scanner(System.in);
        if(input.hasNextInt() ){
           length = input.nextInt();
        }
    }

    double area = (radius * radius) * 3.14159;
    double volume = area * length;

    System.out.printf("%.1f\n", area);
    System.out.printf("%.1f\n", volume);
  }
}

Upvotes: 1

Related Questions