Working on some homework and I want to make my code more precise, I have a set of values inside of an array that I need to convert into a different set of numbers while still being inside the array. Since this is for my homework I don't want to actually post what I am working on, so I will post an example, wouldn't want anyone doing my work for me!
public class Example{
public Example(){
double rainfall [] = {1.07, 3.25, 4.51, 2.32, 8.28}; //in Inches
System.out.print("Enter i for Inches or c for Centimeters ");
String scale = in.next();
if(scale.equalsIgnoreCase("C")){
for (double i : rainfall){
rainSum += i;
}//End for
// Here is where I am lost on what to do in my current program I have it
// to where it adds up all the numbers as inches and then converts them into
// centimeters, however I need to display every number in centimeters, so I
// cannot do it that way.
}//End if
}
}
So I suppose you have stats of rainfall of 5 days. They are provided in Inches and you need to output 2 things(Based on if the user selects 'C') :
(1). Total rainfall in cms.
(2). Daily rainfall stats in cms.
(3). You need to do this while preserving the original array in Inches.
So I would suggest you following code :
(1).
You are pretty correct on thinking in doing this. Add all the elements and multiply them by 2.54
to get its equivalent in cms.
(2).
call a method display as following :
void display(double[] a) // This would print individual rainfall stats in cms.
{
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]*2.54);//Modify formatting as per your requirements
}
}
(3).
These remain as is.
Method-2 :
If the expectancy of program getting input as 'C' is more, then create another array
that actually converts the initial inches array to cms array.
So, now you have two arrays :
rainfallInches[] & rainfallCms[]
You can use them as follows :
for(int i=0;i<rainfallInches.length;i++)
{
rainfallCms[i] = rainfallInches[i]*2.54;
}// This creates new cms array
Hope this helps
If you need to preserve the original values you will need to create a new array and copy the converted values to the corresponding positions in the new array.
If you don't need to preserve the original values use array element assignment, for instance:
private static final double CENTIMETERS_PER_INCH = 2.54d;
...
a[1] = a[i] * CENTIMETERS_PER_INCH;
in a loop to calculate the converted values. The constant definition would appear at the class level, not in the loop.
You're adding up all of the numbers and converting that sum (inches) into centimeters by multiplying by 2.54. The values in your array are still in inches, so to print all of them out in centimeters, simply iterate through the array and print the value multiplied by 2.54. Alternatively, if you need the transformed values and the original, simply copy the array, but multiplying each entry by 2.54.
public class Example{
public interface Constants{
/**
* Centimer to inch
*/
static final double CENTIMETER_TO_INCH = 0.393701;
/**
* Centimer to inch
*/
static final double INCH_TO_CENTIMETER = 2.54;
}
public double[] convertToCentimeter(double[] rainfallInInches){
int length = rainfallInInches.length;
double[] rainfallInCentimeters = new double[length];
for( int i = 0; i < length; i++ ){
rainfallInCentimeters[i] = rainfallInInches[i] * Constants.INCH_TO_CENTIMETER;
}
return rainfallInCentimeters;
}
public double[] convertToInches(double[] rainfallInCentimeter){
int length = rainfallInCentimeter.length;
double[] rainfallInInches = new double[length];
for( int i = 0; i < length; i++ ){
rainfallInInches[i] = rainfallInCentimeter[i] * Constants.CENTIMETER_TO_INCH;
}
return rainfallInInches;
}
public static void main(String[] args){
double rainfall [] = {1.07, 3.25, 4.51, 2.32, 8.28}; //in Inches
// Test convert to centimeter
Example example = new Example();
double[] convertedArray = example.convertToCentimeter(rainfall);
System.out.print("{");
for(int i = 0; i < convertedArray.length; i++){
System.out.print(convertedArray[i] + ", ");
}
System.out.println("}");
} // end main
}
Related
I'm new to Java and I'm stuck on this problem:
"Create a second add() method which has a single parameter of an array of doubles and, inside the method, adds the values of the array, returning the result as a double. Sample test data:
double[] dblArr = {11.82,88.23,33};
I have a separate class file with the following so far:
public double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}
This is the method to add the array's and return the total sum.
And this is the code I have in my "main" document to call the method
double dblArr;
utils.print("Please enter an array of 5 numbers: ");
dblArr = input.nextDouble();
double sum = calc.add(dblArr);
System.out.println(dblArr);
I know I'm quite off scope so some advice would be really appreciated, thank you
"calc" is what I'm using to call the other document
Calculate calc = new Calculate();
You are most of the way there, you just need to use a double array to gather the inputs, and you need to use a loop to save all the inpets to the array:
//use an array instead of a single double
double[] dblArr = new double[5];
int inputs = 0;
//Use a loop to gather 5 inputs
while(inputs < 5){
utils.print("Please enter the next of 5 numbers: ");
dblArr[inputs] = input.nextDouble();
inputs++;
}
//We have changed the add method to static, so you can just use `add(dblArr)` instead of making an instance of the class with the add method
double sum = add(dblArr);
//Finally print out the sum result not the dblArr array
System.out.println("The total is " + sum);
Then just change the method to static so that you can call it directly:
//Add static to this line as shown, because we don't need an instance of this method
public static double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}
/*IMO I have completed most of the project, but I can't wrap my mind around part with the array. I am supposed to assign the values to it then have it show on screen, as it is doing now when program get run, but it isn't going through the array. Please help its driving me insane.
Assignment:
For this project, you will create a program that asks the user to enter a positive integer value less than 20. Note that the program will only collect one number from the user. All other numbers will be generated by the program.
If the user enters a number greater than 20, the user should get an error.
If the user enters a number equal to or less than 20, display the double of each value beginning with 1 up to the selected number (multiply each number by 2), then provide the total of all doubles.
For example, if the user entered the number 5, the following should display:
Double up 1 = 2
Double up 2 = 4
Double up 3 = 6
Double up 4 = 8
Double up 5 = 10
Total = 30
Minimum Requirements:
• Create a separate class that contains the following methods. Note: This class should be separate and apart from the public class that holds the main method. 1. A method that will accept two parameters: an integer array and a integer variable. 1. The integer variable should hold the value provided by the user. The array will be used to hold the double up results.
2. This method should perform the calculations, and store the double up results in the array. Additionally, the total of all double up values should be calculated using an accumulator variable that is also a private instance variable.
3. You must make sure the calling method gets the changes to the array. Remember, arrays are passed by reference by default. This method must use a loop.
A separate method that will return (not display) the value stored in the private instance variable called total.
• Create a main method that creates an array and integer variable, as well as an instance of your class. The main method should then use the instance to call each of the methods of the class, passing the data needed and handling any return data. Display the entire contents of the array and total variable.
*/
import java.util.Scanner;
public class project2 {
public static void main(String args[]){
scores output = new scores();
output.enterNum();
output.displayScores();
}
}
class scores
{
int total;
int stats[] = new int[20];
int num1;
void enterNum()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 1 and 20: ");
num1 = input.nextInt();
if(num1<=0 || num1>20)
{
System.out.println("You entered a wrong number. Try again.");
System.out.println("");
enterNum();
}
}
void displayScores()
{
int b=0;
int val2=0;
int total = 0;
val2=num1*2;
for(int i=1;b<val2;i++)
{
System.out.println(b=i*2);
total = total + b;
// this part.
// stats[i] = b;
// System.out.println(stats);
}
System.out.println(total);
}
}
Maljam is right, your for-loop is the issue here.
Your for-loop is messing around with some int b that doesn't need to be there. What you want is to add i*2 to total on each iteration of your loop. Also, you need to modify your for-loop header to check against i instead of b. I'm not really sure what you are trying to do with the array. It's not needed in this project at all.
Try changing it to something like this:
for (int i=1; i<=val1; i++){
//stats[i] = i;
System.out.println("Double up " + i + " = " + 2*i);
total = total + 2*i; //or total += 2*i;
}
System.out.println("Total: " + total);
public class scores {
int total;
int stats[];
int num1;
void enterNum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 1 and 20: ");
num1 = input.nextInt();
if (num1 <= 0 || num1 > 20) {
System.out.println("You entered a wrong number. Try again.");
System.out.println("");
enterNum();
}
}
void displayScores() {
stats = new int[num1];
int total = 0;
for (int i = 0; i < num1; i++) {
stats[i] = (i+1) * 2;
total += stats[i];
}
for (int i = 0; i < num1; i++) {
System.out.println((i+1) + " * 2 = " + stats[i]);
}
System.out.println("Total: " + total);
}
}
I have an array that takes student grades from an input. I have to make a method that will find the average of the numbers within the array. Here is the code i have so far...
int mark = Integer.parseInt(input.getText());
if(mark <= 100){
marks.add(Integer.parseInt(input.getText()));
input.setText("");
warningLbl.setText("");
}
else{
warningLbl.setText("Please enter an number between 0-100");
}
I want to take the contents in the array 'marks' and get an average for them then append it in my text area
public static double getAverage(int[] marks)
{
int sum = 0;
for(int i : marks) sum += i;
return ((double) sum)/marks.length;
}
This is the method i have to find the average, but i dont know how to use this method and get it to print in a text area
If you want to find the average stored in an array , try the following function.
public static double average(int[] marks)
{
int sum = 0;
double average;
for(int element: marks)
{
sum = sum + element;
}
average = (double)sum / marks.length;
return average;
}
Hope it helps ! :)
The above method is used to find average in an array(primitive type) , but to find average in List type array(wrapper class) , we have to iterate through each element in the list by this way and do the required calculations :
public static String average(Integer[] marks)
{
int sum = 0;
double average;
for (int i = 0; i < marks.size(); i++)
{
sum = sum + marks.get(i);
}
average = (double) sum / marks.size();
String averageString = Double.toString(average);
return averageString;
}
This returns your average in string type directly.
There are several problems with your current code.
Using input.getText(); twice will mean it's going to prompt for input twice. Have a single line like int mark = Integer.parseInt(input.getText()); then use the mark variable wherever it's needed.
In order to test if the number is between 0 and 100 (I'm assuming this needs to be inclusive), that if statement would need to be (mark >= 0 && mark <= 100).
I assume you want to get multiple students' grades/marks, so it may be a good idea to enclose your code in a for or while loop, depending on how you want it to operate. However, since this will be of variable length I'd recommend using a List over an array for resizing.
Finding the average is easy. Just use a foreach loop to sum up all the numbers, then divide that by the array length.
I am writing a program that takes 10 floating point numbers as inputs, and displays the average of the numbers followed by all of the numbers that are greater than the average. I am using a method that takes an array of doubles as a parameter and returns the average of the data in the array. However, my problem is that when I run my program the output window is completely blank. I assume this is because I did not call in my method to the main method. However, I am not sure how to write that code. Thank you.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
}
public double average(double[] number) {
Scanner scanner = new Scanner(System.in);
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
int numberIndex = 0;
int largerIndex = 0;
System.out.printf("Please enter 10 floating-point numberes.\nIf more than 10 values are entered, the numbers following 10 are ignored.\nIf less than 10 numbers are entered, the program will wait for you to enter 10.\n");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
sum += numberList[x]; //add up all inputs to find sum
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
numberIndex = 0;
largerIndex = 0;
numberList = new double[10];
largerList = new double[10];
continue;
}
}
for (int i = 0; i < number.length; i++) {
sum = sum + number[i];
double average = sum / number.length;
System.out.println("Average value of your input is: " + average);
System.out.println();
//return average;
if (x > average) {
largerList[largerIndex] = x; //add negative input to negativeList array
largerIndex = largerIndex + 1;
}
}
for (int i = 0; i < largerIndex; i++) {
System.out.println(largerList[i]);
}
return 0;
}
}
to answer the main question...
However, my problem is that when I run my program the output window is completely blank. I assume this is because I did not call in my method to the main method. However, I am not sure how to write that code.
public static void main(String[] args) {
new Average().average(new double[10]);
}
Or maybe you are thinking something like this...
public static void main(String[] args) {
double[] numbers = {2,3,4,5,6,4,3,2,1,3};
new Average().average(numbers);
}
A output run from above (with the doubles given):
Please enter 10 floating-point numberes.
If more than 10 values are entered, the numbers following 10 are ignored.
If less than 10 numbers are entered, the program will wait for you to enter 10.
2
3
3
4
1
2
3
4
5
1
Average value of your input is: 0.2
Average value of your input is: 0.5
Average value of your input is: 0.9
Average value of your input is: 1.4
Average value of your input is: 2.0
Average value of your input is: 2.4
Average value of your input is: 2.7
Average value of your input is: 2.9
Average value of your input is: 3.0
Average value of your input is: 3.3
1.0
1.0
1.0
Press any key to continue . . .
If you have question about the code itself, then it would be better to create a new question or edit it to make it more clear.
Good luck with your coding.
Your method average() takes an array of doubles, but then retrieves an other array from standard input. That doesn't make sense.
Either get the doubles and pass them to the method, or don't pass them to the method and get them from standard input.
What you need to do is create an instance of Average class in your main method and call the average() method.
Why parse double array in your average() method when you take the input from user?
well,you are using a non static method "average()" for your task which needs an instances of the class to run which are not creating anywhere.so there are only two options:-
#1.create an instances of your class then call it.
public static void main(String... s)
{
Average obj=new Average();
obj.average();
}
#2.make "average()" a static method by adding static keyword.
public static double average()
{
//your code.....
}
public sttatic void main(String... s)
{
average();
}
your dont need to keep an argument in your method.
i'm struggling a bit with getting array values from one method into another without repeating the method over again (the method obtains judges scores using getScannerInput (we have to use it at my uni instead of other options :-/ ).
My program is the following;
public class mark4
{
static int SIZE = 10; // Define array size
static int classMarks[] = new int [SIZE]; // Initialise array classMarks[]
static double max = 0;
static double min = 0;
static double total = 0;
static double averagescore = 0;
static int pass = 0;
public static int[] getMarks()
{
int[] classMarks = new int [SIZE];
for(int i = 0; i< classMarks.length; i++) // Start input loop to obtain marks
{
classMarks[i] = getScannerInput.anInt("Please enter students mark: ");
}
System.out.print("\nThe marks for this class are; "); // Output initial line to be completed with students marks
for(int i=0; i<classMarks.length; i++) // Start output loop to output students marks
{
System.out.print(classMarks[i] + ", "); // Output marks separated by a comma and a space
}
return classMarks;
}
public static double averagescore(){
for(int i=0; i<classMarks.length; i++) // Start loop to calculate total of all marks.
{
total = classMarks[i] + total; // Calculate total of array by traversing and adding to 'total' variable each time
averagescore = total / classMarks.length; // Divide array total by array length to find average
} // end average loop
return averagescore;
}
public static double min(){
min = classMarks[0]; // Set min to first value of array to compare to rest
for(int i=0; i<classMarks.length; i++) // Start loop to calculate minimum and maximum scores
{
if(classMarks[i] < min) // Compare values on each iteration, if value is less than current 'min' value, replace min with new value
min = classMarks[i];
} // end minloop
return min;
}
public static double max(){
max = classMarks[0]; // Set max to first value of array to compare to rest
for(int i=0; i<classMarks.length; i++) // Start loop to calculate minimum and maximum scores
{
if(classMarks[i]>max) // Compare values on each iteration, if value is greater than current 'max' value, repalce max with new value
max = classMarks[i];
} // end max loop
return max;
}
public static int pass(){
for(int i=0; i<classMarks.length; i++) // Start loop to calculate how many students passed with a mark of 8 or higher
{
if( classMarks[i] >= 8 ) // Compare the current score in each iteration to 8 to see if it is more than or equal to the pass mark
pass++; // If current value is greater than or equal to pass mark, add one to pass counter.
} // end pass loop
return pass;
}
public static void main (String args[])
{
int[] classMarks = getMarks();
double averagescore = averagescore();
double min = min();
double max = max();
int pass = pass();
System.out.print("\nThe number of students who passed the exam is " + pass);
System.out.printf("\nThe class average correct to 1 decimal place is: %4.1f", averagescore); // Output average score to 1 decimal place
System.out.printf("\nThe lowest mark obtained in this class was: %3.1f", min); // Output lowest score to one decimal place (in case of half marks...)
System.out.printf("\nThe highest mark obtained in this class was: %3.1f", max); // Output highest score to one decimal place (in case of half marks...)
} // end main
} // end class
The program compiles correctly, but the results I get are all 0 or 0.0, suggesting that the methods aren't taking the figures input during the getScores() method.
If I try to define the results for classMarks[] inside the methods using;
int[] classMarks = getMarks();
it repeats the whole getScores() method and asks for the results again every time it encounters a method in the main.
I'm aware this is probably a fairly simple answer, but we had to do this as a question in an assessment, but i missed the lectures on methods and arrays and i'm struggling a bit with some minor elements.
Any help would be much appreciated!
You declare this, which I beleive is what you intend to use,
static int classMarks[] = new int [SIZE];
but, within getMarks(), you declare a new one:
int[] classMarks = new int [SIZE];
which is what will be used within the scope of that method.
Either, you should use the class scope variable, and not declare others which will override it (that is, remove the second declaration shown above), or your min, max, etc. methods should take the an int[] argument, and you could pass the array returned from getMarks() to them.
In your main method you are declaring classMarks, which is hiding the static classMarks you have at the class level. You are also declaring another classMarks array within your getMarks method, so your scanner is never reading into the shared classMarks array, only into the local array in getMarks, which is then returned and placed in the local classMarks variable in main, but never getting into your static variable that is referenced by every other method in the class.