Why doesn't the code work? [duplicate] - java

This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 5 years ago.
import java.util.Scanner;
public class Formula {
public static void main(String[] args) {
Scanner numIn = new Scanner(System.in);
Scanner form = new Scanner(System.in);
double r, d, h, a;
String formula;
System.out.println("Please state which circle formula you want to use:");
System.out.println("Circumference");
System.out.println("Area");
System.out.println("Cylinder volume");
formula = form.next();
switch (formula) {
case "Circumference":
System.out.println("Please state the diameter: ");
d = numIn.nextDouble();
System.out.println("The circumference is:");
System.out.println(3.14 * d);
break;
case "Area":
System.out.println("Please state the radius: ");
r = numIn.nextDouble();
System.out.println("The area is:");
System.out.println(3.14 * (r * r));
break;
case "Cylinder volume":
System.out.println("State the area of the base: ");
a = numIn.nextDouble();
System.out.println("State the height of the cylinder: ");
h = numIn.nextDouble();
System.out.println("the volume is: ");
System.out.println(a * h);
break;
default:
System.out.println("Option not recognized");
break;
}
}
}
as you can see I am trying to create a formula calculator (note: I am only a begginer) and it all seemed to be working until the last 'case'. The last case "Cylinder volume" is not recognized when I type it in the console. All other cases work fine, and I do not see a difference between "Cylinder volume" and the other ones. Please help!

That is you used
formula = form.next();
This only reads until end of the word but not the space
so when you put "Cylinder volume" it reads Cylinder only.
It will work if you change it to
formula = form.nextLine();

Zircon has the solution. However, it may also be helpful to print in the default case what formula is set to:
default:
System.out.println("Option: " + formula + " not recognized");
break;
Doing this kind of stuff will help your sanity in the future.

Try
Scanner form = new Scanner(System.in, "UTF-8").useDelimiter("\n");
Remember that Scanner doesn't work with non-ascii character.
Another test could be printing 'formula' before the switch, and check its content.

Related

Trying to create a menu in java to calculate and display information about a circle

I'm pretty new to java and I've been working through some questions and have been mostly okay but I've had a lot of trouble with this question which asks me to create a menu to find out and display various information about a circle. My code is as follows:
import java.util.Scanner;
public class Circle2 {
public static void main(String[] args) {
final double pi = 3.1416;
Scanner values = new Scanner(System.in);
char response;
double area, perimeter, radius;
do // put code in loop
{
// offer menu of options
System.out.println();
System.out.println("*** CIRCLE MENU ***"); // create a blank line
System.out.println("[1] Set radius");
System.out.println("[2] Display radius");
System.out.println("[3] Display area");
System.out.println("[4] Display perimeter");
System.out.println("[5] Quit");
System.out.println("Enter choice [1,2,3,4,5}: ");
response = values.next().charAt(0); // get response
System.out.println(); // create a blank line
switch(response) // process response
{
case '1': System.out.println("Enter a value for the radius: ");
radius = values.nextDouble();
while(radius < 0)
{
System.out.println("Please enter a non-negative radius: ");
radius = values.nextDouble();
}
break;
case '2': System.out.println("The radius is " + radius);
break;
case '3': System.out.println("The area is " + (pi * radius * radius));
break;
case '4': System.out.println("The perimeter is " + (2 * pi * radius));
break;
case '5': System.out.println("Goodbye!");
break;
default: System.out.println("Options 1-5 only!");
}
} while (response != '5'); // test for Quit option
}
}
The errors I keep getting are in the switch case, I've tried putting the first case into an if statement and other approaches but nothing is working. I'm trying to allow the user to input the radius in case 1 and then I wanted to use that value in the rest of the cases but it won't work at all. This could be me making a very stupid mistake but any help is appreciated, and sorry if I've done this post wrong this was my last resort because I've been stuck for hours.
I pasted your code into Eclipse.
The only thing that was not working was that
the following variables needed to be initialized:
double area, perimeter, radius = 0;
If you are getting this error :
error: variable radius might not have been initialized
case '2': System.out.println("The radius is " + radius);
Then this is because you are printing the radius value before initializing it, so you need to give a default value before printing it.

