Newbie question on stopping an application
- From: "Cardinal" <john.menken@xxxxxxxxxxxx>
- Date: 28 Nov 2005 04:38:11 -0800
I have a simple console application that prompts the user to enter two
numbers and then the program multiplies these two numbers and spits out
the product. No problem so far. The difficulty I'm having is that if
someone enters a negative number, I want the program to reply something
like "Does not accept negative numbers!" then stop. I tried using
"break;" but it generated an error message and said that I was using it
"outside the loop" or something like that. I would be grateful if
someone could give me a clue on what I might use for this. Thank you
very much. My code is below.
public class Kilowatt
{
private double costKiloWattHours; //example 8.42 which means cents
private double hoursUsedPerYear; //example 653
private double annualCost;
public void setCost(double cost)
{
if (cost <= 0)
{
//I want the program to say "You can't enter a negative number."
//Then the program should stop execution.
}
else
{
costKiloWattHours = cost / 100;
}
}
public void setHours(double hours)
{
hoursUsedPerYear = hours;
}
public double getAnnualCost()
{
annualCost = costKiloWattHours * hoursUsedPerYear;
return annualCost;
}
}
import java.util.Scanner;
class Kilowatt_Test
{
public static void main(String[] args)
{
double myCost;
double myHours;
Scanner myScanner = new Scanner(System.in);
System.out.print("What's the cost per kilowatt hour? ");
myCost = myScanner.nextDouble();
Kilowatt myKilowatt = new Kilowatt();
myKilowatt.setCost(myCost);
System.out.print("How many kilowatt-hours are used per year? ");
myHours = myScanner.nextDouble();
myKilowatt.setHours(myHours);
System.out.println("The annual cost is: " +
myKilowatt.getAnnualCost());
}
}
.
- Follow-Ups:
- Re: Newbie question on stopping an application
- From: Thomas Fritsch
- Re: Newbie question on stopping an application
- Prev by Date: Re: Help with an Array Assignment
- Next by Date: Re: Newbie question on stopping an application
- Previous by thread: NoClassDefFoundError for SerializerFactory on Debian Tomcat but it works on SuSE.
- Next by thread: Re: Newbie question on stopping an application
- Index(es):