Java code - area of a polygon - java

I have some code with no compile errors, but after I enter the second number while its running it crashes on me :(
Heres what I have:
import java.util.Scanner;
public class Assignment536 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of sides: ");
int numberOfSides = input.nextInt();
System.out.println("Enter the side: ");
double side = input.nextInt();
System.out.println("The area of the polygon is: " +area(numberOfSides, side));
input.close();
}
public static double area(int n, double side) {
double answer = (n*(side*side))*(4*(Math.tan((Math.PI*n))));
return answer;
}
}
Any help would be greatly appreciated!
Thank you,
Sebastian

Add input.nextLine() between the numberOfSlices and side request...
System.out.println("Enter the number of sides: ");
int numberOfSides = input.nextInt();
input.nextLine();
System.out.println("Enter the side: ");
double side = input.nextInt();
After requesting numberOfSlices there is still a carriage return/line feed in the input buffer, when you try and request the side value Scanner fails because it can't convert the the carriage return/line feed to a double type.

You should change:
final double side = input.nextInt();
for
final double side = input.nextDouble();
if you want to read a double.

The last part of your formula is wrong. It should be (Math.pi/n) .
import java.util.Scanner;
public class CalcAreaPolygon {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
double area;
final double PI; /method in the formula
double side;
int n;
PI = Math.PI;
System.out.println("Enter the number of sides: ");
n = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter the side: ");
side = scanner.nextDouble();
area = (n * (side * side)) / (4 * (Math.tan(PI/n)));
System.out.println("The area of the polygon is " + area);
}
}

Related

Formatting, Big Decimal, interest to percent please

Can someone please explain the usage not just answer I really would like to learn how to do this. This is my 2nd month using Java and please explain formatting usage in Java. Thank you so much. I really appreciate it. Feel free to ask any other question in regards C++ or python. I am in need of help in formatting, big decimal usage and how to set
import java.util.*;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.math.*;
public class Main{
public static void main(String[] args)
{
Scanner myCalculation = new Scanner(System.in);
System.out.print("Welcome to the Interest Calculator \n\n");
String option = "y";
while (option.equalsIgnoreCase("y"))
{
System.out.print("Enter Loan Amount: ");
//double loanAmount = 520000;
double loanAmount = myCalculation.nextDouble();
//Get Interest rate from user
System.out.print("Enter Interest Rate: ");
// double interRate = .05375;
double interRate = myCalculation.nextDouble();
double interest = loanAmount * interRate;
System.out.printf("%.3f", interest);
System.out.println();
//prompt user to continue? if he enter y then it will Continue
//else it will stop
//System.out.println("Continue? (y:n): ");
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
//do whatever
System.out.println("Would you like to continue? (yes or no)");
String s = scan.nextLine();
if(s.equals("no")) {
stop = true;
}
}
}
}
}
Scanner in = new Scanner(System.in);
System.out.print("enter double");
double d = in.nextDouble(); //doubles
System.out.print("enter int");
int i = in.nextInt(); //ints
System.out.print("enter text");
String text = in.next(); //gets a string up to the first space
in.nextLine();
System.out.print("enter text w/ spaces");
String line = in.nextLine(); //gets a string up to the first space
System.out.println(d);
System.out.println(i);
System.out.println(text);
System.out.println(line);
in.close();
System.out.println(new DecimalFormat("#.###").format(4.567346344634));

Have trouble getting an input using Scanner Class

I'm going through my Java text book and for some reason I cannot compile the following code.
import java.util.*;
public class ComputeAreaWConsoleInput
{
public static void main (String [] args)
{
//Create Scanner Obj
Scanner sc = New Scanner(System.in);
//Get Radius
System.out.print("Please Enter the Radius: ");
double radius = sc.nextdouble();
//determine area
double area = 3.14159 * radius * radius;
//display results
System.out.println("The Area of the Circle w/ radius(" + radius +") is: "
+ area);
}
}
I am getting the following error:
/tmp/java_H98cOI/ComputeAreaWConsoleInput.java:8: error: ';' expected
Scanner sc = New Scanner(System.in);
^
1 error
What shall be done to compile the code?
Two changes to your program.
Change New to new.Change the line
Scanner sc = New Scanner(System.in);
to
Scanner sc = new Scanner(System.in);
and other error in the program is scanning a double. Please change double to Double.So change the below line
double radius = sc.nextdouble();
to
double radius = sc.nextDouble();
It should work fine!
See my comment: Here is the fixed version of your code:
public static void main (String []
{
//Create Scanner Obj
Scanner sc = new Scanner(System.in);
//Get Radius
System.out.print("Please Enter the Radius: ");
double radius = sc.nextDouble();
//determine area
double area = 3.14159 * radius * radius;
//display results
System.out.println("The Area of the Circle w/ radius(" + radius +") is: " + area);
sc.close(); // DO NOT forget this
}
You've written:
New Scanner(System.in);
You N in New is capital.
The actual keyword is new and not New.
Solution:
Change your line of code to:
new Scanner(System.in);
And there is another error.
It should be:
sc.nextDouble(); // with 'D' capital
and not
sc.nextdouble();

How do you store integer into a variable and computeAvg in java?

I am trying to write a Java program that:
In the main method, prompt the user for an integer number.
Store the number in a variable called inputNum.
Pass the inputNum to a method called computeAvg.
In computeAvg, prompt the user to input double values as many times as inputNum. computeAvg method should calculate and return the average of real numbers that user entered.
Print the result in your main method.
This is my code
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
computeAvg();
}
public static void computeAvg() {
System.out.println(inputnum);
System.out.println("Enter double values as inputnum ");
int y;
y=keyboard.nextInt();
}
}
There are several changes to be done in your code:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
System.out.println("The average is"+computeAvg(inputnum));
}
public static double computeAvg(int y)
{
double[] arr = new double[y];
System.out.println(y);
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
double sum = 0;
for(double a:arr){
sum +=a;
}
System.out.println(sum);
double average = sum/arr.length;
return average;
}
First one is that the value you first taken as the user input must be passed to the method. Here I done it in computeAvg(inputnum) And expect this method to return a double value.
Second one is You should declare the method to return a value void means no return. change it to double
public static double computeAvg(int y)
take the parameter from the main method (value you taken from the user.)
If you need to store multiple values better solutions is array.(There are many methods bust for a beginner stick to arrays) crate a double array to take multiple double values.
double[] arr = new double[y];
next loop your code for the number of times the user input and take the double values.
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
next create a double value sum and get the addition and the divide it to get the average (another double value).
for(double a:arr){
sum +=a;
}
Finally return the average to the main method where it prints.
I used static Scanner keyboard = new Scanner(System.in); because I used the same scanner in both methods.
Feel free to ask any question regarding the code.
I hope the comments in the code are self explanatory for what the problem is asking and how the code works:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer? ");
// here you are asking for the number of double numbers that will be
// entered
int inputnum = keyboard.nextInt(); // asking for the int input (varibale
// is stored in inputnum)
System.out.println("Average for all " + inputnum + " numbers is: "
+ computeAvg(inputnum));
}
public static double computeAvg(int inputnum) {
Scanner keyboard = new Scanner(System.in);
double eachInput = 0.0;
double sumInputs = 0.0;
for (int counter = 1; counter <= inputnum; counter++) {
System.out.println("Please enter a double as input #" + counter
+ ": ");
eachInput = keyboard.nextDouble(); // asking for double input
sumInputs += eachInput; // adding up each input
}
// calculating and returning average
return sumInputs / (double) inputnum;
}

