Errors while wrtting script - java

Write the complete java program called Temperature that includes a for loop structure, prompting the user to enter 5 temperature values. The program should add up each temperature entered within the loop and this is stored in a variable called total. Using a system statement, output the total temperature value and the average temperature value. Use the sample output below as a guide:
The total temperature =
The average temperature =
My answer is the statement below but im still getting errors:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner temp = new Scanner (System.in);
double total = 0;
for(int=1;int<=5;int++);
{
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total = temperature;
}
System.out.println("The total temperature =" +total);
System.out.println("The average temperature=" +(double)(total/5));
}
}

The OP does not state what errors you are getting exactly, but I can guess some of them are from:
for(int=1;int<=5;int++);
You cannot use int like that. It is a type and should be used like the following:
for(int itr = 1; itr <= 5; itr++) { ...
Also, the semi-colon on your for loop doesn't need to be there.

for(int i=1;i<=5;i++) {
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total += temperature;
}

Related

How do I get Java to read the lowest float number

So I wrote this code that reads the User's lowest and highest float number. However, it reads the highest number fine, but it doesn't read the lowest number. I'm not
sure what I did wrong.
public static void main(String []args)
{
float cat=(float) 0.0;
float highest = (float) 0.0;
float lowest = (float) 0.0;
Scanner scan = new Scanner(System.in);
for (double i=0.00; i<2; i++) {
System.out.print("Enter a number:");
cat = scan.nextFloat();
if (cat > highest) {
highest = cat;
}
else if(cat < lowest) {
lowest = cat;
//I think it has something to do with the line above with lowest=cat
}
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}}
The test for highest and lowest are independent. You should not have an "else" joining them.
You should also consider what would happen if all the number are negative.
First, initialize highest with a value lower than anything the user is likely to enter (and lowest with a value greater than anything the user is likely to enter). You don't use i other than as a loop counter, so I would make it an int. You don't use cat except as a local variable containing the current user input (so I would limit the scope to the loop body). Finally, you can use Math.max(float, float) and Math.min(float, float) to simplify your logic. Like,
public static void main(String[] args) {
float highest = Float.MIN_VALUE;
float lowest = Float.MAX_VALUE;
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
System.out.print("Enter a number:");
float cat = scan.nextFloat();
highest = Math.max(highest, cat);
lowest = Math.min(lowest, cat);
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}
You always compare your input with lowest value 0.your code will only show exact output when you will take negative value input but not for positive one. here is the exact solution of your code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float cat=(float) 0.0;
float highest = (float) 0.0;
float lowest = (float) 0.0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number:");
cat = scan.nextFloat();
highest=cat;
lowest=cat;
//assignt first input to both so it can compare with next input
for (int i=0; i<(number_of_input -1); i++) { //here i compare with (number of input -1) beacuse you have already taken a input before
System.out.print("Enter a number:");
cat = scan.nextFloat();
if (cat > highest) {
highest = cat;
//System.out.println("Highest number is: " + highest);
}
else if(cat < lowest) {
lowest = cat;
//System.out.println("Lowest number is: " + lowest);
}
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}
}

Odd error in my Java program

I have a Java program that is designed to take an input of customers, then run a loop for each. Then the user has 3 choices to input: clowns, safari sam, or music caravan. I just don't understand what is wrong with my if statements. You see, if a user enters "clowns", the corresponding if statement works fine and the if statement is executed. However, if a user inputs "safari sam" or "music caravan", the if statements do not execute.
My question is: If the first if statement is executed, then why are the other 2 being skipped (not executing when conditions are met)?
CODE:
import java.util.Scanner;
public class FunRentals {
public static void main(String[] args) {
Scanner new_scan = new Scanner(System.in);
System.out.println("Enter the amount of customers: ");
int num_customers = new_scan.nextInt();
for(int i = 1; i<=num_customers; i++){
System.out.println("Please enter the service used (\"Clowns\", \"Safari Sam\", or \"Music Caravan\") for customer #"+i);
String service_type = new_scan.next();
String service_type_real = service_type.toLowerCase();
if(service_type_real.equals("clowns")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ clowns(additional_hours));
}
else if(service_type_real.equals("safari sam")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ safari_sam(additional_hours));
}
else if(service_type_real.equals("music caravan")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ music_caravan(additional_hours));
}
}
}
public static double clowns(double a){
double additional_cost = a*35;
double total_cost = additional_cost + 45;
return total_cost;
}
public static double safari_sam(double a){
double additional_cost = a*45;
double total_cost = additional_cost + 55;
return total_cost;
}
public static double music_caravan(double a){
double additional_cost = a*30;
double total_cost = additional_cost + 40;
return total_cost;
}
}
You need to use nextLine() instead of next() to read user input. nextLine() will read the entire line, but next() will only read the next word.
For reading String provided by the user in console you have to use .nextLine()
So try by using this -
String service_type = new_scan.nextLine();
This should store the value of whatever you are providing in the console to the String "service_type".

Cannot change the variable's value in my loop

I've never made a loop before and have to for a project.
Here is what I have:
import java.util.Scanner;
public class Population
{
public static void main (String [] args)
{
Scanner kb = new Scanner (System.in);
int dailyPopInc=-1;
System.out.print("What is the starting number of organisms? ");
int population = kb.nextInt();
if (population>1){System.out.print("What is the daily population increase as a percentage? ");
dailyPopInc= kb.nextInt();}
else System.out.println("Error");
int daysMultiplied=0;
if (dailyPopInc>=0){System.out.print("How many days will they multiply? ");
daysMultiplied= kb.nextInt();}
int k=0;
for (k=1;k<daysMultiplied;k++){
population= population + population*(dailyPopInc/100);
System.out.println("The the amount of population on day "+k+" is " + population);
}
}
}
I keep getting things like
"The amount of population on day 1 is 89" and it only changes the day value.
The population never changes. Can somebody please show me my mistakes?
Modify these lines:
double population = kb.nextInt();
population= population + population*(dailyPopInc/100.0);
It is because dailyPopInc/100 as an integer is always 0.

How to exit a loop based on what user pressed?

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

Average of an array and associate with name

Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result

Categories

Resources