Joey Clark
Joey Clark

Reputation: 69

Skipped Code causing program to end early

I am currently trying to create a volume, Area, Surface Area, and perimeter calculator but I have run into little problem

package Volume;

public class C {
  static double r;
  static double h;

    static double volume() {
      return (25/7.957747154)*(r*r)*h;
    }

}

The data Class

package Volume;

import java.io.IOException;
import java.util.Scanner;

public class VC {
  public static void main(String args[]) 
    throws IOException {
      char s2;  
      char s1;
      Scanner first = new Scanner(System.in);
      Scanner second = new Scanner(System.in);
      a: {
      System.out.println("Chose your Type: \n1.Volume \n2.Area \n3.Surface Area \n4.Perimeter \n5.Exit \nPlease type the number of your option.");
      s1 = (char) System.in.read();
      switch(s1) {
        case '1':
        System.out.println("Chose Your Shape: \n1.Cylinder \ntype the number");
        s2 = (char) System.in.read();
        switch(s2) {
          case '1': 
          System.out.println("Raidius?");
          Volume.C.r = first.nextDouble();
          System.out.println("Height?");
          Volume.C.h = second.nextDouble();
          Double v;
          v = Volume.C.volume();
          System.out.println("The Volume is:" + v);
          break a;
       }
       case '5':
       System.out.println("GoodBye");
     }
   }
 }
}

The Main Class

The problem I run into is after I finish the first switch statement instead of pausing to read the char it skips that whole block and goes to case '5': ending the program before anything is done.

Could someone please explain this to me?

Upvotes: 0

Views: 112

Answers (1)

MByD
MByD

Reputation: 137382

IO buffering is a source to many problems, I would suggest that you:

  1. Access System.in only through a Scanner (e.g. no System.in.read)
  2. Create only a single Scanner for he same stream (e.g., only first, no second)

Some more explanation:

You are accessing the standard input stream (e.g. the user input) through 3 different objects:

  • first - System.in wrapped by Scanner
  • second - System.in wrapped by Scanner
  • Directly in some places, for example s2 = (char) System.in.read();

Instead, create only one Scanner and use it for all the reads from System.in

Upvotes: 1

Related Questions