double width cannot be resolved along with int walls even though before I started my Surface Area calculations, it compiled.
import java.util.Scanner;
public class Assignment_3_4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Customer Name
System.out.println("Enter your First Name");
String Firstn = in.next();
System.out.println("Enter your Last Name");
String Lastn = in.next();
System.out.println("Valued Customer Name: " + Firstn + " " + Lastn);
//Wall Measurements
System.out.println("Enter the Width");
if(in.hasNextDouble()){
double width = in.nextDouble();
System.out.println("Width/Height: " + width);
} else {
System.out.println("Please enter only numbers");
}
System.out.println("Enter number of walls");
if(in.hasNextInt()){
int walls = in.nextInt();
System.out.println("Number of Walls: " + walls);
} else {
System.out.println("Please enter only integers");
}
//Calculate Surface Area - Width Height and Length are all the same measurement
double SA = ((width * width) * walls);
System.out.println("Area to be Painted: " + SA + " square meters");
Java has what is known as block scope
Any variable declared within a block {} is not accessible outside the block. You can use variables from outside the scope, but not the other way. What you need to do is declare the variable outside the scope. You probably also want to throw an exception to the user.
double width;
if(in.hasNextDouble()){
width = in.nextDouble();
System.out.println("Width/Height: " + width);
} else {
throw new IllegalArgumentException("Please enter only numbers");
}
You declared width inside the block of this if statement:
if(in.hasNextDouble()){
double width = in.nextDouble();
System.out.println("Width/Height: " + width);
}
So this block is the scope of width and it's not visible outside of it.
What you should do?
Declare it like this:
double width;
if(in.hasNextDouble()){
width = in.nextDouble();
System.out.println("Width/Height: " + width);
}
Now width will be visible to the rest of main() although it may be uninitialized. So maybe this is safer:
double width = 0.0;
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
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am new to java and cannot figure out how to work the copy constructors. Please bear with me.
I am trying to get information for shipping packages. I am trying to use the copy constructor to repeat the enter shipping details section.
I honestly have no idea what to do with it. The code works fine for one package and there are no errors - I just need to figure out how to prompt a user for a second package.
import java.util.Scanner;
public class Package {
private static double length = 1.0;
private static double width = 1.0;
private static double height = 1.0;
private static double sum1 = length+width+height;
public Package(Package p) {
this.height = p.height;
this.length = p.length;
this.width = p.width;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter package dimensions.\nEnter Length: ");
length = input.nextDouble();
System.out.println("\nEnter Width: ");
width = input.nextDouble();
System.out.println("\nEnter Height: ");
height = input.nextDouble();
System.out.println("Package 1: " + length + " X " + width + " X " + height + ", Volume = " + sum1);
}
}
I think your misunderstanding is in this line:
private static double sum1 = length+width+height;
This computation will be executed at the moment the runtime executes this line so when the class is loaded (so length=1.0, width=1.0, height=1.0).
If you want the sum to be calculated after you have set the length, width and height, you have to put the calculation in a method:
public static double sum() {
return length+width+height;
}
And in your last line call this method:
System.out.println("Package 1: " + length + " X " + width + " X " + height + ", Volume = " + sum())
Also notice that all your variables are static so you don't really use the Package as an object. For simplicity you can remove the constructor except if you want to learn about java objects but then you have to adapt more code.
UPDATE: this works but to be able to use the copy constructor I each time have to create 2 objects. Speaking of overhead.
Mathimatics: it is not sum but product for volumes.
import java.util.Scanner;
public class Package {
double length=1.0;
double height=1.0;
double width=1.0;
double sum;
public Package() {
}
public Package (Package p)
{
this.length = p.length;
this.height = p.height;
this.width = p.width;
// to calculate the volume it's more like a product then a sum
sum=length*height*width;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for (int i=0;i<5;i++)
{
Package pack=new Package();
System.out.println("Enter package dimensions.\nEnter Length: ");
pack.length = input.nextDouble();
System.out.println("\nEnter Width: ");
pack.width = input.nextDouble();
System.out.println("\nEnter Height: ");
pack.height = input.nextDouble();
Package p=new Package(pack);
System.out.println("Package 1: " + p.length + " X " + p.width + " X " + p.height + ", Volume = " + p.sum);
}
}
}
You can use do-while for this .. something like below
Scanner input = new Scanner(System.in);
int i=0;
do{
Package package =new Package();
System.out.println("Enter package dimensions.\nEnter Length: ");
package.length = input.nextDouble();
System.out.println("\nEnter Width: ");
package.width = input.nextDouble();
System.out.println("\nEnter Height: ");
package.height = input.nextDouble();
System.out.println("Package : " + package.length + " X " + package.width + " X " + package.height + ", package.Volume = " + sum1);
i++;
}while ( i<=5);
I am a complete beginner with java and coding altogether and am trying to make a program that solves two equations based on what a user has inputted into the program. I've tried changing the variable types to long, int, double, but nothing changes. The result is always 0 or 0.0 Any help would be much appreciated.
package pa2;
import java.util.Scanner;
public class GravitationalForce
{
public static void main(String[] args)
{
System.out.println("Please enter the name of the planet and its weight in quintillion kilograms");
Scanner myScanner = new Scanner (System.in);
String planetName = myScanner.next();
int planetWeight = myScanner.nextInt();
System.out.println("Enter the weight of the person in kilograms");
double personWeight = myScanner.nextDouble();
System.out.println("Please enter the radius of the planet Alderaan in million meters");
double planetRadius = myScanner.nextDouble();
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
Double force = gravitationalConstant*(planetWeight*Math.pow(10, 18)*personWeight)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6);
Double gravity = gravitationalConstant*(planetWeight*Math.pow(10, 18)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6));
System.out.println("The gravitational force of planet " + planetName + " on the person is " + force + " Newtons");
System.out.println("The gravity of the planet " + planetName + " is " + gravity + " meters per second squared");
}
}
6.673*Math.pow(10,-11) is < 1, so if you cast it to long, it becomes 0.
change
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
to
double gravitationalConstant = 6.673*Math.pow(10,-11);
I'm trying to Make two calls to a second return method which takes in one parameter ( my value in inches) and prints the value in centimeters but its not working! What did I do wrong?`
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// prompt the user and get the value
System.out.print("Exactly how many inches are you? ");
int uHeight = in.nextInt();
// converting and outputing the result
System.out.print("How many inches is your mother? ");
int mHeight = in.nextInt();
InchesToCm(mHeight,uHeight);
}
public static double InchesToCm() {
Scanner in = new Scanner(System.in);
System.out.print("Exactly how many inches are you? ");
int inHeight = in.nextInt();
double cmHeight = inHeight * 2.54;
System.out.println("He's " + uHeight + " inches or " + mHeight + " cm.");
return
You should to pass your mHeight and uHeight, in your method because you call it in your main method like this InchesToCm(mHeight,uHeight); so your method should look like this:
public static double InchesToCm(int mHeight, int uHeight) {//pass your values in method
Second you have to return the result in the end :
return cmHeight;//return the result
Note
For the good practice your methods should start with a lowercase letter like #Timothy Truckle said in comment and your class names should start with an upper letter
EDIT
For the good practice your have to use :
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Exactly how many inches are you? ");
int uHeight = in.nextInt();
System.out.println("He's " + uHeight + " inches or " + inchesToCm(uHeight) + " cm.");
System.out.print("How many inches is your mother? ");
int mHeight = in.nextInt();
System.out.println("He's " + mHeight + " inches or " + inchesToCm(mHeight) + " cm.");
//------------------------------^^-------------------------------^^------------------
in.close();//close your Scanner
}
//Your function should take inches and return cm
public static double inchesToCm(int height) {
return height * 2.54;
}
I'm working in a project to make a program to ask the user to find the areas of different shapes, like a triangle, circle and squares.
the following code is to get from the user the area of a triangle which lengths is known, I want to add at the end of this class a return value of total correct answers to use it in main class later to show the progress of his work and scores.
+ what do you recommend to add or improve this program?
package tringle_project;
import java.util.Scanner;
public class Tringle_project
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String a1;
int correctCount = 0;
int incorrect = 0;
int total=(correctCount+incorrect);
do
{
int a = (int)(Math.random() * 20);
int b = (int)(Math.random() * 20);
int c = (int)(Math.random() * 20);
double input;
int p = (a + b + c) / 2;
double area = (Math.sqrt(p * (p - a) * (p - b) * (p - c)));
System.out.println("Welcome to the Tringle Area exercise!");
System.out.println("Enter the area of a tringle if you know the 3 sides as: " + a + ", " + b + ", " + c + " in cm.");
input = keyboard.nextDouble();
while (input != area)
{
System.out.println("Ohh wrong answer :( please try again! ");
input = keyboard.nextDouble();
incorrect++;
}
System.out.println("Excellent Work!");
correctCount++;
System.out.println("To continue enter Yes, to end enter done.");
a1 = keyboard.next();
} while (a1.equalsIgnoreCase("Yes"));
}
}