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"));
}
}
Related
I have created an extremely simple program that prompts the user to enter 3 integers, then determines if the inputted variables create a defined triangle. Is there any tips or advice to concise this for increased efficiency? This is an exercise I put forth for myself. I have only be coding for 6 months and am not there yet as far as efficiency, so any help or advice would be great. Thank you.
import java.util.*;
public class Test1
{
public static void main(String[] args)
{
int[] triangleInput = EnterSides();
DisplayArray(triangleInput);
DetermineValidTriangle(triangleInput);
}
public static int[] EnterSides()
{
Scanner keyboard = new Scanner(System.in);
int[] triangleInput = new int[3];
final int numOfSides = 3;
System.out.println("Please enter " + numOfSides + " integers: ");
for(int x = 0; x < triangleInput.length; ++x)
{
triangleInput[x] = keyboard.nextInt();
}
return triangleInput;
}
public static void DisplayArray(int[] userInput)
{
int[] triangleInput = userInput;
System.out.print("You have entered: " + Arrays.toString(triangleInput));
System.out.println();
System.out.println();
System.out.println("Side A of triangle is " + triangleInput[0] + ", Side B of triangle is " +
triangleInput[1] + ", and Side C of triangle is " + triangleInput[2]);
}
public static void DetermineValidTriangle(int[] userInput)
{
int[] triangleInput = userInput;
boolean isTriangle = false;
if(triangleInput[0] + triangleInput[1] > triangleInput[2])
if(triangleInput[1] + triangleInput[2] > triangleInput[0])
{
if(triangleInput[0] + triangleInput[2] > triangleInput[1])
{
isTriangle = true;
}
}
System.out.println();
if(isTriangle)
System.out.println("Successful triangle has been built!");
else
System.out.println("Sorry, Unsuccessful triangle. The requirement for a triangle is A + B
is greater than C. B + C is greater than A, and A + C is greater than B.");
}
}
Yea delete everything, then replace it with this:
import java.util.Scanner;
//Do not use "import java.util.*;" this will import the entire library in java.util
public class Test1
{
public static void main()
{
Scanner keyboard = new Scanner(System.in);
int trianglePoint1X = keyboard.nextInt();
int trianglePoint1Y = keyboard.nextInt();
int trianglePoint2X = keyboard.nextInt();
int trianglePoint2Y = keyboard.nextInt();
int trianglePoint3X = keyboard.nextInt();
int trianglePoint3Y = keyboard.nextInt();
//No Arrays, they are unneccessary
//No Checks, the triangle does not need to be checked to confirm it's a triangle, the user should have freedom to set points
//Triangle should have it's corners stored in memory instead of it's sides
}
public void drawTriangle()
{
//connect triangle point 1 with 2
//connect triangle point 2 with 3
//connect triangle point 3 with 1
}
}
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);
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 7 years ago.
Improve this question
I looked and could not find anything like what I am wanting to do. I have a method with 3 parameters that I need to call from my main method. I've tried everything I have leaned in class so far, but I cannot fig this out. this is for my Programming in Java Course. Here is what I need to call from my main method:
import java.util.*;// for scanner
import java.text.DecimalFormat;
public class Grades {
//Homework, exam1, and exam2 weights
static double homeworkWeight;
static double examOneWeight;
static double examTwoWeight;
//Homework
static int homeworkNumberOfAssignments;
static int homeworkAssignment1Score;
static int homeworkAssignment1Max;
static int homeworkAssignment2Score;
static int homeworkAssignment2Max;
static int homeworkAssignment3Score;
static int homeworkAssignment3Max;
static int homeworkSectionsAttended;
static int homeworkSectionsAttendedTotal;
static int homeworkSectionsAttendedMax;
double homeworkTotalPoints;
double homeworkMaxPoints;
double homeworkWeightedScore;
//Exam1
static int examOneScore;
static int examOneCurve;
static double examOneMaxPointsAvailable;
double examOneWeightedScore;
//Exam2
static int examTwoScore;
static int examTwoCurve;
static double examTwoMaxPointsAvailable;
double examTwoWeightedScore;
//Grades
static double courseGrade;
static double grade;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
showIntro();
System.out.println("");
System.out.print("Homework and Exam 1 weights? ");
homeworkWeight = console.nextInt();
examOneWeight = console.nextInt();
examTwoWeight = 100 - homeworkWeight + examOneWeight;
System.out.println("Using weights of " + homeworkWeight + " " + examOneWeight + " " + examTwoWeight);
homework();
System.out.println("");
exam1();
//System.out.println("");
//exam2();
//System.out.println("");
//courseGrade(courseGrade; double homeworkWeightedScore; double examOneWeightedScore; double examTwoWeightedScore;);
double d = courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
System.out.println("");
}//
//Shows the intro to the program to the user.
public static void showIntro() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grades in the course.");
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.println("");
System.out.println("Homework:");
System.out.print("Number of assignments? ");
homeworkNumberOfAssignments = console.nextInt();
System.out.print("Assignment 1 score and max? ");
homeworkAssignment1Score = console.nextInt();
homeworkAssignment1Max = console.nextInt();
System.out.print("Assignment 2 score and max? ");
homeworkAssignment2Score = console.nextInt();
homeworkAssignment2Max = console.nextInt();
System.out.print("Assignment 3 score and max? ");
homeworkAssignment3Score = console.nextInt();
homeworkAssignment3Max = console.nextInt();
System.out.print("Sections attended? ");
homeworkSectionsAttended = console.nextInt();
homeworkSectionsAttendedTotal = homeworkSectionsAttended * 4;
homeworkSectionsAttendedMax = 20;
//Calculating total points earned
double totalPoints = homeworkAssignment1Score + homeworkAssignment2Score + homeworkAssignment3Score + homeworkSectionsAttendedTotal;
//Calutaing the max points available to be earned
double maxPoints = homeworkAssignment1Max + homeworkAssignment2Max + homeworkAssignment3Max + homeworkSectionsAttendedMax;
//Formatting with DecimalFormat to remove the decimal and 0 when displaying
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(("Total points = ") + df.format(totalPoints) + " / " + df.format(maxPoints));
//Calculating the weighted score by dividing totalPoints by maxPoints and then multiplying times homeworkWeight
double homeworkWeightedScore = ((totalPoints / maxPoints) * homeworkWeight);
//Printing out weighted score and rounding to the nearest hundreth with Math.round
System.out.println("Weighted score = " + Math.round(homeworkWeightedScore * 100.0) / 100.0);
}
public static void exam1() {
Scanner console = new Scanner(System.in);
System.out.println("Exam 1:");
System.out.print("Score? ");
examOneScore = console.nextInt();
System.out.print("Curve? ");
examOneCurve = console.nextInt();
System.out.println("Total points = " + examOneScore + " / " + examOneCurve);
examOneMaxPointsAvailable = 100;
double examOneWeightedScore = ((examOneScore / examOneMaxPointsAvailable) * examOneWeight);
System.out.println("weighted score = " + Math.round(examOneWeightedScore * 100.0) / 100.0);
}
public static void exam2() {
Scanner console = new Scanner(System.in);
System.out.print("Exam 2:");
System.out.print("Score? ");
examTwoScore = console.nextInt();
System.out.print("Curve? ");
examTwoCurve = console.nextInt();
System.out.print("Total points = ");
System.out.println("weighted score = ");
}
public double courseGrade(double homeworkWeightedScore, double examOneWeightedScore, double examTwoWeightedScore) {
return homeworkWeightedScore + examOneWeightedScore + examTwoWeightedScore;
}
}
There's a couple factors missing from your question that makes me unable to completely answer them, but:
Is the courseGrade method in a separate class or in the same class as your public static void main method?
Yes: Create a new instance of the separate class by doing: public SeparateClass instance = new SeparateClass(); inside of public static void main
After that, call this from your main method: double grade = instance.courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
No: Make the courseGrade method static, you can't call a non-static method from a static method (replace public double courseGrade with public static double courseGrade). After that, inside of your main method, do this: double d = courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
I hope this helps.
here is my source code, I get the error for each of my strings
I am not sure If there is anything else I am missing.
import java.util.Scanner;
public class RoseBowl {
public static void main(String[] args) {
int programsOrdered;
double programCost, salesTax, shippingFee, handlingFee, totalCost;
final double PROGRAM_RATE = 12.95;
String shippingMethod, groundType, taxExempt, G, S1, N1, P, Y, N2, B, S2, F;
Scanner input = new Scanner (System.in);
// user input
System.out.print ("Enter the number of programs ordered: ");
programsOrdered = input.nextInt ();
double programCostForOUTPUT = (PROGRAM_RATE * programsOrdered);
while(programsOrdered > 0) {
System.out.print ("Choose shipping method (<G>round, S1(second day), N1(next day), or <P>riority): ");
shippingMethod = input.next();
// PROCESS
// ground shipment
if (shippingMethod.equalsIgnoreCase("G")) {
System.out.print("Choose a ground type (<B>ulk), S2(second class), <F>irst class): ");
groundType = input.next ();
System.out.print("Select one: <B>ulk, <S>econd Class, <F>irst Class ");
groundType = input.next();
// calculate ground shipment
// FOLLOW THIS PROCESS, RUN IT, IT WORKS FOR JUST GROUND SELECTION AND THEN BULK
if(groundType.equalsIgnoreCase("B")) {
shippingFee = 3.00 + (.01 * programCost);
}
else if(groundType.equalsIgnoreCase("")){
}// <--if its not b then it is what for other cases?
else if(groundType.equalsIgnoreCase("")) {
}
}
// calculate program cost
programCost = (PROGRAM_RATE * programsOrdered);
if (shippingMethod == "G" && groundType == "S2") //follow the format above
shippingFee = (4.00 + (.01 * programCost));
else if (shippingMethod == G && groundType == F)
shippingFee = (4.50 + (.01 * programCost));
// calculate second day shipment
if (shippingMethod == S1)
shippingFee = (5.95 + (.02 * programCost));
// calculate next day shipment
if (shippingMethod == N1)
shippingFee = (9.95 + (.03 * programCost));
// calculate priority shipment
if (shippingMethod == P)
shippingFee = (14.95 + (.05 * programCost));
// calculate handling fees
if (shippingFee + programCost < 500)
handlingFee = 2.50;
else if (shippingFee + programCost >= 500)
handlingFee = 4.50;
System.out.print("Is the order tax exempt? (<Y>es or N(no): ");
taxExempt = input.next();
// calculate tax
if(taxExempt.equalsIgnoreCase("N"))
salesTax = (.0675 * programCost);
// calculate order total
totalCost = (programCost + shippingFee + handlingFee + salesTax);
// OUTPUT
System.out.printf ("Number of programs ordered: $ %4.2f%s%n" + programsOrdered);
System.out.printf ("program cost: $ %4.2f%s%n" + programCostForOUTPUT);
System.out.printf ("Sales tax: $ %4.2f%s%n" + salesTax);
System.out.printf ("Shipping fee: $ %4.2f%s%n" + shippingFee);
System.out.printf ("Handling fee: $ %4.2f%s%n" + handlingFee);
System.out.printf ("Total order amount: $ %4.2f%s" + totalCost);
// close input
input.close ();
} // ending while loop here
}
} // end main
// end class
yeah I must be over looking something small
Here :
double programCost, salesTax, shippingFee, handlingFee, totalCost; // no initial value
...
if(groundType.equalsIgnoreCase("B")) {
shippingFee = 3.00 + (.01 * programCost); // accessed here
}
...
// calculate program cost
programCost = (PROGRAM_RATE * programsOrdered); // it is only assigned later
you access programCost before it is ever initialized. I'm not sure if that's the only error.
You must assign a value to all your local variables before accessing them. Perhaps you should give them default values in their declaration. For example :
double programCost = 0.0; // or some other default value that makes sense