0

All I need it to do is loop again so the user can continuously use the program if they to. Let me know if there are any reference that I can read up to, to help me understand more about this problem. Thanks in advance.

import java.util.Scanner;

public class Module3Assignment1 {

    // public variables
    public static String letterChosen;
    public static int loop = 0;
    public static double radius, area;
    public static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {

        // tells user what the program is about
        System.out.println("Welcome to the Round Object Calculator");
        System.out.println("This program will calculate the area of a circle of the colume of a sphere.");
        System.out.println("The calculations will be based on the user input radius.");
        System.out.println("");

            // loops while the user wants to calculate information
            while (loop == 0){

                Input();
                System.out.print(Answer());

                System.out.println("Do you want to calculate another round object (Y/N)? ");
                String input = scanner.next().toUpperCase();
                    if (input == "N"){
                        loop = 1;
                        }
            }

        // ending message/goodbye
        Goodbye();
        scanner.close();

    }

    private static void Input(){

        // prompts user for input
        System.out.print("Enter C for circle or S for sphere: ");
        letterChosen = scanner.nextLine().toUpperCase();
        System.out.print("Thank you. What is the radius of the circle (in inches): ");
        radius = scanner.nextDouble();

    }

    private static double AreaCircle(){

        // calculates the area of a circle
        area = Math.PI * Math.pow(radius, 2);
        return area;

    }

    private static double AreaSphere(){

        // calculates the area of a sphere
        area = (4/3) * (Math.PI * Math.pow(radius, 3));
        return area;

    }

    private static String Answer(){

        //local variables
        String answer;

        if(letterChosen == "C"){
            // builds a string with the circle answer and sends it back
            answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", AreaCircle(), "inches");
            return answer;
        }else{
            // builds a string with the sphere answer and sends it back
            answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", AreaSphere(), "cubic inches");
            return answer;
        }
    }

    private static String Goodbye(){

        // local variables
        String goodbye;

        // says and returns the goodbye message
        goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye");
        return goodbye;
    }

}

The below is the console output and the error I am getting after execution

Welcome to the Round Object Calculator
This program will calculate the area of a circle of the colume of a sphere.
The calculations will be based on the user input radius.

Enter C for circle or S for sphere: C
Thank you. What is the radius of the circle (in inches): 12
The volume of a sphere with a radius of 12.000000 inches is: 5428.672 cubic inches 
Do you want to calculate another round object (Y/N)? 
Y
Enter C for circle or S for sphere: Thank you. What is the radius of the circle (in inches): C
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextDouble(Scanner.java:2387)
    at Module3Assignment1.Input(Module3Assignment1.java:48)
    at Module3Assignment1.main(Module3Assignment1.java:24)
Kalyan Chavali
  • 1,330
  • 8
  • 24
Lea
  • 97
  • 2
  • 14
  • Read http://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html – Sneh Jul 08 '15 at 10:19
  • What is **exactly** your problem? What happens? What do you **want** to happen? Can you provide example fo failure? – TDG Jul 08 '15 at 10:19
  • Kind of dangerous to include calls to `nextLine()` in with calls to `next()` or `nextDouble()` on the same Scanner. I'd probably replace `nextLine()` with `next()` and see if that helps. Your error actually means that your Scanner is encountering letters where it expects numbers. – Dawood ibn Kareem Jul 08 '15 at 10:25

2 Answers2

0

Concept One

Always use .equals Method while Comparing String in Java

So

if(letterChosen == "C")

Should be if(letterChosen.equals("C")) and so the Others

Concept Two.

This might be one of the reason that is happening with your code . You have already taken a UserInput from the keyboard object of the scanner class that's why it's giving the else response. This particularly happens when you take other than String input from that object

Thats because the Scanner#nextDouble method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine.

WorkAround Fire a blank Scanner#nextLine call after Scanner#nextDouble to consume newline.

Or Use Two Scanner Object.

Demo What Happens With Same Scanner Object for Both nextLine() and nextInt()

public class Test {

    public static void main(String[] args) {
        Scanner keyboard= new Scanner(System.in);
        int n=keyboard.nextInt();

        String userResponse;
        while(true) {
            userResponse = keyboard.nextLine();
            if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
                System.out.println("Great! Let's get started.");
                break;
            }
            else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
                System.out.println("Come back next time " + "" + ".");
                System.exit(0);
            }
            else {
                System.out.println("Invalid response.");
            }
        }
    }

} 

Output

5
Invalid response.

now change the code structure to get String Input from that scanner Object and not get another kind of data types the code works.

