floorspace do-while program - java

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);
}
}

Related

How to implement the function into the main

So I have a working code that asks the user the height & width of a rectangle and then outputs the rectangle in asterics (*).
Now I want to implement a function public static int askPositiveInteger(String question, String messageIfError) {...} that uses scanner.hasNextInt() (checks for integer) and scanner.next() (throw away whatever nonsense the user wrote).
The function is supposed to ask the user for a positive integer using the message question. If the input is wrong it prints the error message messageIfError and asks again.
I wrote the function:
public static int askPositiveInteger(String question, String messageIfError) {
int num = -1;
do {
System.out.print("Please enter a positive integer number: ");
if (scan.hasNextInt()) {
num = scan.nextInt();
} else {
System.out.println("I need an int, please try again.");
scanner.next();
}
} while (num <= 0);
}
But I'm not sure how to implement it into my code:
public static void main(String[] args) {
int height, width, i, j;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the height of the rectangle: ");
height = scanner.nextInt();
System.out.print("Enter the width of the rectangle: ");
width = scanner.nextInt();
for(i = 1; i <= height; i++){
for(j = 1; j <= width;j++){
System.out.print("*");
}
System.out.print("\n");
}
scanner.close();
}
Your function dosen't really use the parameters String question and String messageIfError. You can integrate them in you function by just swap out the
System.out.print("Please enter a positive integer number: "); and
System.out.println("I need an int, please try again.");
with
System.out.print(question); and System.out.println(messageIfError);.
this would result in :
public static int askPositiveInteger(String question, String messageIfError, Scanner scan) {
int num = -1;
while(num <= 0){
System.out.print(question);
num = scan.nextInt();
if(num <= 0){
System.out.println(messageIfError);
}
scan.nextLine();
}
return num;
}
I changed the function also, that you take an existing Scanner and scan of the given one.
Implementing this new function in your Main-Programm would look like follows:
public static void main(String[] args) {
int height, width;
Scanner scan = new Scanner(System.in);
height = askPositiveInteger("Enter the height of the rectangle: ","I need an int, please try again.", scan);
System.out.println("h = " + height);
width = askPositiveInteger("Enter the width of the rectangle: ","I need an int, please try again.", scan);
scan.close();
for(int i = 1; i <= height; i++){
for(int j = 1; j <= width;j++){
System.out.print("*");
}
System.out.print("\n");
}
}
Is that roughly what you thought of?

Unsure what to use for a sentinel controlled while loop - Java

I'm currently a beginner in Java Programming.
I'm having a little bit of trouble with my while loop that has a sentinel value.
Everything works until I add the while loop, however it's required so I can exit when the value '999' is entered.
I'm also not sure what to add for the 'if' values.
Any help would be appreciated!
import java.util.Scanner;
public class SumAverage {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.printf("Please Enter the first number%n");
int num1 = keyboard.nextInt();
System.out.printf("Please enter the second number%n");
int num2 = keyboard.nextInt();
System.out.printf("Please enter the third number%n");
int num3 = keyboard.nextInt();
int sum = num1 + num2 + num3; //calculates sum
int average = (num1 + num2 + num3) / 3; //calculates average
while (num1 != ) {
if (sum > 1)
System.out.printf("Sum: %s %nAverage: %s", sum, average);
else if (sum < 1)
System.out.printf("Sum: %s %nAverage: %.2f", sum, average);
}
}
}
You can do it in the following manner:
import java.util.Scanner;
public class SumAverage {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
int input,sum,avg,count;
do{
System.out.printf("Please enter number" + (count+1) + "%n");
input = keyboard.nextInt()
sum += input;
count += 1;
avg = sum/count;
}while(input != 999);
//Do whatever is to be done once sentinel is input.
}
You can modify the while loop as follows
while(num1 !=999 || num2 !=999 || num3 !=999)
|| is used as OR operator. So whenever any input value is 999 the loop wont execute.

Java code - area of a polygon

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);
}
}

Using a for loop to read ONLY 5 numbers and average them. JAVA

Really having issues with this program I'm making. I've searched this site and a few others, although have yet to find a solution. It may look like I'm just soliciting help but I truly am stuck. I am to make a program that reads in 5 numbers from the user and average those numbers. My extent of knowledge of Java is the Scanner class and for loops, yet haven't used while loops yet. Here is the very poorly written code:
public class Average5
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int num;
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
num = sc.nextInt();
}
I honestly have no clue what to do. More or less self taught.
public class Average5 {
public static void main(String args[]) {
int numlenngth = 5;
double total = 0;
Scanner sc = new Scanner(System.in);
for (int num1 = 0; num1 < numlenngth; num1++) {
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : " + (total / numlenngth));
}
}
output >>
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 2
Average : 1.2
For calculating exact average, you need to take double(sum) instead of int and add(sum) everytime with the user value.
public class Average5
{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to enter for calculating average: ");
int totalCount = sc.nextInt();
double sum=0;
for(int i= 0; i<totalCount; i++)
{
System.out.print("Please enter a number: ");
sum += sc.nextDouble();
}
System.out.println("Average of number is"+(sum/totalCount));
}
This is almost the same as the others posted, but it is limited to entering only 5 numbers and it takes care of possibly resulting floating number in the final division:
import java.util.Scanner;
public class Average5 {
private static final int TOTAL = 5;
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
double sum = 0;
System.out.format("You have to enter %d numbers now.\n", TOTAL);
for (int cnt = 1; cnt <= TOTAL; cnt++) {
System.out.format("Please enter number %d of %d: ", cnt, TOTAL);
sum += scanner.nextInt();
}
System.out.format("The average is %f.\n", sum / TOTAL);
scanner.close();
}
}
Here you can use the array to store the numbers:
public class Average5 {
private static final int MAX = 5;
public static void main(String[] args) {
int[] numbers = new int[MAX];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < MAX; i++) {
System.out.println("Please type the number");
numbers[i] = sc.nextInt();
}
float average = getAverage(numbers);
System.out.println("The average of the five numbers: " + average);
}
public static float getAverage(int[] arg0) {
int sum = 0;
float Ret = 0.0f;
if(arg0 != null) {
for(int i = 0; i < MAX; i++) {
sum += arg0[i];
Ret = sum / MAX;
}
return Ret;
}
}
This is not the only way to slove this problem.
int num = 0;
float total = 0f;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : "+(total/num));

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