floorspace do-while program

I am supposed to write a program that calculates the total floor space in a house. The program prompts the user to enter the length & width of at least one room and it needs to verify with the user if he wants to enter more room dimensions.
It isn't working. Someone please help me?
import java.util.*;
public class FloorSpace
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double length = 0.0, width = 0.0, floorSpace = 0.0;
char ans;
do
{
System.out.print("Enter length: ");
length = input.nextDouble();
System.out.print("Enter width: ");
width = input.nextDouble();
floorSpace = length * width;
floorSpace += floorSpace;
System.out.print("Do you want to enter more room dimensions? (y/n): ");
ans = input.nextLine().charAt(0);
}
while (ans == 'y');
System.out.println("\nTotal floor space is " + floorSpace);
}
}
Oh my I just found out something's wrong with my computation formula. Can someone please help me.
You are setting floorSpace to length * width every time and then incrementing that value by itself (which is really just multiplying it by two).
Replace
floorSpace = length * width;
floorSpace += floorSpace;
with just
floorSpace += length * width
Try this:
import java.util.*;
public class FloorSpace
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double length = 0.0, width = 0.0, floorSpace = 0.0;
char ans='n'; //not for default
do
{
System.out.print("Enter length: ");
length = input.nextDouble();
System.out.print("Enter width: ");
width = input.nextDouble();
floorSpace += length * width;
System.out.print("Do you want to enter more room dimensions? (y/n): ");
if (input.hasNext()){
ans = input.next().charAt(0);
}
}
while (ans == 'y');
System.out.println("\nTotal floor space is " + floorSpace);
}
}
Regards
Instead of:
ans= input.nextLine().charAt(0);
use:
ans = input.next().charAt(0);
To fix your formula use:
floorSpace += length * width;
and remove:
floorSpace = length * width;
So the final solution looks like:
import java.util.*;
public class FloorSpace
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double length = 0.0, width = 0.0, floorSpace = 0.0;
char ans;
do
{
System.out.print("Enter length: ");
length = input.nextDouble();
System.out.print("Enter width: ");
width = input.nextDouble();
floorSpace += length * width;
System.out.print("Do you want to enter more room dimensions? (y/n): ");
ans = input.next().charAt(0);
}
while (ans == 'y');
System.out.println("\nTotal floor space is " + floorSpace);
}
}

UnknownFormatConversionException in a program that prints a percentage

I have to write a program where I put in baseball stats and it comes out with slugging % batting avg and re says the name of the player then put it on a sentinel loop. My current code is below. I'm trying to get it to work with just one before I turn it into a loop. When I run to test, I get UnknownFormatConversionException. What does it mean? How can I fix my code?
import java.util.Scanner;
public class bata
{
public static void main(String[] args) throws Exception
{
double ba,sp,tb;
int tri,dou,sin,hr,ab,hits;
String name;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Singles");
sin = sc.nextInt();
System.out.print("Enter Doubles");
dou = sc.nextInt();
System.out.print("Enter Triples");
tri = sc.nextInt();
System.out.print("Enter Homeruns");
hr = sc.nextInt();
System.out.print("Enter At bats");
ab = sc.nextInt();
System.out.print("Enter Player name");
name = sc.nextLine();
System.in.read();
tb= (sin + (dou*2) + (tri *3) +(hr *4));
hits = sin+dou+tri+hr;
sp= tb/ab;
ba= hits/ab;
System.out.println(""+name);
System.out.printf("Slugging % is %.3f\n", sp);
System.out.printf("Batting avg os %.3f\n", ba);
}
}
Escape % sign,by using double %%:
System.out.printf("Slugging %% is %.3f\n", sp);
// ^------------- escaping
UnknownFormatConversionException happens when you are expecting an integer and read a string from your scanner. It would be helpful if you could post your input file.
Also, escape the % sign using another %.
System.out.printf("Slugging %% is %.3f\n", sp);

Categories

Resources