how to store a calculation from an input to memory, input repeats, first calculation from input is added to second calculation from input and so on?

I need some help with a program I'm trying to make using Java.
I'm currently a freshman in Information Technology and for finals, we have to do an electrical billing program of some sort I've already done some code but it won't work the way I want it to. Can anyone help me fix it?
flow of program:
1)user inputs multiple numbers to be calculated
2)program calculates it
3)the result of the calculation from step 2 is stored somewhere
4)program asks user if they want to input again
5)if user chooses input again the process repeats from step 1 to 2 and is added to the first calculation and so on and so forth
static Scanner console = new Scanner (System.in);
Double loopFor=0.0;
Double w,h,kwh,t;
System.out.print("\nHello and welcome to Pikabill. The electricity bill estimate calculator.");
while(true) {
do {
System.out.print("\nEnter what is being asked. You might have to refer to labels on your appliances");
System.out.print("\nWATTAGE (W): ");
w=console.nextDouble();
System.out.print("\nUSAGE (in HOURS): ");
h=console.nextDouble();
System.out.print("\nELECTRICITY RATE (kWh): ");
kwh=console.nextDouble();
t=(w*h)/1000*kwh;
System.out.print("\nCOST: " + t);
loopFor += t;
System.out.print("\nWould you like to continue? YES [y] No [n]");
String c= console.nextLine();
if(c.equalsIgnoreCase("n")){
break;
}
}
while (loopFor !=0);
}
}
}
somehow, when I run this the calculation works fine, but when it comes to displaying the t (the calculation), it shows the "do you want to continue" just fine but the "Hello and welcome to Pikabill...." shows on the next line even though i havent pressed y. It also doesn't add the previous calculations to the newer ones as well.
This piece of code will work.
import java.util.Scanner;
public class ElectricalBillingProgram
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
Double loopFor = 0.0;
Double w, h, kwh, t;
for (int i = 0;; i++)
{
System.out.print("\nEnter what is being asked. You might have to refer to labels on your appliances");
System.out.print("\nWATTAGE (W): ");
w = console.nextDouble();
System.out.print("\nUSAGE (in HOURS): ");
h = console.nextDouble();
System.out.print("\nELECTRICITY RATE (kWh): ");
kwh = console.nextDouble();
t = (w * h) / 1000 * kwh;
System.out.print("\nCOST: " + t);
loopFor += t;
System.out.print("\nWould you like to continue? YES [y] No [n]");
String c = console.next();
if (c.equalsIgnoreCase("n"))
{
break;
}
}
}
}
Observations from your code:
Never mixup "while" and "doWhile", if it confuses you, use "for" loop.
use console.next() instead of console.nextLine().
Happy learning!
This should be your code -
Scanner console = new Scanner(System.in);
Double loopFor = 0.0;
Double w, h, kwh, t;
System.out.println("Hello and welcome to Pikabill. The electricity bill estimate calculator.");
while (true) {
System.out.println("Enter what is being asked. You might have to refer to labels on your appliances");
System.out.println("WATTAGE (W): ");
w = console.nextDouble();
System.out.println("USAGE (in HOURS): ");
h = console.nextDouble();
System.out.println("ELECTRICITY RATE (kWh): ");
kwh = console.nextDouble();
t = (w * h) / 1000 * kwh;
loopFor += t;
System.out.println("COST:\t" + t);
System.out.println("loopFor:\t" + loopFor);
System.out.println("Would you like to continue? YES [y] No [n]");
String c = console.next();
if (c.equals("n")) {
break;
}
}

