How to print out an altered dynamic array - java

I think I have swapped the first and last numbers of a dynamic array with each other and am at a total loss as to how to print the array with the numbers swapped.
Ideally, with the program working, the user is supposed to enter in the number of numbers they want to enter and then they will type each number in individually. Then it is supposed to output (along with standard deviation, the mean, and the original array order) the array in order, except the first number entered and the last number entered are switched. How would you go about printing the new array with the switched numbers?
Here is my code so far:
import java.util.Scanner;
import java.lang.Math;
public class Project_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? ");
int N = scan.nextInt();
float sd, mean;
float Sum = 0;
float Square = 0;
float [] numbs = new float[N];
System.out.println("Enter your numbers below: ");
for (int i = 0; i < N; i++){
numbs[i] = scan.nextFloat();
Sum += numbs[i];
}
mean = Sum/N;
scan.close();
for (int j = 0; j < N; j++){
Square = (numbs[j] - mean) * (numbs[j] - mean);
}
sd = (float)Math.sqrt(Square/N);
System.out.println("The mean is: " + mean);
System.out.println("The standard deviation is: " + sd);
for (int k = 0; k < N; k++){
if (k == N-1){
System.out.print(numbs[k]);
}else{
System.out.print(numbs[k] + ", ");
}
}
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
}
}

You can swap the integers by doing the following,
int temp = numbs[N-1];
numbs[N-1] = numbs[0];
numbs[0] = temp;
Hope this helps :)

I did not realize that I would just have to enter another simple if statement to print it out. I was confused as to where the edited array was saving to, not realizing that it was just saving to the original array. Thank you all for the help.
In the end this is what I used for the code (in regards to my program specifically):
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
for (int g = 0; g < N; g++){
if (g == N-1){
System.out.print(numbs[g]);
}else{
System.out.print(numbs[g] + ", ");
}
Heres the output:
How many numbers would you like to enter? 5
Enter your numbers below:
1
2
3
4
5
The mean is: 3.0
The standard deviation is: 0.8944272
1.0, 2.0, 3.0, 4.0, 5.0
5.0, 2.0, 3.0, 4.0, 1.0

Related

How to find out variance from array of numbers?

New to Java here! I have to have the user enter 10 numbers and store them in an array (of doubles). After that I need to calculate:
Mean: I have that done and I need it to get the variance & std dev requires knowing the variance.
Variance: aka the average of the squares of the distance from the mean. The part I'm confused with. For each number in the array, I have to subtract the number from the mean, square the result, and then add the square to a running total. After that I have to divide the running total by the number of values (10).
Lastly, Standard deviation: aka the square root of the variance
I have to print all the results rounded to 2 decimal places.
Example: if my dataset was just {4, 7.5, 8}, then the mean is (4 + 7.5 + 8)/3 = 19.5/3 = 6.5.
Variance = ((6.5 - 4)^2 + (6.5 - 7.5)^2 + (6.5 - 8)^2
)/3 = (6.25 + 1 + 2.25)/3 = 9.5/3 = 3.17
Standard Deviation = √3.17 = 1.78
What I need help with is the math to find out the variance. I am not sure how to take a running total or how to square root numbers in parenthesis.
public class Statistics {
public static void main(String[] args) {
int userNumbers;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the 10 numbers: ");
userNumbers = scan.nextInt();
double array[] = new double[userNumbers];
double mean;
double variance;
for (int i = 0; i < array.length; i++) {
userNumbers += userNumbers;
mean = userNumbers / 10;
}
for (int i = 0; i < array.length; i++) {
variance = mean - userNumbers;
}
System.out.print("The variance is:" + );
System.out.print("The standard deviation is: " + Math.sqrt(variance));
}
}
In this code
for (int i = 0; i < array.length; i++) {
variance = mean - userNumbers;
}
you are overwriting the value of variance in each iteration of the loop, so only the last value would be kept.
Also, for both loops, you want to use the elements in the array
Try adding to the value
for (int i = 0; i < array.length; i++) {
variance += mean - array[i];
}

How to update multiple variables in a loop

I'm a beginner Java student faced with the following question: W"rite a program that inputs an integer that will be the number of times (n) that you will read a random number."
The program is then supposed to calculate the sum and product of those random numbers.
I understand how to generate a random number and I set up a For loop to generate the n random numbers per user input.
import java.util.Scanner;
import java.util.Random;
public class Example {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter a number:");
n = input.nextInt();
for (int i = 0; i < n; i++){
double randomNumber = Math.random();
System.out.println(randomNumber);
}
}
}
My first attempt had shoehorned
System.out.println(randomNumber * randomNumber);
System.out.println(randomNumber + randomNumber);
at the bottom of the code which did not work for reasons that are probably obvious to anyone else.
I'm stuck on the concept of storing n random numbers for long enough to do the required arithmetic on them.
You should be able to just maintain some state for the sum and product:
int n = input.nextInt();
double sum = 0d;
double product = 0d;
for (int i=0; i < n; i++) {
double randomNumber = Math.random();
sum += randomNumber;
product = i == 0 ? randomNumber : product*randomNumber;
}
System.out.println("sum = " + sum);
System.out.println("product = " + product);
The line:
product = i == 0 ? randomNumber : product*randomNumber;
is equivalent to:
if (i == 0) {
product = randomNumber;
}
else {
product = product*randomNumber;
}
The version I used is called a ternary expression, and is a concise way of writing if else logic. The idea here is that we want to initialize the product with the first random number. Otherwise, we just multiply the product with the latest random number.

