Basically, the program I am supposed to write is to get the energy usage from the customer for 12 months and then output the total usage, price for two tariffs (the formulas are included in the code) and say which tariff is cheaper. But it also has to check whether the input for each of those 12 months is within the range (greater than "0" AND less or equal to "1000").
I have found a fairly easy(?) way to do it using arrays, however I have no idea how to check whether each one of the integers scanned to be in that array are actually within the range 0 < int <= 1000
If the integer is less than 0 or greater than 1000, the program has to output a line "Please enter a valid amount" and ask for the same integer again, so that it doesn't store the wrong value, if it makes sense?
import java.util.Scanner;
public class EnergyConsumptionExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int total_usage;
float t1_cost, t2_cost;
final int MAX_USAGE = 1000, MIN_USAGE = 0;
int[] energyCons = new int[12];
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
energyCons[month] = scan.nextInt();
}
int totalCons = 0;
for (int month = 0; month < energyCons.length; month++) {
totalCons += energyCons[month];
}
System.out.println();
System.out.println("Total usage for the year was " + totalCons + " kWh");
t1_cost = (float) (totalCons * 0.1);
t2_cost = (float) ((totalCons * 0.09) + 50);
System.out.println("Using tariff one, the cost is: " + t1_cost);
System.out.println("Using tariff two, the cost is: " + t2_cost);
System.out.println();
if (t1_cost > t2_cost) {
System.out.println("Tariff two would be cheaper for this customer.");
} else {
System.out.println("Tariff one would be cheaper for this customer.");
}
}
}
Change your input reading loop to something like this:
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
int inputValue = scan.nextInt();
while (inputValue < 0 || inputValue > 1000) {
System.out.println("Please enter a valid amount: ");
inputValue = scan.nextInt();
}
energyCons[month] = inputValue;
}
Related
Im trying to configure my code to tell the user to re enter a number, taking them back to the scanner if it falls outside of my specified range of 25
long number;// declares variables for storing number
long factorial = 1;// declare variable for storing factorial
System.out.println("Enter a number between 1 and 25"); // tells user to enter number
number = scanner.nextLong();
if (number <0)
System.out.println("Positive numbers only");// if number entered is negative
else if (number > 25)
System.out.println("Number to large to print");
else if (number <= 1)// if number entered is 0 or 1
System.out.printf("The factorial of " + number+ " is equal to " + factorial);
else {
// if user enter 10, counter starts at 10 and runs to two
for(long mynumber = number; mynumber >= 1; mynumber--) {
factorial = factorial*mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and storing again in factorial variable
}
System.out.println("The factorial of " + number +" is equal to " + factorial);
}
To simplify the logic, you could extract it to the separate method. The logic itself is pretty strightforward:
in loop
ask a number
check if the number within the bounds
if not repeate or return if yes
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
int num = getNumberWithin(scan, 1, 25);
}
private static int getNumberWithin(Scanner scan, int lo, int hi) {
while (true) {
System.out.format("Enter a number between %d and %d: ", lo, hi);
int num = scan.nextInt();
if (num >= lo && num <= hi)
return num;
System.err.format("The number should be between %d and %d\n", lo, hi);
System.out.println();
}
}
boolean correctInputn = false;
while(!correctInputn)
{
long number;// declares variables for storing number
long factorial = 1;// declare variable for storing factorial
System.out.println("Enter a number between 1 and 25"); // tells user to enter number
number = scanner.nextLong();
if (number <0) {
System.out.println("Positive numbers only"); // if number entered is negative
correctInputn = false;
continue; // if user enters number less than 0 loops back to code start
} else if (number > 25) {
System.out.println("Number to large to print");
correctInputn = false;
continue; // if user enters number over 25 loops back to code start
} else {
// if user enter 10, counter starts at 10 and runs to two
for(long mynumber = number; mynumber >= 1; mynumber--) {
factorial = factorial * mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and stored again in factorial variable
}
System.out.println("The factorial of " + number +" is equal to " + factorial);
break;
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
import java.util.Scanner;
public class ToStoersteTall{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
int biggest = 0;
for (int i = 3; i <= tall; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
biggest = num1;
if(biggest < num3){
biggest = num3;
}
}
System.out.println(biggest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
A couple things:
good practice to close scanner (and IO-related resources in general)
reduced if-statement blocks bloat for easier readability
you specify 2 guaranteed numbers, so attempt to parse those before looping
can remove system.exit calls or replace system.exit and move bulk of code back into the larger if-else blocks as originally state in OP (but I refer back to the sake of readability)
added check for the first and second numbers input to make sure high1 is highest value, and high2 is second highest value.
keep order while looping and checking values (note: does not use array), if the number is a new high, replace high1 and move high1's value down to high2, or if the number is a second (new) high, replace high2. If values are equal, this logic is excluded and you may want to specify based on your own constraints
import java.io.IOException;
import java.util.Scanner;
public class ToStoersteTall {
public static void main(String[] args) throws IOException {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
int n = 0;
if (reader.hasNextInt()) {
n = reader.nextInt();
} else {
System.out.println("Vennligst oppgi et heltall større eller lik 2.");
System.exit(-1); // quits execution
}
if (n < 2) {
System.out.println("Please enter an integer equal or higher than 2.");
System.exit(-2);
}
// Since guaranteed 2 numbers, parse and assign now
int high1 = 0, high2 = 0;
System.out.println("Enter value # 1");
if (reader.hasNextInt())
high1 = reader.nextInt();
System.out.println("Enter value # 2");
if (reader.hasNextInt())
high2 = reader.nextInt();
// check to see if a switch to keep correct highest order, swap values if so
if (high1 < high2) {
int t = high2;
high2 = high1;
high1 = t;
}
// loop won't execute if only 2 numbers input, but will if 3 or more specified at start
for (int i = 2; i < n; ++i) {
System.out.println("Enter value #" + (i + 1));
if (reader.hasNextInt()) {
int t = reader.nextInt();
if (t > high1) {
high2 = high1; // throw away high2 value and replace with high1
high1 = t; // replace high1 value with new highest value
} else if (t > high2) {
high2 = t;
}
} else {
System.out.println("Please enter an interger");
}
}
reader.close();
System.out.println("The two highest numbers are: " + high1 + ", " + high2);
}
}
You're already keeping track of the biggest, so why not keep track of the second biggest? Another easy way of solving this problem is to keep all the numbers in a list, sort the list by number size, and grab the two highest entries.
I tried your code and used an array to solve the problem.
import java.util.Scanner;
public class Main {
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
public static void main(String[] args) {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
int[] array = new int[numbers];
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
array[0] = num1;
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
array[1] = num2;
int biggest = 0;
for (int i = 3; i <= numbers; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
array[i-1] = num3;
}
System.out.println("second largest number is" + secondHighest(array));
int largest = 0;
for(int i =0;i<array.length;i++) {
if(array[i] > largest) {
largest = array[i];
}
}
System.out.println("Largest number in array is : " +largest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
Test
How many numbers? (minimum 2)?:
6
Enter value #1
3
Enter value #2
4
Enter value #3
5
Enter value #4
6
Enter value #5
7
Enter value #6
8
second largest number is7
Largest number in array is : 8
There is a logic error in your program. If numbers is 2, then the for loop never gets executed, and the value of biggest remains zero because it is never updated. Change your declaration of biggest to reflect the current maximum value found so far.
int biggest = num1 > num2 ? num1 : num2;
That way if the for loop never executes then biggest will be the maximum value of the first two numbers.
As for keeping track of the second highest value, you could introduce another variable secondBiggest, initialised in a similar manner to biggest, and then write logic to update this value in your for loop. However, in my opinion, it would be much easier to change your strategy to hold the entered values into an array, then when all inputs have been entered, calculate whichever values you desire from the array. This would lead to a much cleaner solution IMO.
(I have assumed that tall in the for loop is actually meant to be numbers...)
import java.util.Scanner;
public class Foo{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if(reader.hasNextInt()){
int numbers = reader.nextInt();
if(numbers >= 2){
int[] list = new int[numbers];
for(int i = 0; i < numbers; i++){
System.out.println("Enter value #" + (i + 1));
if(reader.hasNextInt())
list[i] = reader.nextInt();
}//for
int biggest = 0;
int secondBiggest = 0;
// find the values you want
for(int i = 0; i < numbers; i++){
if(list[i] > biggest){
secondBiggest = biggest;
biggest = list[i];
}//if
else if(list[i] > secondBiggest)
secondBiggest = list[i];
}//for
// print your results
System.out.println("The biggest integer is: " + biggest);
System.out.println("The second biggest integer is: " + secondBiggest);
}//if
}//if
}//main
}//class
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to make a program that takes user generated monthly rainfall numbers and and averages them, finds the max and min, finds standard deviation etc. I seem to have most everything down but my "find numbers above and below the average" doesn't seem to be working. Also i cant figure out how to let the user make another choice once they have selected and then been given the desired info. Any help would be greatly appreciated.
example output
import java.util.Arrays;
import java.util.Scanner;
public class RainfallAnalyzer {
public static void main(String[] args) {
double theRainfall = 0;
double total = 0;
Scanner scan = new Scanner(System.in);
double[] rainfall = new double[12];
System.out.println("Enter the rainfall measurements for this year: ");
for (int i = 0; i < rainfall.length; i++) {
theRainfall = scan.nextDouble();
rainfall[i] = theRainfall;
total += rainfall[i];
}
int choiceentry = -1;
loop:
while (choiceentry !8) {
System.out.println("1. print all rainfall measurements");
System.out.println("2. print the avererage rainfall");
System.out.println("3. print the maximum and minimum rainfall measurements");
System.out.println("4. print the number of months above average rainfall");
System.out.println("5. print the number of months below average rainfall");
System.out.println("6. print the median rainfall measurement");
System.out.println("7. print the standard deviation");
System.out.println("8. exit");
if (scan.hasNextInt()) {
choiceentry = scan.nextInt();
}
switch (choiceentry) {
case 1:
for (int i = 0; i < rainfall.length; i++) {
System.out.println("Month # " + (i + 1) + ": " + rainfall[i]);
}
break loop;
case 2:
total = total / 12;
System.out.println("This year's average rainfall: " + total);
break loop;
case 3:
Arrays.sort(rainfall);
System.out.println("Min value " + rainfall[0]);
System.out.println("Max value " + rainfall[rainfall.length - 1]);
break loop;
case 4:
int numRainfallAbove = 0;
for (int i = 0; i < rainfall.length; i++) {
if (rainfall[i] >= avg) {
numRainfallAbove++;
} else {
}
}
System.out.println("Number of months above the average rainfall: " + numRainfallAbove);
break loop;
case 5:
int numRainfallBelow = 0;
for (int i = 0; i < rainfall.length; i++) {
if (rainfall[i] <= total) {
numRainfallBelow++;
} else {
}
}
System.out.println("Number of months below the average rainfall: " + numRainfallBelow);
break loop;
case 6:
double median;
if (rainfall.length % 2 == 0) {
median = ((double) rainfall[rainfall.length / 2] + (double) rainfall[rainfall.length / 2 - 1]) / 2;
} else {
median = (double) rainfall[rainfall.length / 2];
}
System.out.println("This year's median rainfall: " + median);
break loop;
case 7:
double theDeviation = deviation(rainfall, total);
System.out.println("The standard deviation is " + theDeviation);
break loop;
}
}
}
public static double deviation(double[] rainfall, double total) {
double endResult = 0;
double temporary = 0;
double arraySum = 0;
double average = total;
double sum = 0;
for (int i = 0; i < rainfall.length; i++) {
sum += Math.pow((rainfall[i] - average), 2);
}
temporary = sum / (rainfall.length - 1);
endResult = Math.sqrt(temporary);
return endResult;
}
}
Change the code within your case 4:
int numRainfallAbove = 0;
for(int i = 0; i < rainfall.length; i++){
if(rainfall[i] >= total){
numRainfallAbove++;
} else{}
}
System.out.println("Number of months above the average rainfall: "+numRainfallAbove);
break loop;
To this:
int numRainfallAbove = 0;
double avg = total / 12;
for (int i = 0; i < rainfall.length; i++) {
if (rainfall[i] >= avg) {
numRainfallAbove++;
}
}
System.out.println("Number of months above the average rainfall: " + numRainfallAbove);
break loop;
The issue is that you compare the monthly rainfall to the total instead of the average. You will need to do something similar for your "number of months with below average rainfall".
To make it keep asking for more choices as long as the user doesn't exit, change the while loop to:
while (choiceentry != 8) {
As an aside that does not directly relate to your question, try to indent your code properly when you post, and DO NOT use goto statements or breaks which direct to labels.
Also i cant figure out how to let the user make another choice once they have selected and then been given the desired info.
Well the way you have written the code, is says (in effect)
loop: while not a valid choice:
get a choice
if it is valid choice":
act on it
break out of loop
(Note the "belt and braces" way you are terminating the loop is ... unnecessary. It is clearest to put the termination condition in the while condition only.)
So what you actually need is a way for the user to say "I want to stop now". So you could make that another choice, or you could say that an invalid choice is required.
Then you need to change the loop to say
while a valid choice:
or
while not the stop choice (or condition):
One point, have you considered what happens if you the user enters "STOP" or something else that isn't a number? Try it. Then try to explain what is actually happening.
I have 2 parts of code, the first one being converting fraction to decimal, and the second one being converting decimal to fraction.
However, I have to combine the two piece of code together and I have no idea.I want it to detect the input as either doubles or fraction and convert it to the other.
import java.util.*;
public class ExcerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
public class Fractions {
public static void main(String args[]) {
double decimal;
double originalDecimal;
int LIMIT = 12;
int denominators[] = new int[LIMIT + 1];
int numerator, denominator, temp;
int MAX_GOODNESS = 100;
// Get a number to be converted to a fraction
if (args.length == 1) {
decimal = Double.valueOf(args[0]).doubleValue();
} else {
// No number was given, so just use pi
assert args.length == 0;
decimal = Math.PI;
}
originalDecimal = decimal;
// Display the header information
System.out.println("-------------------------------------------------------");
System.out.println("Program by David Matuszek");
System.out.println("Input decimal number to be converted: " + decimal);
System.out.println();
// Compute all the denominators
System.out.println("All computed denominators:");
int i = 0;
while (i < LIMIT + 1) {
denominators[i] = (int)decimal;
System.out.print(denominators[i] + " ");
decimal = 1.0 / (decimal - denominators[i]);
i = i + 1;
}
System.out.println();
System.out.println();
// Compute the i-th approximation
int last = 0;
while (last < LIMIT) {
// Print out the denominators used in this computation
System.out.print("Using these " + (last + 1) + " denominators: ");
for (int j = 0; j <= last; j++) {
System.out.print(denominators[j] + " ");
}
System.out.println();
// Initialize variables used in computation
numerator = 1;
denominator = 1;
temp = 0;
// Do the computation
int current = last;
while (current >= 0) {
denominator = numerator;
numerator = (numerator * denominators[current]) + temp;
temp = denominator;
current = current - 1;
}
last = last + 1;
// Display results
double value = (double)numerator/denominator;
int goodness = denominators[last];
double error = 100 * Math.abs(value - originalDecimal) / originalDecimal;
System.out.print("fraction = " + (int)numerator + "/" +
(int)denominator);
System.out.print(", value = " + value);
System.out.print(", goodness = " + goodness);
System.out.println(", error = " + (int)error + "%");
System.out.println();
// Exit early if we have reached our goodness criterion
if (Math.abs(goodness) > MAX_GOODNESS) break;
}
}
}
If I was doing it all on one prompt, I would make two static methods Fraction.TryParse(), and I would use the built in Double.TryParse(), if decimal.TryParse returns true then you do in fact have a decimal. If it returns false, then you have a Fraction, therefore you have to use the same string you passed into Decimal.TryParse() in Fraction.TryParse(). Of course you will need some sanity checks in your Fraction.TryParse() method. The prompt could look something like this:
Enter Decimal/Fraction: 3.14
Enter Decimal/Fraction: 1 + 1/2
Enter Decimal/Fraction: 1 1/2
Enter Decimal/Fraction: 1 (1/2)
You see, if you want this all on one line you need some way to be able to delimit the characters, like a space, or brackets, or simply a + sign which would be mathematically accurate. If it is all on one line it also simplifies your program a little bit because you don't have multiple prompts for one object. The "1 (1/2)" input is not technically mathematically accurate, but you can kind of see how the data is supposed to be structured, you just can't be mathematically rigid with that prompt.
Here I am using the fraction one and one half, your implementation doesn't have a mixed number implementation, but you could just input 1/2 or something, just regular fractions.
I'm working on a program that will calculate the basic interest accrued on a certificate of deposit. The program asks for the amount of money invested and the term (up to five years). Depending on how many years their term is, is what determines how much interest is earned. I use an if/else statement to determine the rate of interest. I then use a loop to print out how much money is in the account at the end of each year. My problem is that when I run the program, the money is not counting.
Here is the entire code.
import java.util.Scanner;
public class CDCalc
{
public static void main(String args[])
{
int Count = 0;
double Rate = 0;
double Total = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("How much money do you want to invest?");
int Invest = userInput.nextInt();
System.out.println("How many years will your term be?");
int Term = userInput.nextInt();
System.out.println("Investing: " + Invest);
System.out.println(" Term: " + Term);
if (Term <= 1)
{
Rate = .3;
}
else if (Term <= 2)
{
Rate = .45;
}
else if (Term <= 3)
{
Rate = .95;
}
else if (Term <= 4)
{
Rate = 1.5;
}
else if (Term <= 5)
{
Rate = 1.8;
}
int count = 1;
while(count <= 5)
{
Total = Invest + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}
}
}
and here is the result I get with a 10 dollar investment, just to keep it simple, and a 5 year investment.
How much money do you want to invest?
10
How many years will your term be?
5
Investing: 10
Term: 5
Value after year 1: 10.18
Value after year 2: 10.18
Value after year 3: 10.18
Value after year 4: 10.18
Value after year 5: 10.18
My main problem is I dont know how to make it continually add the intrest onto the total. I'm not sure if I need to use a different loop or what. Any help would be appreciated.
Total = Invest + (Invest * (Rate) / (100.0));
You are not changing the value of Invest for each year, so it is not compounding. It is like you are getting .18$ of interest each year, retired from the account.
Change Total for Invest.
You need to add the investment interest to your total:
Total = Invest;
int count = 1;
while(count <= 5)
{
Total = Total + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}