I am trying to take values from separate arrays and perform divisional math. I have created a method to perform the division, but I keep getting the "bad operand..." error. I have searched and searched, but cannot find resolution. I need to be able to take the values from tripMiles and divide that by the values from gallons.
import java.util.Scanner;
public class Week6Challenge {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int count = 0;
//double miles = 0, gallons = 0;
//Arrays
String[] tripName;
tripName = new String[11];
double[] tripMiles;
tripMiles = new double[11];
double[] tripMPG;
tripMPG = new double [11];
double[] gallons;
gallons = new double [11];
//double miles = 0, gallons = 0;
while (count <= 9){//start while
System.out.println("Enter a description of this trip");
tripName[count] = scan.next();
System.out.println("How many miles did you drive?");
tripMiles[count] = scan.nextDouble();
System.out.println("How many gallons of gas did you use on this trip");
gallons[count] = scan.nextDouble();
count++;
}//end while
tripMPG[count] = answer(tripMiles, gallons);
System.out.println("Trip Name \t Miles Traveled \t MPG");
int k = 0;
for(k = 0; k < 10; k++){
System.out.println(tripName[k]+ "\t\t" + tripMiles[k] + "\t\t\t" + tripMPG[k]);
}
}
public static double answer(double[] num1, double[] num2){
return (num1/num2);
}
}
You are trying to divide two arrays like:
return (num1/num2);
Which is not valid.
Instead if you need length or sum of two arrays and then divide, you could sum up all the elements and then divide the two values.
You can't divide array like this (num1/num2)
Code snippet of one method how to do division of arraya
public static double answer(double[] num1, double[] num2){
//assumimg both array is of equal length
for (int i=0;i<num1.length;i++){
double result = num1[i]/num2[i];
}
}
As already been mentioned you can't divide arrays to each other, but their elements.
Change your answer function so instead of two arrays of double it takes two double and returns the result:
//num1 & num2 are double, not array
public static double answer(double num1, double num2){
return (num1/num2);
}
Remove tripMPG[count] = answer(tripMiles, gallons); from right after the while loop and instead add the following line at the end of your while loop right before count++;:
tripMPG[count] = answer(tripMiles[count], gallons[count]);
So your while should look like this:
while (count <= 9){//start while
System.out.println("Enter a description of this trip");
tripName[count] = scan.next();
System.out.println("How many miles did you drive?");
tripMiles[count] = scan.nextDouble();
System.out.println("How many gallons of gas did you use on this trip");
gallons[count] = scan.nextDouble();
tripMPG[count] = answer(tripMiles[count], gallons[count]);
count++;
}//end while
Related
Instructions;
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the max and average. A negative integer ends the input and is not included in the statistics. Assume the input contains at least one non-negative integer.
Output the average with two digits after the decimal point followed by a newline, which can be achieved as follows:
System.out.printf("%.2f\n", average);
Ex: When the input is:
15 20 0 3 -1
the output is:
20 9.50
I have tried a few different ways to convert the int avg into a string but somehow keep messing up.. What am I not doing?? Example code below
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
String s=Integer.toString(avg);
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.printf("%.2f\n", avg);
}
}
What you are trying to do is almost correct. The only things, you would need to change for this to work are these:
int avg = 0; // The type of avg should be a float
The reason for this is that what you're printing is a float but before these changes, you are providing it with an int.
// The number you are providing avg with should be cast to a float value
avg = total/(count-1);
This is because if you didn't, you would have integer division.
// It would look like this
float avg = 0;
avg = (float)total/(count-1);
this is my first post here!
So, as an extra credit project for my Calculus course, the professor offered us an opportunity to write a simple program that calculates the area under a user specified curve. I realize this isn't the best way to implement this, but he say's that's fine, but I think this is giving me the wrong answer. Could anyone help?
import java.util.*;
public class RiemannSum2 {
public static void main(String args []) {
System.out.println("This is a Riemann Sum Calculator. This calculator accepts polynomials in the form of a(x)^ex + b(x)^ex2 + c, where c is a constant.");
System.out.print("Enter the first coeffecient of the polynomial: ");
Scanner sc = new Scanner(System.in);
int firstCoe = sc.nextInt();
System.out.print("Enter the exponent of the first term: ");
int firstExp = sc.nextInt();
System.out.print("Enter the second coeffecient of the polynomial: ");
int secondCoe = sc.nextInt();
System.out.print("Enter the exponent of the second term: ");
int secondExp = sc.nextInt();
System.out.print("Enter the third term of the polynomial: ");
int thirdTerm = sc.nextInt();
System.out.print("Enter the x value that you want to start the Riemann Sum: ");
int startX = sc.nextInt();
System.out.print("Enter the x value to stop the Riemann Sum: ");
int endX = sc.nextInt();
String poly = (firstCoe+"x^"+firstExp+"+"+secondCoe+"x^"+secondExp+"+"+thirdTerm);
System.out.println("Your polynomial is: "+poly);
System.out.print("Enter the number of rectangles you want: ");
int rectangles = sc.nextInt();
double numerator = (endX-startX);
double rectanglesD = (double)rectangles;
double constantWidth = numerator/rectanglesD;
System.out.println("This is the constant width: " + constantWidth);
double totalSum = 0;
//System.out.println(totalSum);
for(int i = 0; i < rectangles ; i++) {
totalSum = totalSum+((Math.pow((firstCoe * (i/constantWidth)), firstExp)) + (Math.pow((secondCoe * (i/constantWidth)), secondExp))+thirdTerm);
}
totalSum = totalSum*constantWidth;
System.out.println("The Riemann Sum of your polynomial is roughly equivalent to: "+ totalSum);
}
}
You use (i/constantWidth) to calculate the argument of your function (x). However, it should be
double x = startX + i * constantWidth;
Furthermore, your coefficients should be outside of the pow function. Otherwise, they will get exponentiated too. Removing some of the superfluous parentheses makes the formula a lot easier to read. Like this:
double x = startX + i * constantWidth;
totalSum = totalSum
+ firstCoe * Math.pow(x, firstExp)
+ secondCoe * Math.pow(x, secondExp)
+ thirdTerm;
Unrelated to the code: Since you have a simple polynomial, you can calculate the antiderivative analytically and simply evaluate that function instead.
I am making an investment calculator.
So I will be doing a math problem and I want to loop it through each array and there will be 12 of them.
So let's say I am going to invest $1000 with a rate return of 4.5%.
So I will need to do 1000 * 0.045 + 1000 = 1,045 that equals one month. Then I need to do 1,045 * 0.045 + 1,045 = 1,092 that would equal the second month and how would I have it go through a loop like that?
Would I use a for loop? or?
This is what I have so far maybe you'll get it better by reading it. But I still need to create a loop that would like the example I gave above.
public class SimpleInvestment {
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double [] num = new double [11];
printWelcome();
double investTotal = getInvestAmount();
double rateTotal = getRate();
}
public static void printWelcome()
{
System.out.println("Welcome to the Investment Calulator");
}
public static double getInvestAmount()
{
double amountInvest;
System.out.print("Hou much will you be investing? ");
amountInvest = input.nextDouble();
while (amountInvest <= 0)
{
System.out.println("Amount must be greater than 0. Try again.");
System.out.print("How much will you be investing? ");
amountInvest = input.nextDouble();
}
return amountInvest;
}
public static double getRate()
{
double rate;
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
while (rate < 0 )
{
System.out.println("Rate must be greater than 0. Try again.");
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
}
return rate;
}
public static void calculateInterst( double num[], double investTotal, double rateTotal)
{
double total;
rateTotal = rateTotal / 100;
total = investTotal * rateTotal + investTotal;
}
}
You can use a while or for loop. In this example I used a for loop.
There is documentation in the code to walk you through the logic.
public static void calculateInterest(double num, double investTotal, double rateTotal) {
double total; //keep the total outside loop
rateTotal = rateTotal / 100; //your percent to decimal calculation
total = investTotal * rateTotal + investTotal; //intial calculation
for (int i = 1; i < num; i++) {//for loop starting at 1 because we alreay calculated the first
total += (total * rateTotal);//just calculate the rate of change
}
System.out.println(total);//either output it or return it. Whatever you want to do from here.
}
I hope this helps!
You can use below code:
where months is the investment duration in months,
investment is the amount that is being invested,
rate is the interest rate. e.g. 0.045
public static double calculateTotal(int months, double investment, double rate) {
double total = investment;
for (int i=1; i <= months; i++) {
total = total + (total * rate);
}
return total;
}
As you see this program supposed to give me number of lines.
I want to know how to put a condition give me the minimum triangle side
like if I give the number 5 to the (line) it will loop five times and each line
I have to put 3 separated numbers but I can't find a way to put a condition to give me which one of them is the minimum one.
import java.util.Scanner;
public class Triangles {
private int side[];
public static void main(String args[]) {
double line;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of Triangles:");
line = s.nextInt();
int side[] = new int[(int) line];
System.out.println("Please, insert lengths of the sides of this triangles(3 real numbers per line) ");
for (int i = 0; i < side.length; i++) {// for reading array
side[0] = (int) s.nextDouble();
side[1] = (int) s.nextDouble();
side[2] = (int) s.nextDouble();
double perimeter = side[0]+side[1]+side[2];
System.out.println(perimeter);
System.out.println("Enter the next Triangles:");
}
line--;
}
}
according to your requirement i have modified it.i hope this will solve your problem, please let me know if you need any help
public static void main(String[] args) {
double line;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of Triangles:");
line = s.nextInt();
int side[] = new int[3];//because every triangle has 3 sides
double min = Double.MAX_VALUE;//assuming perimeter of a tringle will be grater than zero
while(line-->0){//we need to loop as many no Triangles
System.out.println("Please, insert lengths of the sides of this triangles(3 real numbers per line) ");
// for (int i = 0; i < side.length; i++) {// for reading array
side[0] = (int) s.nextDouble();
side[1] = (int) s.nextDouble();
side[2] = (int) s.nextDouble();
double perimeter = side[0]+side[1]+side[2];
if(perimeter<min){
min = perimeter;
}
System.out.println(perimeter);
//System.out.println("Enter the next Triangles:");
//}
}
System.out.println("Minimum Perimeter :"+min);
// line--;
}
I'm trying to figure out how to implement a total of my SCORES and VOTES which I have done no problem. Where I'm getting confused and can't seem to solve is how I would go back through my array of Contestants and get their percent of the total SCORES or VOTES. e.g player 1 has a score of 10 out of a total score of 30, player 2 has a score of 15/30 ect... a running average is not a problem its a real total average I can't seem to wrap my head around. Any advice would be terrific.
package contestscore;
import java.util.*;
public class ContestScore {
public static void main(String[] args) {
// TODO code application logic here
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter number of contesants: ");
int numContest = keyboard.nextInt();
System.out.println("Enter contestants DANCE SCORE and NUMBER OF VOTES EARNED: ");
int[] danceScore = new int[numContest+1];
int[] numVotes = new int[numContest+1];
double avgDanceScore = 0.0;
double avgVoteScore = 0.0;
double totalDanceScore = 0.0;
int numContestIndex = 0;
double avgContestDanceScore = 0.0;
int totalVotes = 0;
double avgContestVote = 0.0;
for(numContestIndex = 1; numContestIndex <= numContest; numContestIndex++)
{
danceScore[numContestIndex] = keyboard.nextInt();
numVotes[numContestIndex] = keyboard.nextInt();
System.out.println("DANCE SCORE: "+danceScore[numContestIndex]);
System.out.println("NUMBER OF VOTES: "+numVotes[numContestIndex]);
totalDanceScore = totalDanceScore + danceScore[numContestIndex];
//avgContestDanceScore = danceScore[numContestIndex] /totalDanceScore;
System.out.println("TOTAL DANCE SCORE: "+totalDanceScore);
totalVotes = totalVotes + numVotes[numContestIndex];
//avgContestVote = numVotes[numContestIndex] / totalVotes;
System.out.println("TOTAL CONTESTANT VOTE SHARE: "+totalVotes);