Finding average of a text file

I am fairly new to java and I'm trying to code to find the average. I understand that the average is adding all the numbers and then dividing the sum by the number of numbers but I'm not really sure how to code that. My guess is that I'd need a for loop but I don't know what to do from there. The program basically asks for a file to be read and then calculate the average. Here's the code I have so far:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Calculations
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Please enter a file name");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.next();
Scanner reader = new Scanner (new File(filename));
int length = reader.nextInt();
double [] num = new double[length];
double [] num2 = new double[length];
System.out.println("The numbers are:");
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
System.out.println(num[i]);
}
}
}
The file I would be using is list.txt which contains:
20
1.1 2 3.3 4 5.5 6 7 8.5 9 10.0
11 12.3 13 14 15.5 16.1 17 18 19.2 20.0
The mean should be 10.625. Any help is deeply appreciated. Thank you in advance.
Just introduce a new variable sum, initialize it to 0, and add the elements to the variable while you are printing them.
System.out.println("The numbers are:");
double sum = 0; //new variable
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
sum += num[i];
System.out.println(num[i]);
}
sum /= (double) length; //divide by n to get the average
System.out.print("Average : ");
System.out.println(sum);
It appears that you're simply having trouble computing the average; I'll address that issue here:
In Java 7 and below, use a for loop:
double sum = 0; //declare a variable that will hold the sum
//loop through the values and add them to the sum variable
for (double d : num){
sum += d;
}
double average = sum/length;
In Java 8 you can use a Stream to compute the average
double sum = Arrays.stream(num).sum(); //computes the sum of the array values
double average = sum/length;

Average of an array showing 1

