It gets to the point where it has to print the line System.out.printf("%4s%22s%24s\n","Year"...), and then just stops without printing.
public class WorldPopulationGrowth {
/**
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner( System.in);
long BasePopulation; //The base, or current population
double GrowthRate; //The rate of increase
double GrowthResult; // The pop after growth rate increase
//Time to obtain the numbers needed for Calculation
//Specifically, the growth rate and the base population
System.out.println("Welcome to the world population calculator");
System.out.print("Enter the current world population:");
BasePopulation = input.nextLong();
System.out.println("Enter the current growth rate: (e.g, 1.14% would be .0114): ");
GrowthRate = input.nextDouble();
int Year = 1; //I need this for the next part
System.out.printf("%4s%22s%24s\n", "Year", "Estimated Population", "Change from prior Year");
while (Year <= 75); {// Start of the while
GrowthResult = BasePopulation * (1 + GrowthRate);
System.out.printf("%4d%22d%24d\n", Year, (long) GrowthResult, (long) GrowthResult - BasePopulation);
BasePopulation = (long) GrowthResult;
}//End of the while
}//End of public static
}//End of class
You've got a semicolon after your while loop. That semicolon is an empty statement, and that's what gets executed in the loop. After that, you have an anonymous block (which is what you want to be executed in the loop). It's equivalent to this:
while (Year <= 75) {
// empty
}
{
// anonymous block
GrowthResult = BasePopulation * (1 + GrowthRate);
...
The fix is to remove the semicolon.
Try removing semicolon from this line
while (Year <= 75); {// Start of the while
Should be:
while (Year <= 75) {// Start of the while
Related
I was tasked to create a program that would calculate how fast you must go to reach a certain distance (miles per hour) at a certain time (in hours). You are supposed to consider a 5 minute break for every 100 miles. Also, the program has to be written using 4 methods and a main method. I already did a majority of the program but I don't know how to properly output my results. I am positive that I am doing something wrong with one of the methods but I don't know how to fix it. Heres what I have:
import java.util.Scanner;
public class I95Machine {
public static void userMessage() {
System.out.println("Welcome to I95 Speed Machine");
System.out.println("You will have to supply:\n+ The distance you want to travel, in miles\n+ The time you have available, in hours");
}
public static double computeTravelSpeedOne(double inputDist, double inputTime) {
double stopTime, travelSpeed;
int timeQuotient;
timeQuotient = (int) (inputDist / 100);
stopTime = timeQuotient * 5;
if ((timeQuotient % 100) > 0) {
stopTime += 5;
}
stopTime /= 60;
inputTime = inputTime - stopTime;
travelSpeed = inputDist / inputTime;
if (inputTime > 0) {
return travelSpeed;
} else {
return 0.0;
}
}
public static double inputDistAndTime() {
Scanner keyboard = new Scanner(System.in);
double distNum = 0, timeNum = 0, distance, time;
System.out.print("Enter distance to travel : ");
distNum = keyboard.nextDouble();
distance = distNum;
System.out.print("Enter time available : ");
timeNum = keyboard.nextDouble();
time = timeNum;
return computeTravelSpeedOne(distance, time);
}
public static void displayOutput(double travelSpeed) {
boolean speedLim = computeTravelSpeedOne() > 65;
System.out.print("You will have to travel at ");
System.out.println(computeTravelSpeedOne() + " MPH");
System.out.print("Over the speed limit : ");
System.out.print(speedLim);
}
public static void main(String[] args) {
userMessage();
inputDistAndTime();
displayOutput();
}
}
Not sure if I understand your question, but in displayOutput you call computeTravelSpeedOne without any arguments, this might fail...
This program will prompt the user to enter a medium (either air, water or steel) and the distance. Then calculate the distance a sound wave will travel through the medium.
I wrote the whole program but I didn't read the last bit that my professor added to the homework which is the following paragraph. Now I'm stuck because I'm not quite sure how to add this to my program. I was using an if statements but maybe I can add it in one?
The program prompts for the medium with: "Enter one of the following: air, water, or steel:" and reads the medium. If the medium is not air, water, or steel the program prints the message: "Sorry, you must enter air, water, or steel" and nothing else. Otherwise the program prompts for the following distance input.
I tried a while loop and adding another if statement but really my problem is the syntax. Because I've never had to command the user to type in specific strings.
public class SpeedOfSound {
public static void main(String[] args) {
double distance;
double time;
Scanner keyboard = new Scanner(System.in);
//prompt the user to enter the medium through which sound will
System.out.print("Enter one of the following: air, water, or steel:");
String input;
input = keyboard.nextLine();
// prompt the user to enter a distance
System.out.print("Enter distance in feet: ");
distance = keyboard.nextDouble();
// determine if medium is air, water, steele and calculate
if (input.equals("air")) {
time = (distance / 1100);
System.out.println("The total time traveled is " + time + " feet per second.");
}
else if (input.equals("water"))
{
time = (distance / 4900);
System.out.println("The total time traveled is " + time + " feet per second.");
}
else if (input.equals("steel"))
{
time = (distance / 16400);
System.out.println("The total time traveled is " + time + " feet per second.");
}
}
}
My expected result is to make the user only type in either Air, water, or Steel.
There was several issue with your code and I've taken the liberty of correcting them. Read through the comments to better understand each part of the code.
public class SpeedOfSound
{
/* Best to declare it here so other methods have access to it. */
private static final Scanner keyboard = new Scanner(System.in);
/*
* Declared as a class field so you can use it if you
* have a need for it in addition to time calculated in main.
*/
private static double distance;
/**
* Blocks program execution until a number has been detected as user input.
* #return numeric representation of user input.
*/
public static double getDistance()
{
System.out.println("Enter distance in feet: ");
// CAREFUL: This will throw an exception if the user enters a String
// return keyboard.nextDouble();
while (keyboard.hasNext())
{
/*
* Check if the user input is actually a number
* and if it isn't print an error and get next token
*/
String input = keyboard.nextLine();
try {
return Double.valueOf(input);
}
catch (NumberFormatException e) {
System.out.println("Incorrect input, try again.");
}
}
throw new IllegalStateException("Scanner doesn't have any more tokens.");
}
/**
* Calculate the speed of sound for user input which is limited to:
* <ul>
* <li>Air</li>
* <li>Water</li>
* <li>Steel</li>
* </ul>
* #return total time traveled in feet per second.
*/
public static Double calculate()
{
Double time = null;
//prompt the user to enter the medium through which sound will travel through
System.out.println("Enter one of the following: air, water, or steel:");
// The loop will break the moment time is calculated
while (time == null && keyboard.hasNext())
{
double distance;
String input = keyboard.nextLine();
//determine if medium is air, water, steele and calculate
if (input.equals("air"))
{
distance = getDistance();
time = (distance / 1100);
}
else if (input.equals("water"))
{
distance = getDistance();
time = (distance / 4900);
}
else if (input.equals("steel"))
{
distance = getDistance();
time = (distance / 16400);
}
else System.out.println("Incorrect input, try again.");
}
return time;
}
public static void main(String[ ] args)
{
Double time = calculate();
System.out.println("The total time traveled is " + time + " feet per second.");
}
}
However the way I would tackle this assignment would be to implement the elements in an enum of sort and move the bulk of the calculate() method there. This will allow you to quickly create more elements like air, water and steel without having to create additional if blocks to process them.
Element Enumerator
public enum Element {
AIR("air", 1100),
WATER("water", 4900),
STEEL("steel", 16400);
private final String name;
private final int factor;
Element(String name, int factor) {
this.name = name;
this.factor = factor;
}
/**
* #param element name of the element to calculate time for
* #return total time traveled in feet per second for given element or
* {#code null} if no element matched the given name.
*/
public static Double getTimeTraveledFor(String element)
{
/* Find an element that matches the given name */
for (Element e : Element.values()) {
/*
* Validate the parameter without case consideration.
* This might be a better way of validating input unless
* for some reason you really want a case-sensitive input
*/
if (e.name.equalsIgnoreCase(element)) {
return SpeedOfSound.getDistance() / e.factor;
}
}
return null;
}
}
Revised method
public static Double calculate()
{
Double time = null;
//prompt the user to enter the medium through which sound will travel through
System.out.println("Enter one of the following: air, water, or steel:");
// The loop will break the moment time is calculated
while (time == null && keyboard.hasNext())
{
String input = keyboard.nextLine();
time = Element.getTimeTraveledFor(input);
if (time == null) {
System.out.printf("%s is not a recognized element, try again.", input);
}
}
return time;
}
while(true){
System.out.print("Enter distance in feet: ");
String input;
input = keyboard.nextLine();
//prompt the user to enter a distance
System.out.print("Enter distance in feet: ");
distance = keyboard.nextDouble();
//determine if medium is air, water, steele and calculate
if (input.equals("air"))
{
time = (distance / 1100);
System.out.println("The total time traveled is " + time + "
feet per second.");
break;
}
else if (input.equals("water"))
{
time = (distance / 4900);
System.out.println("The total time traveled is " + time + "
feet per second.");
break;
}
else if (input.equals("steel"))
{
time = (distance / 16400);
System.out.println("The total time traveled is " + time + "
feet per second.");
break;
}
else
System.out.println("wrong choice");
}
I am making a simple average grade calculator. Basically takes in users mark and the percentage of that module and displays the average percentage. The program does work but it has a few glitches which happens in the while loop.
The while loop should end as soon as the user enters any value under -1 but it continues on for a few times and then exits the while loop. Also, it first lets the user enter a number to ensure to start the while loop and then the text 'Enter Mark' comes up which makes the user enter their marks again. Im trying to make the while loop automatically start but dont know how too.
import java.util.ArrayList;
import java.util.Scanner;
public class percentage {
static ArrayList<Double> marks = new ArrayList<>();
static ArrayList<Double> percentage = new ArrayList<>();
static Scanner input = new Scanner(System.in);
static void addingToMarks(double currentmark) {
marks.add(currentmark);
}
public static void main(String[] args) {
System.out
.println("Type in the number of marks you got \n"
+ "in the module. And then type the percentage weight of it.\n"
);
double exitLoop = input.nextDouble();
while (exitLoop > -1) {
System.out.println("Type in your marks");
marks.add(input.nextDouble());
System.out
.println("Type in the weighted percentage of the module: ");
percentage.add(input.nextDouble());
exitLoop = input.nextDouble();
}
System.out.println(percentage);
System.out.println(marks);
System.out.println("Your average percent for the module is: "
+ gradeCalculate());
}
static double gradeCalculate() {
double totalaverageweight = 0;
for (int x = 0; x < marks.size(); x++) {
totalaverageweight += ((marks.get(x) / 100) * percentage.get(x));
}
return totalaverageweight;
}
}
I think a do... while loop will work in this case since the test condition will happen at the end of the loop
do{
////your code goes here
}while(exitLoop!=-1);
edit 1 - I changed all sc.nextInt to Integer.parseInt(sc.nextLine()) and I now have some errors but less
edit 2 - It now runs but I am something getting things printed 2x, the game does not end at the end of round 10 and I'm missing a total wins line at the end. I think the error occurs after a win.
edit 3 - 2x cold/hot printing fixed. fixed the 2x header (repeat line left in wins method). New (and hopefully last error) - first round the game only allows 3 tries, other rounds 4. sample run:
I will choose a number between 1 and 10
You have 3 tries to get it right
Round 1
Enter a new guess: 5
Cold
5
Cold
5
You lose!
You have won 0 out of 1 rounds.
Round 2
Enter a new guess: 5
Cold
5
Cold
5
Cold
5
You lose!
You have won 0 out of 2 rounds.
Round 3
Enter a new guess: 5
Cold
5
Cold
5
Cold
5
You lose!
You have won 0 out of 3 rounds.
class 1:
import java.util.Scanner;
public class GuessRunner
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("I will choose a number between 1 and 10" +
'\n' + "You have 3 tries to get it right" + '\n');
GuessCalc game = new GuessCalc();
while (game.getRounds() <= 10)
{
System.out.println('\n' + "Round " + game.getRounds() + '\n');
System.out.print("Enter a new guess: ");
int guess = Integer.parseInt(sc.nextLine());
do
{
game.rounds(guess);
guess = Integer.parseInt(sc.nextLine());
}
while (game.roundOver == false);
System.out.println(game.wins());
}
sc.close();
}
}
class 2:
public class GuessCalc
{
private int wins;
private int rounds = 1;
private int num = (int) (1 + Math.random() * 10);
private int tries = 0;
public boolean roundOver;
/**
* Runs the rounds and determines if they win
* #return outcome the boolean true if they won or false if they lost
*/
public String rounds(int guess)
{
if (guess == num) //player won
{
wins++;
rounds++;
tries = 0;
System.out.println("You win!");
num = (int) (1 + Math.random() * 10); //new number
roundOver = true;
}
else if (tries == 3) //out of tries
{
rounds++;
tries = 0;
System.out.println("You lose!");
num = (int) (1 + Math.random() * 10); //new number
roundOver = true;
}
else
{
hotOrCold(guess);
roundOver = false;
}
}
/**
* Tells the player if they are hot or cold
*/
public void hotOrCold(int guess)
{
if (guess == num - 1 || guess == num + 1) //if they are off by 1
System.out.println("Hot");
else // if they are further than 1 away
System.out.println("Cold");
tries++;
}
/**
* Returns the number of wins and makes a new header
* #return the String with the number of wins and new header
*/
public String wins()
{return("You have won " + wins + " out of " + (rounds - 1) + " rounds.");}
/**
* Returns the number of rounds played
* #return rounds the number of rounds
*/
public int getRounds()
{return rounds;}
}
try adding
sc.nextLine(); after sc.nextInt(); which will consume the new line character
The thing with Scanner is that Scanner is very, very strange. I've been using it for years and she hates that I use her for only fast and dirty input. I don't even want to begin to describe the bizarre things that happen, but the explanation is usually around how non-nextLine() methods deal with newline characters (whether they consume/ignore them or not)
My advice with scanner is to only ever use its hasNextLine() and nextLine() methods. They are the only methods I found were every human using them can predict the method's behaviour. You can then check if it is a number (matches("[1-9]+[0-9]*")) or just be wild and do Integer.parseInt() directly.
Seeing
game = new GuessCalc(guess);
is a loop looks strange in class 1. That looks like an error since rounds will be reset constantly.
Edit 1:
If your code is not suppose to reset the random number every single round and reset the 'tries' count every round (the code threw away the current game every round) the below code may help you:
import java.util.Scanner;
public class GuessRunner {
public static void main(String[] args) throws InterruptedException {
System.out.print("I will choose a number between 1 and 10" + '\n'
+ "You have 3 tries to get it right" + '\n');
GuessCalc game = new GuessCalc();
while (game.getRounds() <= 10) {
game.playRound();
System.out.println(game.wins());
}
}
}
Second class:
import java.util.Scanner;
public class GuessCalc {
private int wins, rounds = 0, num = (int) (1 + Math.random() * 10);
private int tries = 0;
private Scanner sc=new Scanner(System.in);
/**
* Constructs the game
*
* #param guess
* the player's guess
*/
public GuessCalc() {
}
/**
* Runs the rounds and determines if they win
*
* #return outcome if they won (true) or lost (false);
*/
public boolean playRound() {
startNewRound();
System.out.printf("Round %d \n\n", this.getRounds());
while(true){
System.out.println("Enter a new guess: ");
int guess = Integer.parseInt(sc.nextLine());
printHotOrCold(guess);
if (guess == num) {
wins++;
System.out.println("Jackpot! Setting a new random number");
return true;
}else if(tries==3){
System.out.println("Oops, didn't succeed. Better luck next time. The number was "+num);
return false;//ran out of tries
}else{
//got it wrong but still has guesses left
}
}
}
public final void startNewRound() {
rounds++;
tries = 0;
num = (int) (1 + Math.random() * 10);// set a new random number
}
/**
* Tells the player if they are hot or cold
*/
public void printHotOrCold(int guess) {
int offBy = guess - num;
if (offBy == 1 || offBy == -1) {// if they are over or under by 1
System.out.println("Hot");
} else if (guess != num) {// if they are further than 1 away
System.out.println("Cold");
}
tries++;
}
/**
* Returns the number of wins and makes a new header
*
* #return the String with the number of wins and new header
*/
public String wins() {
String record = String.format("You have won %d out of %d rounds. \n\n",wins,rounds);
return record;
}
/**
* Returns the number of rounds played
*
* #return rounds the number of rounds
*/
public int getRounds() {
return rounds;
}
}
Your code was malformed (couldn't compile) and I don't 100% know your intent (ex unknown if it is 10 rounds to get as many random numbers correct as possible or they have 3 guesses in 10 rounds). Good luck.
Responses to previous question , my initial answer to that question had been solved, but I had another problem when it came down to looping which was later solved by simply using a for loop.
However, my problem is I do not want the user to constantly have to restart the program after an exception is handled, rather I want it to loop the same beginning questions to the user. I've tried placing print statements after the return statements, and also tried completely copying the logic code after the try catch, however, realizing that that would not cause the user to loop unlimited times for the exception. Also, on a side note yes my previous question had good answers, however, no one managed to answer my more recurring problem, which is why no one got the check mark towards their answer.
import java.io.*;
import java.text.DecimalFormat;
public class Test
{
public static void main(String[] args) throws IOException
{
double x;
x = circlemethods(0.0, 0.0, 0.0, 1.0);
}
public static double circlemethods(double volume, double surfacearea,
double area, double radius) throws IOException
{
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
String numInput;
String reqInput;
String amountStr;
double numInt = 0;
double num = 0;
double answer = 0;
double amount = 0;
double answer2 = 0;
double answer3 = 0;
double answer4 = 0;
for (double i = 0; i < 999; i++)
;
try
{
// for (double i = 0; i < 999; i++);
// while (numInt != 999) {
System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
System.out.println("The program will use four methods to achieve this, all calling back to the main method");
System.out.println("Press any key to continue");
numInput = myInput.readLine();
System.out.println("First, what would you like to calculate?");
System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
reqInput = myInput.readLine();
numInt = Double.parseDouble(reqInput);
System.out.println("Now enter the radius of the required shape(Half of diameter)");
numInput = myInput.readLine();
num = Double.parseDouble(numInput);
DecimalFormat nextAmount = new DecimalFormat("0.00");
amountStr = nextAmount.format(amount);
if (numInt == 1)
{
System.out.println("You chose to calculate circumference, given the radius :" + num);
answer = (3.14) * (2) * (num);
System.out.print("The circumference of that sphere is :");
System.out.println(answer + "cm³");
return answer;
}
else if (numInt == 2)
{
System.out.println("You chose to calculate area, given the radius :" + num);
answer2 = (3.14) * 2;
System.out.print("The area of the circle is :");
System.out.println(answer2 + "cm²");
return answer2;
}
else if (numInt == 3)
{
System.out.println("You chose to calculate volume, given the radius :" + num);
answer3 = 4 / 3 * (3.14) * (num) * (3) * (3) * (3);
System.out.print("The volume of that sphere is : cm³");
System.out.println(answer3 + "cm³");
return answer3;
}
else
// if (numInt == 4)
{
System.out.println("You chose to calculate surface area, given the radius :" + num);
answer4 = 4 * (3.14) * (num) * (2) * (2);
System.out.print("The Surface area of that sphere is :");
System.out.println(answer4 + "cm²");
return answer4;
}
} catch (Exception e)
{
System.out.println("Please do not enter any string values, next time input enter a number ");
return 0;
// how to loop this untill the user inputs a number????
}
}
}
First, you use a while(true) loop instead of looping for 999 times. (That loop doesn't actually do anything considering there is a semicolon right after it.)
Then, you remove the return 0; from your catch block.
So it would be
while(true) {
try {
.... //your code
}
catch {...}
} //while loop end bracket
This way, the loop will only end if it reaches one of your return statements.
You need to loop until you get a valid value. One way to do that is loop until a boolean value is set to true. Try something similar to this:
boolean inputIsValid = false;
while (!inputIsValid) { ...
Then when you have determined you have a valid input, add the line:
inputIsValid = true;
Your loop will continue until inputIsValid becomes true.
You could also create an endless while loop. Then when you receive a valid input, break out of the loop:
while(true) {
//when valid input is received
break;
}