Adding a 'While' Loop To My Program [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm working on a program that calculates the area of either a circle (C), square (S), or rectangle (R), depending on what letter the user inputs. I've tested it and it works fine; the code is below:
import java.util.Scanner;
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
String Shape = input.nextLine();
if (Shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
}
else if (Shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
}
else if (Shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
}
Now, what I want to do is add a loop to the program. For example, if the user inputs C for circle and puts in the number 22 for the radius, they'll get an answer, but I want the program to loop back to the beginning again so that it asks the user "What is your shape?...". Also, if the user types in X instead of C, S, or R, I want the program to quit, but I'm not sure how to add that in, either.
I know that I need to add a 'while' loop, but I was hoping someone could point me in the right direction, because I don't know where to insert that part of the code. Do I add the 'while' loop somewhere at the beginning of the code, after the last "if else" statement, or... Also, I'm not actually sure what to type. Should it be something like,
while (Shape == C, S, R) {
....?
Any help or pointers would be appreciated by any one in the coding community! I will continue to work on this code on my own as well.
I would go for the do, while
So, the program will always do something while the conditions that are set are being accomplished, so you want your program to look something like:
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean thisB = false; /*this is the guy who will tell the loop to stop the execution when the user inserts X*/
String shape;
do{
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
shape = input.next();
if(shape.equalsIgnoreCase("C") || shape.equalsIgnoreCase("S") || shape.equalsIgnoreCase("R")) {
if (shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
} else if (shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
} else if (shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
else if (shape.equalsIgnoreCase("X")) thisB = true;/*or in other words: stop*/
}
while(!thisB);
}
}
Things to consider:
1) Naming conventions, always start variable names with undercase using camelCase, in your example shape started with UpperCase
2) When in a while loop, use only next(), not nextLine() to pick up the values as the latter will duplicate the question in the System.out.Println.
3) The optimum way to do this is to put all your if clauses in a method and call it with the parameter from the Scanner input. Even better would be having a method per shape, as things can get hairy depending on requests

Compile error in my do/while statements?