I have a program where the user inputs marks into the array and then gets the average value
This is using Jcreator
My problem is that when I ask for the average on my program,it says that the average is 1
This is my code :
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int averageEnglish = english.length / 10;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
English is an int array
int[] english = new int [10];
averageEnglish is a variable
int averageEnglish;
10/10 equals 1. pretty normal.
what you need to do is get the sum of all elements, and divide them by the length of the array.
also: the IDE you use is not really relevant
english.length/10 is not the average value of the array, its simply the length (10) of the array divided by 10, which is 1. You need to sum up all values of the array and divide the sum by the length of the array.
Often you want to present the result not only as an integer but with a few decimals, store the sum and average result in a double.
double sum = 0;
for (int i = 0; i < english.length; i++) {
sum += english[i];
}
double average = sum / english.length;
You are dividing the array's length by the constant 10 (which just happens to be the length), so naturally you'd get 1. You should sum all values of the array and only then divide them by its length:
double englighSum = 0;
for (int i = 0; i < english.length; ++i)
englishSum += english[i];
}
double englishAverage = englishSum / english.length;
If you want user to fill the array, you need to use Scanner object.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of grades: ");
int n = scanner.nextInt();
double[] english = new double[n];
for(int i=0; i<n; i++)
{
System.out.println("Please enter the grade for grade " + (i+1) + ":");
english[i] = scanner.nextDouble();
}
scanner.close();
Than you may use Markus Johnsson's code to proceed.
You anticipated the size of the array and assumed it is always 10 which is the first mistake, then you did your division based on the number of array elements not their sum:
int[] english = new int[10];
/* Now we assume you did some stuff here to fill the array. */
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int noOfElements = english.length; // The divisor
int sum = 0; // The dividend
for (int i = 0; i < noOfElements; i++)
{
sum += english[i];
}
// Here is your Average (Should be of type double since there will be floating points)
double averageEnglish = sum / noOfElements;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
The value of english.lenght is always 10. As in this example:
int[] english = new int [10];
It doesn't matter what data the english array holds, its lenght is always 10.
In order to do the proper calculation use the data, not the lenght of the array.

Java - Finding even numbers and the percent of them within an array

This is the question that I need to figure out:
Write a method called percentEven that accepts an array of integers as a parameter and returns the percentage of even numbers in the array as a real number. For example, if the array stores the elements [6, 2, 9, 11, 3] then your method should return 40.0. If the array contains no even elements or no elements at all, return 0.0.
Here is what I have so far:
import java.util.*;
public class Change {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Let's find the range.");
System.out.println("Enter five numbers to find the range.");
int num = console.nextInt();
int[] list = new int[num];
System.out.println("The numbers you entered are: " + list.length);
System.out.println();
percentEven(list);
}
public static void percentEven(int[] num){
int percent = 0;
int even = 0;
for(int i = 0; i < num.length; i++){
if(num[i] % 2 == 0){
even++;
}
}
percent = (even / num.length) *100;
System.out.println("The percent of even numbers is: " + percent);
}
}
When I run it, I get 100 as the percent.
Two issues here:
Cast one of them to a double or float.
percent = (even / (double) num.length) *100;
The other issue is that you never assign the numbers any value, so they are all 0. 0 % 2 is equal to 0, so the list is, by definition, 100% even.
You should also have a base case in the method when nums == {}, which would return 0.0 as the assignment states.
There are three major problems in your code:
You are reading only ONE integer, not five
You use this single integer to define the LENGTH of the array, not the content (so you don't put the integer into the array. So the array contains only zeroes, which means that all of them are even.
You are doing wrong integer arithmetic (as Obicere already stated in his answer). But this doesn't have any effect, as all elements of the array are even, so the result will be 100 in any case.
You are almost there. But you are initializing and storing the array wrong way. Do this
int num = console.nextInt();
int[] list = new int[num];
System.out.println("Enter " + num + " numbers");
for(int i = 0; i < num; i++) {
list[i] = console.nextInt();
}
System.out.println("The numbers you entered are: " + java.util.Arrays.toString(list));
System.out.println();
and also do as other suggested.
Write
percent = even * 100 / num.length;
Changing the order of the operations will make the integer division business work in your favour - you'll get a value rounded down to the next lowest percentage, rather than rounded down to zero.
Also fix the problem with all the numbers being zero by reading them from the keyboard, as in tintinmj's answer.
import java.util.*;
public class percentEvenClass
{
public static void main(String[] args){
int[] list = {6, 2, 9, 11, 3};
int percentEven_Result = percentEven(list);
System.out.println(percentEven_Result);
}
public static int percentEven(int[] list){
int count = 0;
int percent = 0;
for (int i=0; i<list.length; i++){
if (list[i] % 2 == 0){
count++;
}
percent = (count * 100)/ list.length;
}
return percent;
}
}

Categories