With String as previous Input

public class Test {

    public static void main(String[] args) {
        Scanner keyboard= new Scanner(System.in);
        String n=keyboard.nextLine();
        String userResponse;
        while(true) {
            userResponse = keyboard.nextLine();
            if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
                System.out.println("Great! Let's get started.");
                break;
            }
            else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
                System.out.println("Come back next time " + "" + ".");
                System.exit(0);
            }
            else {
                System.out.println("Invalid response.");
            }
        }
    }

}

Output

j
y
Great! Let's get started.

Without any previous response with that object your code will work.

public class Test {

    public static void main(String[] args) {
        Scanner keyboard= new Scanner(System.in);

        String userResponse;
        while(true) {
            userResponse = keyboard.nextLine();
            if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
                System.out.println("Great! Let's get started.");
                break;
            }
            else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
                System.out.println("Come back next time " + "" + ".");
                System.exit(0);
            }
            else {
                System.out.println("Invalid response.");
            }
        }
    }

}

and Gives me the desired output

y
Great! Let's get started.

I usually have been doing this whole time creating two OBJECT of Scanner Class one to get String Input and other to get other data types Input (Too be frank even i have been not able to figure out why i needed to create two Object's for receiving String and Other data types in java without any error. If anyone know please let me know )

Ankur Anand
  • 3,873
  • 2
  • 23
  • 44
0
import java.util.Scanner;

public class Module3Assignment1 {
// public static variables are discouraged... 
private static char letterChosen; //char takes less memory 
private static char useAgain = 'Y'; //just use the answer to loop... 
private static double radius, area;
private static String answer;
private  static Scanner scanner = new Scanner(System.in);


//you might want to clear the screen after the user gave an answer to another round object
private static void clearScreen(){
    for(int i =0;i<50;i++){System.out.print("\n");}
}

public void input(){

    // prompts user for input
    System.out.print("Enter C for circle or S for sphere: ");
    letterChosen = scanner.next().charAt(0);
    System.out.print("Thank you. What is the radius of the circle (in inches): ");
    radius = scanner.nextDouble();
    this.answer= answer(letterChosen);

}

public double areaCircle(double radius){

    // calculates the area of a circle
    area = Math.PI * Math.pow(radius, 2);
    return area;

}

public double areaSphere(double radius){

    // calculates the area of a sphere
    area = (4/3) * (Math.PI * Math.pow(radius, 3));
    return area;

}

public String answer(char letterChosen){

    //local variables
    String answer = "";
    if(letterChosen=='c'||letterChosen=='C'){
        answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", areaCircle(radius), "inches");
    }else{
        answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", areaSphere(radius), "cubic inches");
    }
    return answer;
}

private static String goodbye(){

    // local variables
    String goodbye;

    // says and returns the goodbye message
    goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye");
    return goodbye;
}

public static void main(String[] args) {

    // tells user what the program is about
    System.out.println("Welcome to the Round Object Calculator");
    System.out.println("This program will calculate the area of a circle of the colume of a sphere.");
    System.out.println("The calculations will be based on the user input radius.");
    System.out.println("");
    Module3Assignment1 ass1 = new Module3Assignment1();

        // loops while the user wants to calculate a round object
        while (useAgain == 'Y'||useAgain=='y'){

            ass1.input();
            System.out.print(answer);
            System.out.println("Do you want to calculate another round object (Y/N)? ");
            useAgain = scanner.next().charAt(0);
            System.out.println(useAgain);
            clearScreen();
        }

    // ending message/goodbye
    System.out.println(goodbye());
    scanner.close();

}

}

Some things that I changed:

  • I used char instead of String. String takes up more memory than char.
  • added clearScreen() method which "clears" the screen when you're using console.
  • I added a parameter radius to areaSphere and areaCircle methods. This makes the methods reusable.

  • I changed all the public static variables to private static. using public static variables is HIGHLY DISCOURAGED. You may read this to find out why.

  • and to prevent public static variables, I created an instance of Module3Assignment1 instead of having everything in static.

  • changed the casing of method names. Please follow camel-casing, which means that the first letter of the method is lowercase and the other words will have the first letter in uppercase (e.g. input(), areaSphere() )

A comment about comparing Strings:

== compares REFERENCES TO THE OBJECT , NOT VALUES

use .equals() or .equalsIgnoreCase() if you want to compare the values of two Strings. here is a sample syntax:

if(string1.equals(string2)){
//do something
}
Community
  • 1
  • 1
triForce420
  • 719
  • 12
  • 31