I created 3 classes Circle, Rectangle, and RightTriangle using my FigureGeometry interface. This program is supposed to take input run calculation using the different classes.
I'm getting a couple of errors with my do/while statement. The do statement says "Illegal start of type". My while statement say the same and "can't find variable option".
I've tried searching for other questions on here/google, but I can't find anything that has helped with my code. It is always something like an extra bracket but as far as I can tell there isn't anything extra here.
I've double checked that all my open/close brackets match up. I've tried having my option variable in the do statement (which I was certain wasn't correct, but I was just trying some different things). I'm just not sure what the issue is?
package figuregeometry;
import java.util.Scanner;
public class FigGeometryCalculator
{
//========================MAIN==============================================
public static void main(String[] args)
{
float height;
float width;
float length;
float radius;
float degrees;
String menu = "Would you like to figure the geometry for a: " + "\n"
+ "1. Circle" + "\n"
+ "2. Rectangle" + "\n"
+ "3. Right Triangle" + "\n"
+ "0. Exit";
do
{
Scanner in = new Scanner(System.in);
int option = in.nextInt();
switch(option)
{
case 1: System.out.println("Enter radius: ");
radius = in.nextFloat();
System.out.println("Enter Degrees of sector: ");
degrees = in.nextFloat();
Circle newCircle = new Circle(radius, degrees);
System.out.println("Set Scale: ");
newCircle.setScale(in.nextInt());
newCircle.toString();
break;
case 2: System.out.println("Enter length: ");
length = in.nextFloat();
System.out.println("Enter width: ");
width = in.nextFloat();
Rectangle newRectangle = new Rectangle(length, width);
System.out.println("Set Scale: ");
newRectangle.setScale(in.nextInt());
newRectangle.toString();
break;
case 3: System.out.println("Enter Length: ");
length = in.nextFloat();
System.out.println("Enter Height: ");
height = in.nextFloat();
RightTriangle newTriangle = new RightTriangle(length, width);
System.out.println("Set Scale: ");
newTriangle.setScale(in.nextInt());
newTriangle.toString();
break;
case 0:
System.out.println("Exit");
break;
default: System.out.println("Not an a valid option. Please try again.");
}
}while(option != 0);
}
}
Problems:
Remove all invalid modifiers. That is, change:
public float height;
public float width;
public float length;
public float radius;
public float degrees;
To:
float height;
float width;
float length;
float radius;
float degrees;
Maybe not a direct answer to your question but you need to put your input received option = in.nextInt(); inside the loop. Otherwise you will end up with an infinite loop.
For example, if the user chooses '1', option becomes 1 and is never updated inside the loop so your loop will run forever.
EDIT:
Just to clarify since I see you didn't understand.
You don't put int option = in.nextInt(); inside the loop, you put everything but the int. (so option = in.nextInt(); inside the loop). You say int option; outside the loop.
So:
int option; // created outside the loop
do {
System.out.print(menu);
option = in.nextInt(); // used inside the loop
switch(option)
{
// CASES AND CODE
}
} while(option != 0);
That is why you are getting an error because your variable option isn't visible to the while loop so the loop cannot compare something with 0 if it cannot find it.
In general, try not to create anything inside loops, and create outside of them to prevent unnecessary object creation. Another example, your Scanner object should be created outside of your loop.
Put the statement Scanner in = new Scanner(System.in); outside the loop then use it with option = in.nextInt(); the way I described above.

correct way to check user input with scanner

I'm very new to programming, I've wrote an app for working the area out of certain shapes.
I have the AreaCalculations in another class can provide if needed but that works fine.
My problem is checking when the user types a character instead of a double. As you can see from my code i got it to work by using a while loop and (!reader.NextDouble()) .
This works but i then have to repeat the question. I could do this throughout the program but is there an easier/tidier way of doing this???
Thanks,
Craig
My code so far :
package areaprog;
import java.util.Scanner;
public class Mainprog {
public static void main (String [] args){
//Area Menu Selection
System.out.println("What shape do you need to know the area of?\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
//User input for menu
Scanner reader = new Scanner(System.in);
System.out.println("Number: ");
//Menu syntax checking
while (!reader.hasNextDouble())
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
reader.next(); //ask for next token?
}
double input = reader.nextDouble();
reader.nextLine();
//Depending on user selection, depends on what method is called using switch.
Scanner scan = new Scanner(System.in);
//Square selection
if (input == 1){
System.out.println("What is a length of 1 side of the Square?\n");
double s1 = scan.nextDouble();
double SqAns = AreaCalculator.getSquareArea(s1);
System.out.println("The area of you square is: " + SqAns);
}
//Rectangle selection
if (input == 2){
System.out.println("What is the width of your rectangle?.\n");
double r1 = scan.nextDouble();
System.out.println("What is the height of your rectangle?\n");
double r2 = scan.nextDouble();
double RecAns = AreaCalculator.getRectArea(r1, r2);
System.out.println("The area of your rectangle is: " + RecAns);
}
//Triangle selection
if (input == 3){
System.out.println("What is the base length of the triangle?.");
double t1 = scan.nextDouble();
System.out.println("What is the height of your triangle?");
double t2 = scan.nextDouble();
double TriAns = AreaCalculator.getTriArea(t1, t2);
System.out.println("The area of your triangle is " + TriAns);
}
//Circle selection
if (input == 4){
System.out.println("What is the radius of your circle?.");
double c1 = scan.nextDouble();
double CircAns = AreaCalculator.getCircleArea(c1);
System.out.println("The area of your circle is " + CircAns);
}
//Exit application
if (input == 5){
System.out.println("Goodbye.");
}
}
}
Ok so I've added in a Exception to catch the error. So its a bit cleaner now in the way it handles people not using intergers.
Number:
1
What is a length of 1 side of the Square?
a
Why are you trying to be clever? use an interger.
But then the program just ends.... How would i either get them back to the main menu or even get them to re-input there last effort?
Thanks,
Craig
As far as menu driven programs are concerned,its well and good.But as you said:
"This works but i then have to repeat the question."
So read Exception handling tutorial in java
So, your code will look something like this :
try
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
input = reader.nextDouble();
}
catch(InputMismatchException err)
{
System.out.print(err.getMessage());
}
Don't forget to import import java.util.InputMismatchException or import java.util.*
And try to declare variables outside the try block, may not be visible outside.

Categories

Resources