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)
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
}
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 )
Related
I got a task, where I have to calculate the perimeter and area of a given object, that's determined by the user, with accompanying data - side length, radius, etc. To do this I have to do a "GUI" as my teacher said, and to do that, I have to use the Scanner.
Everytime I try to do the second scan, after the user has choosen what object we are dealing with, when it gets to the part, where the user's supposed to input their data about their object, it always crashes, with a java.util.NoSuchElementException error, according to NetBeans. I looked through it, and even copied in the working scanner, but to no avail.
Here's the full code:
package Methods2;
import java.util.Scanner;
public class Methods2 {
public static void main(String[] args) {
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
input1.close();
//decision
if (decider == 1) {
circle();
} else if (decider == 2) {
square();
} else if (decider == 3) {
rectangle();
} else {
System.out.println("There aren't any other options, other than these three.");
}
}
public static void circle() {
//method specific initialization
int radius;
double pi;
double perimeter;
double area;
Scanner input2;
//define
pi = 3.14;
input2 = new Scanner(System.in);
System.out.println("Please type in the radius of the circle!");
radius = input2.nextInt(); //these are where my problem's lie
input2.close();
//calculate
perimeter = 2 * radius * pi;
area = radius * radius * pi;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void square() {
//method specific initialization
int a;
int perimeter;
int area;
Scanner input3;
//define
input3 = new Scanner(System.in);
System.out.println("Please type in one side's length of the square!");
a = input3.nextInt(); //these are where my problem's lie
input3.close();
//calculate
perimeter = 4 * a;
area = a * a;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void rectangle() {
//method specific initialization
int a;
int b;
int perimeter;
int area;
Scanner input4;
//define
input4 = new Scanner(System.in);
System.out.println("Please type in one of the sides' length of the rectangle!");
a = input4.nextInt(); //these are where my problem's lie
System.out.println("Now type the other, non-equal side, compared to the previous one!");
b = input4.nextInt(); //these are where my problem's lie
input4.close();
//calculate
perimeter = 2 * (a + b);
area = a * b;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
}
I have thought about it being multiple Scanner's, but after I realized, that variables don't carry over between methods, unless they're defined within the class, that was swiftly thrown out as a theory. Also, NetBeans didn't mark any problems with that line, so it made even less sense to me.
The reason why your code is "stopping" the scanner, is because you added input1.close();. What .close() does, is that it closes the scanner. Once a scanner is closed, you won't be able to open it again. According to your code, you use the Scanner.. even after it was closed. So to fix your problem, removed the line:
input1.close();
Here is a close up of where you should remove the line:
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
//input1.close(); REMOVE THIS LINE
I have to write a program that calculates the shipping cost for something being sent in the mail.
Here are some specifications and what a practice run should look like:
Calculations:
Use: Ship Method Cost
Overnight $5 * weight
Two Day $2 * weight
Economy $1 * weight (yes, that's just = weight)
Data Validation On this program, you'll also need to perform some validation in the main method. Specifically:
The item description must not be empty.
The item weight must be > 0.
The shipping method must be either O, T or E. The program should accept either lower or uppercase equivalents.
Sample Runs:
Be sure to end your output with a println.
Run #1: No item description entered:
Enter item description:
<-- user hits enter key but doesn't enter item description
Invalid description. Program cannot continue
Run #2: Invalid item weight entered:
Enter item description:
A big box <-- user enters valid description
Enter item weight in lbs:
-5 <-- user enters invalid weight
Invalid shipping weight. Program cannot continue
Run #3: Invalid shipping method entered:
Enter item description:
A big box
Enter item weight in lbs:
3.5
How fast would you like to ship your package:
(O)vernight
(T)wo Days
(E)conomy (may take up to 7 days)
Choose an option: P
Invalid shipping method. Program cannot continue
Run #4: Invoice Generated
Enter item description:
A big box
Enter item weight in lbs:
3.5
How fast would you like to ship your package:
(O)vernight
(T)wo Days
(E)conomy (may take up to 7 days)
Choose an option: o
*** WE SHIP INVOICE ***
Item Description: A big box
Item Weight: 3.50
Ship Method: O
Total Cost: $17.50
Decomposition
You must use the decomposition provided below. For maximum sanity, remember to build and test one method at a time in development mode. Two of these methods have already been written for you and supplied as part of you code template for this exercise.
Use: double getWallHeight(Scanner scnr) - This method is called from the main method. It accepts the scanner as a parameter, prompts the user for the wall height and returns the value entered by the user to the main method.
Use: double getWallWidth(Scanner scnr) - This method is called from the main method. It accepts the scanner as a parameter, prompts the user for the wall height and returns the value entered by the user to the main method.
Use: double calcWallArea(double wallHeight, double wallWidth) - This method is called from the main method. It accepts the wallHeight and wallWidth and calculates the wall area in square feet.
Use: double calcGallons(double wallArea) - This method is called from the main method. It accepts the wall area and determines how much paint is need to paint the entire room.
Use: void displayResults(double wallArea, double gallonsPaintNeeded) - This method is called from the main method. It accepts the wallArea and the amount of paint needed to paint the room. It displays the results to the user including the walk area and the number of paint cans needed to be purchased as an integer.
Here is my code:
import java.util.*;
import java.util.Scanner;
public class WeShipIt {
public static final int OVERNIGHT_CHARGE = 5;
public static final int TWO_DAY_CHARGE = 2;
public static final int ECONOMY_CHARGE = 1;
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in); //scanner object to pass around
double weight;
String itemDescription;
char shipMethod;
double shippingCost;
itemDescription = getitemDescription(keyboard);
weight = getShipWeight(keyboard);
shipMethod = getShipClass(keyboard);
shippingCost = calculateShipping(shipMethod, weight);
if (itemDescription.length() == 0){
System.out.println("Invalid description. Program cannot continue");
System.exit(0);
} else {
getShipWeight(keyboard);
if (weight <= 0){
System.out.println("Invalid shipping weight. Program cannot continue");
} else {
getShipClass(keyboard);
if (!(shipMethod == 'O' || shipMethod == 'T' || shipMethod == 'E')){
System.out.println("Invalid shipping method. Program cannot continue");
} else {
displayResults(itemDescription, weight, shipMethod, shippingCost);
}
}
}
}
//get item description
public static String getitemDescription(Scanner keyboard){
System.out.println("Enter item description:");
String itemDescription = keyboard.next();
return itemDescription;
}
//get item weight
public static double getShipWeight(Scanner console){
System.out.println("Enter item weight in lbs:");
double itemWeight = console.nextDouble();
return itemWeight;
}
//get user's choice for shipping method and return it
public static char getShipClass(Scanner keyboard) {
char shipMethod;
//get shipping method
System.out.println();
System.out.println("How would you like to ship your package:");
System.out.println("(O)vernight");
System.out.println("(T)wo Days");
System.out.println("(E)conomy (may take up to 7 days)");
System.out.println("Choose an option: ");
shipMethod = keyboard.next().charAt(0); //Prof. Dan says leave this line in here. Will explain in
class.
shipMethod = Character.toUpperCase(shipMethod);
return shipMethod;
}
//calculate and return shipping charge
public static double calculateShipping(char shipMethod, double weight){
double shipCharge;
if (shipMethod == 'O') {
shipCharge = weight * OVERNIGHT_CHARGE;
}
else if (shipMethod == 'T') {
shipCharge = weight * TWO_DAY_CHARGE;
}
else if (shipMethod == 'E') {
shipCharge = weight * ECONOMY_CHARGE;
} else {
shipCharge = 0;
}
return shipCharge;
}
//display shipping charge invoice
public static void displayResults(String itemDescription, double shipWeight, char shipMethod, double
shipCost) {
System.out.println();
System.out.println("*** WE SHIP INVOICE ****");
System.out.println("Item Description: " + itemDescription);
System.out.printf("Item Weight: %.2f\n" + shipWeight);
System.out.println("Ship Method: " + shipMethod);
System.out.printf("Total Cost: $%.2f\n" + shipCost);
}
}
This is the output when I use "box 3.5 0" as my input:
Enter item description:
Enter item weight in lbs:
How would you like to ship your package:
(O)vernight
(T)wo Days
(E)conomy (may take up to 7 days)
Choose an option:
Enter item weight in lbs:
I don't have to reprint out the input's given, but I am very confused why it asks for the item's weight again and doesn't printout the final result.
I am also getting this error:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at WeShipIt.getShipWeight(WeShipIt.java:67)
at WeShipIt.main(WeShipIt.java:35)
I have tried for hours to fix this on my own, but I am asking for help as a last resort. I am new to computer science and probably made some very dumb mistake. Thank you
You have actually called the "getShipWeight(keyboard)" and "getShipClass(keyboard)" in the else block and that's why it is asking for weight again. Just make these statements comment and your code will run properly.
Good you are learning java.
There is a slight change that needs to be done in our program. getShipWeight & getShipClass are called twice in our actual code.
please use this code
import java.util.Scanner;
public class WeShipIt {
public static final int OVERNIGHT_CHARGE = 5;
public static final int TWO_DAY_CHARGE = 2;
public static final int ECONOMY_CHARGE = 1;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); // scanner object to pass around
double weight;
String itemDescription;
char shipMethod;
double shippingCost;
itemDescription = getitemDescription(keyboard);
/*weight = getShipWeight(keyboard);
shipMethod = getShipClass(keyboard);
shippingCost = calculateShipping(shipMethod, weight);*/
if (itemDescription.length() == 0) {
System.out.println("Invalid description. Program cannot continue");
System.exit(0);
} else {
weight = getShipWeight(keyboard);
if (weight <= 0) {
System.out.println("Invalid shipping weight. Program cannot continue");
} else {
shipMethod =getShipClass(keyboard);
shippingCost = calculateShipping(shipMethod, weight);
if (!(shipMethod == 'O' || shipMethod == 'T' || shipMethod == 'E')) {
System.out.println("Invalid shipping method. Program cannot continue");
} else {
displayResults(itemDescription, weight, shipMethod, shippingCost);
}
}
}
}
//get item description
public static String getitemDescription(Scanner keyboard) {
System.out.println("Enter item description:");
String itemDescription = keyboard.next();
return itemDescription;
}
//get item weight
public static double getShipWeight(Scanner console) {
System.out.println("Enter item weight in lbs:");
double itemWeight = console.nextDouble();
return itemWeight;
}
// get user's choice for shipping method and return it
public static char getShipClass(Scanner keyboard) {
char shipMethod;
// get shipping method
System.out.println();
System.out.println("How would you like to ship your package:");
System.out.println("(O)vernight");
System.out.println("(T)wo Days");
System.out.println("(E)conomy (may take up to 7 days)");
System.out.println("Choose an option: ");
shipMethod = keyboard.next().charAt(0); // Prof. Dan says leave this line in here. Will explain in class.
shipMethod = Character.toUpperCase(shipMethod);
return shipMethod;
}
// calculate and return shipping charge
public static double calculateShipping(char shipMethod, double weight) {
double shipCharge;
if (shipMethod == 'O') {
shipCharge = weight * OVERNIGHT_CHARGE;
} else if (shipMethod == 'T') {
shipCharge = weight * TWO_DAY_CHARGE;
} else if (shipMethod == 'E') {
shipCharge = weight * ECONOMY_CHARGE;
} else {
shipCharge = 0;
}
return shipCharge;
}
// display shipping charge invoice
public static void displayResults(String itemDescription, double shipWeight, char shipMethod, double shipCost) {
System.out.println();
System.out.println("*** WE SHIP INVOICE ****");
System.out.println("Item Description: " + itemDescription);
System.out.println("Item Weight: "+ shipWeight);
System.out.println("Ship Method: " + shipMethod);
System.out.println("Total Cost: $"+ shipCost);
}
}
The code you showed has 2 errors which are as :
1: System.out.printf("Item Weight: %.2f\n"+ shipWeight); and
System.out.printf("Total Cost: $%.2f\n"+ shipCost);
Doing this will throw a MissingFormatArgumentException
Cause when using printf and declaring an argument it adjusts itself with the first
variable (value to be printed) passed to it after comma. and in this case, there
ain't any comma so it won't recognize and throw a MissingFormatArgumentException.
Instead, you should write like this:
System.out.printf("Item Weight: %.2f\n",shipWeight);
System.out.printf("Total Cost: $%.2f\n", shipCost);
2: You are calling getShipWeight(keyboard) and getShipClass(keyboard) twice.
First time, when the user just enters the program.
Second time, in the else statement.
Which forces you to entre weight and shipping method again.
Here are the final changes:
public static final int OVERNIGHT_CHARGE = 5;
public static final int TWO_DAY_CHARGE = 2;
public static final int ECONOMY_CHARGE = 1;
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in); //scanner object to pass around
double weight;
String itemDescription;
char shipMethod;
double shippingCost;
itemDescription = getitemDescription(keyboard);
weight = getShipWeight(keyboard);
shipMethod = getShipClass(keyboard);
shippingCost = calculateShipping(shipMethod, weight);
if (itemDescription.length() == 0){
System.out.println("Invalid description. Program cannot continue");
System.exit(0);
} else {
// getShipWeight(keyboard); <-- this is forcing uset to enter weight again.
if (weight <= 0){
System.out.println("Invalid shipping weight. Program cannot continue");
} else {
// getShipClass(keyboard); <-- this is forcing user to again give shipping method
if (!(shipMethod == 'O' || shipMethod == 'T' || shipMethod == 'E')){
System.out.println("Invalid shipping method. Program cannot continue");
} else {
displayResults(itemDescription, weight, shipMethod, shippingCost);
}
}
}
}
//get item description
public static String getitemDescription(Scanner keyboard){
System.out.println("Enter item description:");
String itemDescription = keyboard.next();
return itemDescription;
}
//get item weight
public static double getShipWeight(Scanner console){
System.out.println("Enter item weight in lbs:");
double itemWeight = console.nextDouble();
return itemWeight;
}
//get user's choice for shipping method and return it
public static char getShipClass(Scanner keyboard) {
char shipMethod;
//get shipping method
System.out.println();
System.out.println("How would you like to ship your package:");
System.out.println("(O)vernight");
System.out.println("(T)wo Days");
System.out.println("(E)conomy (may take up to 7 days)");
System.out.println("Choose an option: ");
shipMethod = keyboard.next().charAt(0); //Prof. Dan says leave this line in here. Will explain in
shipMethod = Character.toUpperCase(shipMethod);
return shipMethod;
}
//calculate and return shipping charge
public static double calculateShipping(char shipMethod, double weight){
double shipCharge;
if (shipMethod == 'O') {
shipCharge = weight * OVERNIGHT_CHARGE;
}
else if (shipMethod == 'T') {
shipCharge = weight * TWO_DAY_CHARGE;
}
else if (shipMethod == 'E') {
shipCharge = weight * ECONOMY_CHARGE;
} else {
shipCharge = 0;
}
return shipCharge;
}
//display shipping charge invoice
public static void displayResults(String itemDescription, double shipWeight, char shipMethod, double
shipCost) {
System.out.println();
System.out.println("*** WE SHIP INVOICE ****");
System.out.println("Item Description: " + itemDescription);
System.out.printf("Item Weight: %.2f\n",shipWeight); // <-- changed
System.out.println("Ship Method: " + shipMethod);
System.out.printf("Total Cost: $%.2f\n", shipCost); // <-- changed
}
Output:
Enter item description:
box
Enter item weight in lbs:
3.5
How would you like to ship your package:
(O)vernight
(T)wo Days
(E)conomy (may take up to 7 days)
Choose an option:
O
*** WE SHIP INVOICE ****
Item Description: box
Item Weight: 3.50
Ship Method: O
Total Cost: $17.50
I created a module that's called within another module, and it looks something like this:
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere (itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
but, I'm getting the error of "illegal start of expression" with the line where I make the method header for the second module. It looks constructed correctly.
Complete code as follows:
//This program will find the area or volume of a circle or sphere, respectively.
import javax.swing.JOptionPane;
public class Java_Chapter_9
{
public static void main(String args[])
{
//Declarations
String itemShape; //type of shape
String runProgram; //user control
Double itemRadius; //radius of tem
Double finalAnswer; //calculation for final answer
//End Declarations
showGreeting (); //Call greeting module
runProgram = JOptionPane.showInputDialog("Please enter 'Y' to run the program, or 'N' to quit"); //giving user control
while (runProgram.equalsIgnoreCase("y")) //loop for continuous use
{
itemShape = getItemShape (); //calling itemShape module
itemRadius = getItemRadius (); //calling itemradius module
finalAnswer = calculateAnswer (itemRadius, itemShape); //calling the module for calculation with paramaters
runProgram = JOptionPane.showInputDialog("Enter 'Y' to input more, or 'N' to Quit");
}
showGoodbye ();
////////////////////////////////////////////////// starting modules
public static void showGreeting () //greeting module
{
System.out.println("Welcome to the program");
System.out.println("This program will show you the area or volume of a shape");
}
///////////////////////////////////////////////// seperating modules
public static String getItemShape ()
{
String typeOfShape;
typeOfShape = JOptionPane.showInputDialog("Please enter 'C' for a Circle, or 'S' for a Sphere"); //getting input for shape
return typeOfShape; //returning to method
}
////////////////////////////////////////////////// seperating modules
public static double getItemRadius ()
{
double radiusOfItem; //variable withing scope of module
String radiusOfItemInput;
radiusOfItemInput = JOptionPane.showInputDialog("Please enter the radius of the item in inches: ");
radiusOfItem = Double.parseDouble(radiusOfItemInput);
return radiusOfItem;
}
////////////////////////////////////////////////// seperating modules
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere(itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
}
public static void showGoodbye ()
{
System.out.println("Thank you for using the program. Goodbye.");
}
Specifically, I appear to be having problems in general calling the modules, but none of the text is overly clear and how to make a module fit within the main method, which is where I'm struggling.
There are a lot of errors in your code.
Remove the ; in function. ; is not needed for function.
public static double calculateAnswerSphere(double itemRadius); // remove ;
After showGoodBye() method is being called, you miss to add a close brackets.
You have a typo in this line
system.out.print
It should be System.out.print and so on...
This is the Console. When entering values after the user decides what to calculate. The values that return from the class are zero. I have private variables, with accessors and mutators. I don't know what the reason for this is. Any ideas?? Please!!!
public class Console {
public static final int USER_CHOIDE_VOLTAGE = 1;
public static final int USER_CHOIDE_AMPERAGE = 2;
public static final int USER_CHOIDE_RESISTANCE = 3;
public static void main(final String[] args) {
// Creates a Circuit Object
Circuit myCircuit = new Circuit();
// Creates a Scanner Object to get input from user
Scanner keyboard = new Scanner(System.in);
// Holds input from user
int userChoice;
System.out.println("\n");
System.out.println("This system will calculate the ");
System.out.println("\tVoltage, Amperage, or Resistance ");
System.out.println("\tgiven the other two values using Ohms Law.");
System.out.println("\n");
// Ask user what to calculate, if it is not one
// of the options, ask again(while-do loop)
do {
System.out.println("Which value would you like to calculate?");
System.out.println("\t1. Voltage");
System.out.println("\t2. Resistane");
System.out.println("\t3. Amperage");
System.out.println("\n");
System.out.println("Please select 1, 2, or 3");
userChoice = keyboard.nextInt();
//Switch follows cases for what the user would
// like to calculate
switch (userChoice) {
case USER_CHOIDE_VOLTAGE:
// Gets Amperage from User
System.out.println("Please enter the Amperage:");
// Sets Amperage value
myCircuit.setAmperage(keyboard.nextDouble());
// Gets Resistance from User
System.out.println("Please enter the Resistance:");
// Sets Resistance value
myCircuit.setResistance(keyboard.nextDouble());
// Returns Value for voltage from method
System.out.println("The value of Voltage is: "
+ myCircuit.getVoltage());
break;
case USER_CHOIDE_AMPERAGE:
// Gets Voltage from User
System.out.println("Please enter the Voltage:");
myCircuit.setVoltage(keyboard.nextDouble());
// Gets Resistance from User
System.out.println("Please enter the Resistance:");
// Sets Resistance value
myCircuit.setResistance(keyboard.nextDouble());
// Returns Value for Amperage from method
System.out.println("The value of Amperage is: "
+ myCircuit.getAmperage());
break;
case USER_CHOIDE_RESISTANCE:
// Gets Amperage from User
System.out.println("Please enter the Amperage:");
// Sets Amperage value
myCircuit.setAmperage(keyboard.nextDouble());
// Gets Voltage from User
System.out.println("Please enter the Voltage:");
myCircuit.setVoltage(keyboard.nextDouble());
// Returns Value for Resistance from method
System.out.println("The value of Resistance is: "
+ myCircuit.getResistance());
break;
// Do Nothing Since do while loop takes care of this option
default:
}
} while (userChoice != USER_CHOIDE_VOLTAGE
&& userChoice != USER_CHOIDE_AMPERAGE
&& userChoice != USER_CHOIDE_RESISTANCE);
System.exit(0);
keyboard.close();
}
}
This is the Class
public class Circuit {
private double voltage, resistance, amperage;
public double getVoltage() {
return voltage;
}
public double getResistance() {
return resistance;
}
public double getAmperage() {
return amperage;
}
public void setVoltage(double pVoltage) {
voltage = pVoltage;
}
public void setResistance(double pResistance) {
resistance = pResistance;
}
public void setAmperage(double pAmperage) {
amperage = pAmperage;
}
public void calcVoltage() {
voltage = amperage * resistance;
}
public void calcResistance() {
resistance = voltage / amperage;
}
public void calcAmperage() {
amperage = voltage / resistance;
}
}
You never actually call any of the Circuit classes calc...() methods.
You need to call the appropriate calc method before your final print statements.
For example, when userChoice is USER_CHOIDE_VOLTAGE:
case USER_CHOIDE_VOLTAGE:
// Gets Amperage from User
System.out.println("Please enter the Amperage:");
// Sets Amperage value
myCircuit.setAmperage(keyboard.nextDouble());
// Gets Resistance from User
System.out.println("Please enter the Resistance:");
// Sets Resistance value
myCircuit.setResistance(keyboard.nextDouble());
// *** Add the following line to your program. ***
myCircuit.calcVoltage();
// Returns Value for voltage from method
System.out.println("The value of Voltage is: "
+ myCircuit.getVoltage());
break;
You are not calling your calcSomething() methods, therefore, you are not computing anything and just returning (by getSomething()) the values without modifications. Before continuing, please check your print statements, I think they should look like
System.out.println("\t1. Voltage");
System.out.println("\t2. Amperate");
System.out.println("\t3. Resistance");
since you declared your constants:
public static final int USER_CHOIDE_VOLTAGE = 1;
public static final int USER_CHOIDE_AMPERAGE = 2;
public static final int USER_CHOIDE_RESISTANCE = 3;
Continuing with the explanation, let's say the input is 2, so the switch would enter the case USER_CHOIDE_AMPERAGE, here is the problem, you must compute the "amperage" by calling myCircuit.calcAmperage():
case USER_CHOIDE_AMPERAGE:
System.out.println("Please enter the Voltage:");
myCircuit.setVoltage(keyboard.nextDouble());
System.out.println("Please enter the Resistance:");
myCircuit.setResistance(keyboard.nextDouble());
myCircuit.calcAmperage(); // ADD THIS LINE
System.out.println("The value of Amperage is: " + myCircuit.getAmperage());
break;
You must do similar changes to the other swith-cases.
You can call your cal.. Method in every Getter method like..
public double getAmperage() {
calcAmperage();
return amperage;
}
public double getVoltage() {
calcVoltage();
return voltage;
}
Here is the problem
For example
you are calling myCircuit.getVoltage()
and in the function you are not calculating anything
public double getVoltage() {
return voltage;
}
instead call
myCircuit.calcVoltage()
import java.io.*;
import java.util.*;
public class volumeConeD
{//class
public static void main (String [] args)
{//main
Scanner keyBoard = new Scanner(System.in);//input for keyBoard
//variables
double volume;
double radius;
double hieght;
double oneThird = 0.3333;
double pie = 3.14;
double yes = 1.0;
boolean r = true;
try
{//begin of try
while(r == true){
System.out.print("Volume of a Cone... V=1/3(3.14)r^2(h)");
System.out.println ();
System.out.println ();
radius = getRadius(radius);//call to method
radius = keyBoard.nextDouble ();
System.out.print("Enter a Height ");
hieght = keyBoard.nextDouble ();
//math
volume = oneThird * pie * radius * radius * hieght;
System.out.printf ("Volume = " + volume);
}//end of try
catch (Exception Error){
System.out.println("You entered wrong data");
}
System.out.println ();
System.out.print("Does the user wish to try again?");
System.out.println ();
System.out.print("Enter 1 to go again OR any other key to end.");
yes = keyBoard.nextDouble();
}//end of while
}//end of main
public static double getRadius(double mRadius)
{
System.out.print("Enter Radius Squared Number ");
return mRadius;
}
}//end of program
this is my first time posting on this forum, so please excuse how ask...here goes... all i am trying to do with this is repeat this problem under user control using a sentinel method(while loop). I had it almost working earlier but i kept getting errors about how i defined "r". Now i get errors about my catch try blocks. please help.
volumeConeD.java:35: error: 'catch' without 'try'
catch (Exception Error){
^
volumeConeD.java:35: error: ')' expected
catch (Exception Error){
^
volumeConeD.java:35: error: not a statement
catch (Exception Error){
^
volumeConeD.java:35: error: ';' expected
catch (Exception Error){
^
volumeConeD.java:19: error: 'try' without 'catch', 'finally' or resource declarations
try
^
5
You placed your try { outside the while loop, but the corresponding catch is within the while loop. But must be either outside the loop or inside the loop, together.
Try placing the try { lines inside the while loop.
Additionally, it looks like these lines won't work either:
radius = getRadius(radius);//call to method
radius = keyBoard.nextDouble ();
All getRadius does is print out a prompt and return the passed in parameter, radius. But radius hasn't been initialized yet. But it looks like nothing is done with it yet anyway. Rename the method something like promptForRadius, and it doesn't need to take in a parameter or return anything.
public static void promptForRadius()
{
System.out.print("Enter Radius Squared Number ");
}
Then when calling it:
promptForRadius();
// Then you can call this line (unchanged)
radius = keyBoard.nextDouble();
Where your comment says // end of try it should really say // end of while and vice versa.
I have reformatted the code. Braces for try/catch block cannot end before while loop braces. Also you have to initialize variables before using them (e.g,. radius). Eclipse like IDE will be helpful to format and identify compilation errors. BTW I have not checked the logical correctness of the code but more of compilations and syntax issues
import java.util.Scanner;
public class volumeConeD
{
public static void main(String[] args)
{
Scanner keyBoard = new Scanner(System.in);// input for keyBoard
// variables
double volume;
double radius = 0.0;
double hieght;
double oneThird = 0.3333;
double pie = 3.14;
double yes = 1.0;
boolean r = true;
try
{// begin of try
while (r == true)
{
System.out.print("Volume of a Cone... V=1/3(3.14)r^2(h)");
System.out.println();
System.out.println();
radius = getRadius(radius);// call to method
radius = keyBoard.nextDouble();
System.out.print("Enter a Height ");
hieght = keyBoard.nextDouble();
// math
volume = oneThird * pie * radius * radius * hieght;
System.out.printf("Volume = " + volume);
System.out.println();
System.out.print("Does the user wish to try again?");
System.out.println();
System.out.print("Enter 1 to go again OR any other key to end.");
yes = keyBoard.nextDouble();
}// end of while
}// end of try
catch (Exception Error)
{
System.out.println("You entered wrong data");
}
}// end of main
public static double getRadius(double mRadius)
{
System.out.print("Enter Radius Squared Number ");
return mRadius;
}
}// end of program
This seems to be your problem
try
{
while (...)
{
int blammo;
try
{
... code
blammo = 9;
}
catch ...
{
// catching here means that the while loop will continue looping.
}
System.out.println("Blammo: " + blammo); // This results in the error: variable
// blammo might not have been initialized. This is because the assignment
// "blammo = 9" is inside the try block and if an exception was thrown before
// the assignment then it (the assignment) will never execute and blammo will
// be uninitialized.
} // end of while loop
} // end of outter try
catch ...
{
// catching here means that the exception exits the while loop.
}
You use a catch, but it's not matching with the try...
oneThird variable can be set as 1 / 3 (more precision).
Same for PI, the Math library already has a PI definition.
The function getRadius is useless, you should take it off, or maybe replace it by a function which asks the user to enter a double number.
import java.util.Scanner;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double volume, radius, height, oneThird = (1.0 / 3);
int continueExecution = 1;
try {
while (continueExecution == 1) { // same as r == true (redundant)
System.out.println("Volume of a Cone... V=1/3(3.14)r^2(h)\n\n"); // '\n' is the newline character
radius = getDoubleValue(sc, "Enter radius : ");
height = getDoubleValue(sc, "Enter height : ");
volume = oneThird * Math.PI * Math.pow(radius, 2) * height;
System.out.println("Volume = " + volume + "\nEnter 1 to start again, or another number to exit: ");
continueExecution = sc.nextInt();
}
} catch (Exception e) { // Pokemon exception handling !
System.err.println(e.getMessage());
}
}
public static double getDoubleValue(Scanner sc, String msg) {
System.out.print(msg);
return sc.nextDouble();
}