I am working on a project and am stuck on what to do next. I need to write a Java program that accepts from a user ten values and place those numbers in an array. The numbers in the array will be added together and the result displayed to the user. (I got that part)
Here is the problem: The program should compare the values for elements 1 and 2 (in the array) and divide the larger number by the smaller number. It should compare the values for all odd/even elements and divide the larger by the smaller value.
I do not know how to do this at all. I started with if-else statements but I am getting errors. It know it's a mess right now, but any help with dividing the array pairs would be very helpful. Send me links too, I have been unsuccessful finding any, so I can learn more.
Thanks!
Here is what I have so far:
/import java.util.Scanner;
public class ExceptionHandler {
/**
* #param args the command line arguments10
* 10
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter ten values:");
System.out.println();
// Input the data from the user.
int[ ] digit = new int[11];
int sum = 0;
//Declare an array
for (int i = 1; i < digit.length; i++) {
System.out.print("Value " + i + ": ");
digit[i] = in.nextInt();
sum += digit[i];
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println("Would you like to divide values?");
// Fix this later
int result= digit[i];
if (digit[i] > digit[i + 1])
result = digit[i] / digit[i + 1];
else {
(digit[i + 1] / digit[i]);
}
// Compare element 0 with 1, divide larger element by smaller element
if (digit[i])> digit[i + 3])
result = digit[i] / digit[ i+ 3];
else{
(digit[i +3])/ digit[i];
}
}
You are using int for the division. Use a double instead, as it can divide two integers with decimal point precision.
// needed for division
double[] digit = new double[11];
for (int i = 0; i < digit.length; i++)
{
digit[i] = (double)in.nextInt;
sum += (int)digit[i];
}
//you can use this variable if needed, if not, ignore it
double[] divisionResult = new double[digit.length / 2];
for(int i = 1; i < digit.length; i += 2) {
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult[i / 2] = result;
System.out.println(result);
}
EDIT: I'm also not sure why you're using
for(int i = 1; i < 11; i++)
Because you used that, I used it similarly above, but the actual convention should be:
for(int i = 0; i < 10; i++)
Doesn't make a huge difference, but better to follow good coding conventions :)
You can just use a for loop:
for (int i = 0; i < 10; i += 2) {
if (digit[i] > digit[i + 1]) {
result = digit[i] / digit[i + 1];
}
else {
result = digit[i + 1] / digit[i];
}
System.out.println(result);
}
This should work if I got it right what you want:
for (int i = 0; i < array.length; i = i+2) {
int firstDigit = array[i];
int secondDigit = array[i+1];
if (firstDigit > secondDigit) {
return firstDigit / secondDigit;
} else {
return secondDigit / firstDigit;
}
}
You iterate over the array and compare the first with the second element. By increasing your counterVariable (i) by two you always compare the 1st / 2nd, 3rd / 4th and so on numbers of the array.
Hope this helps :)
You variable i is local to the for loop in your code. If you want to use i again, you need to declare it outside of the loop to for you to use it outside the scope of the for loop. In addition, the last value of "i" here is the last array index, which would throw on array out of bound exception anyway (in other words you need to make another loop where you initialize "i" to 0 again under your "Would you like to divide values?" statement). Lastly, you need to do an assignment, so
(digit[i + 1] / digit[i]);
is not a valid statement. If you want to write it into result, you need to write:
result = (digit[i + 1] / digit[i]);
and if you want to override in place you can use
digit[i+1] = (digit[i + 1] / digit[i]);
or
digit[i + 1] /= digit[i];
Related
for(i=0; i<array.length; i++){
sum = 4 * 5;
}
What I'm trying to do is add ((array.length - 1) - i) 0's to the value of sum. For this example assume array length is 3. sum equals 20. So for the first iteration of the loop i want to add ((3 - 1) - 0) 0's to the value of sum, so sum would be 2000. The next iteration would be ((3 - 1) - 1) 0's. so sum would equal 200 and so on. I hope what I am trying to achieve is clear.
So my questions are:
Is it possible to just shift an int to add extra digits? My search thus far suggests it is not.
If not, how can i achieve my desired goal?
Thankyou for reading my question and any help would be greatly apreciated.
You can just multiply it by 10 however many times.
200 * 10 = 2000
etc
So in your case, you'd have to use a for loop until the end of the array and multiply sum every iteration. Be careful though, because the max value of an int is 2^31, so it of surpasses that, it will roll back to 0
You can add n zeroes to the end of a number, sum by multiplying sum by 10 * n.
int sum = 20;
for (int i = 0; i < ary.length; ++i) {
int zeroesToAdd = ary.length - 1 - i
sum *= (zeroesToAdd > 0) ? zeroesToAdd * 10 : 1
}
System.out.println("Sum after loop: " + sum);
for(int i=array.length; i>0; i--){
sum = 20;
for(int j=0; j < (i - 1); j++)
{
sum *= 10;
}
}
Use inner loop to multiply by 10 the number of times i is for that iteration. You would need to reset sum in your outer loop each time.
You will want to check your for-loop condition: i>array.length. Since i starts at 0, this loop will not run unless the array's length is also 0 (an empty array). The correct condition is i < array.length.
This "shift" you want can be achieved by creating a temporary variable inside the loop that is equal to the sum times 10i. In Java's Math library, there is a pow(a,b) function that computes ab. With that in mind, what you want is something like this:
int oldSum = 4 * 5;
for (int i = 0; i < array.length; i++) {
int newSum = oldSum * Math.pow(10,i);
}
Multiply by 10 instead, and use < (not >) like
int sum = 20;
int[] array = { 1, 2, 3 };
for (int i = 0; i < array.length; i++) {
int powSum = sum;
for (int j = array.length - 1; j > i; j--) {
powSum *= 10;
}
System.out.println(powSum);
}
Output is (as requested)
2000
200
20
For array of length = n; you will end up adding (n - 1) + (n - 2) + ... + 2 + 1 + 0 zeros for i = 0, 1, ... n-2, n-1 respectively.
Therefore, number of zeros to append (z) = n * (n-1) / 2
So the answer is sum * (10 ^ z)
[EDIT]
The above can be used to find the answer after N iteration. (I miss read the question)
int n = array.length;
long sum = 20;
long pow = Math.pow(10, n-1); // for i = 0
for (int i = 0; i < n; i++) {
System.out.println(sum*pow);
pow /= 10;
}
From my research, my first error was populating the array in the switch case. I fixed it so it is populated outside. I did a few tests and arr.length will give me the output of 1000 as expected, but it should be 500 (if I put 500 as the upperbound, how would I make values between 1-1000?). Case 5 works for some reason which uses arr.length as well.
I want to have 500 integers between the value of 1-1000 print out various outcomes. There are no errors in the code. All cases except case 2 & 7 work.
import java.util.Scanner;
import java.util.Random;
class ArrayMenu {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Pick an option 1-7, 0 to exit");
byte menu;
Random num = new Random();
int[] arr = new int[1000];
for (int i = 0; i <= 500; i++) {
arr[i] = num.nextInt(500);
}
do {
menu = scan.nextByte();
switch (menu) {
case 1:
for (int i = 0; i <= 500; i++) {
System.out.println(arr[i]);
}
break;
case 2:
int mean = 0;
for (int i = 0; i <= 500; i++) {
int sum = 0;
int z = arr[i];
sum = sum + z;
mean = sum / arr.length;
}
System.out.println("The mean is " + mean);
break;
case 3:
for (int i = 0; i <= 500; i++) {
int y = arr[i];
if (y % 2 != 0) System.out.println(arr[i]);
}
break;
case 4:
for (int i = 0; i <= 500; i++) {
int x = arr[i];
if (x % 2 == 0) System.out.println(arr[i]);
}
break;
case 5:
System.out.println("Median is " + arr[arr.length / 2]);
break;
case 6:
System.out.println("First is " + arr[0]);
break;
case 7:
System.out.println("Last is " + arr[arr.length - 1]);
System.out.println(arr.length);
break;
}
} while (menu != 0);
scan.close();
}
}
Bonus question: how would I randomly fill with negative values instead of only positive?
This is your code right now:
case 2:
int mean = 0;
for (int i = 0; i <= 500; i++) {
int sum = 0;
int z = arr[i];
sum = sum + z;
mean = sum / arr.length;
}
System.out.println("The mean is " + mean);
break;
However, there are a couple of mistakes here. First of all, the mean could be a decimal, so you should declare it as a double, not an int. Also, there's no need to assign it in the loop; you can just assign it once after the loop. You're also redeclaring sum every loop, which means the sum never gets incremented. Here's the fixed code:
case 2:
double mean;
int sum = 0;
for (int i = 0; i <= 500; i++) {
sum = sum + arr[i];
}
mean = (double) sum / arr.length;
System.out.println("The mean is " + mean);
break;
Also, for this line:
int[] arr = new int[1000];
You allocate an array of 1000 elements, but only fill from 0 to 500 inclusive (which is 501 elements). If you want arr.length to work properly, only allocate what you need:
int[] arr = new int[501];
If you don't want to manually allocate, then use ArrayLists instead.
If you want a negative number between -500 and 500, then generate one between 0 and 1000 then subtract 500:
rand.nextInt(1000) - 500
Note that case 5 also doesn't work. The mean is not defined as 'the middle in a random assortment', there is nothing special about the 500th element. It's defined as: "Once you've sorted it all, the middle element". You aren't sorting anything.
Without resorting to calling Arrays.sort (I don't know if your homework assignment allows you to do this), case 5 is in fact the one that's the most complicated to write.
Furthermore, you have an array of 1000 slots (so, array.length is 1000), and you wrote a bunch of code that assumes 1000 is in fact how large your array actually is - such as your 'print the last' code returning the [999] element. However, at the start, you only fill the first 500 with random numbers, the remaining 500 remain unfilled, which means they retain their initial value, which is 0.
Thus, we get to:
All cases except case 2 & 7 work.
No, they don't.
Programming is really, really hard. Before concluding that your stuff works just because it compiled and it ran, check that the outputs you see actually make sense.
for (int i = 0; i <= 500; i++) {
arr[i] = num.nextInt(500);
}```
The first use of '500' is how many times you want to loop. If you want to fill the whole array, use 1000 there. The second use of 500 decides from amongst how many numbers you want to pick random numbers. 500 means that you get any number, from as low as 0 to as large as 499 (which is a total span of 500 numbers).
You've used <= and that's the mistake; use <. An array of size 1000 has valid indices [0] all the way up to and including [999], but not [1000]. Think about it: if 0 is the first element, then 999 is the 1000th element, and [1000] would be the 1001st element, which isn't there. Thus:
for (int i = 0; i < 1000; i++) {
arr[i] = num.nextInt(500);
// or if you want uniform from -500 to 500 all inclusive:
arr[i] = num.nextInt(1001) - 500;
}
why 1001? Because that's how many different numbers you can generate: 500 negative numbers, 500 positive numbers.. and 0. 1001. (That goes some way into showing you why java is 0-based, the math tends to be less weird that way).
I solved the Project Euler problem #14 https://projecteuler.net/problem=14 on Java, but when I run it in Powershell, it stops iterating at exactly i = 113383 every time. I rewrote the solution on python, and it works perfectly fine, albeit slowly. According to my (identical) python solution, the answer is that the number that produces the longest chain is 837799 and the chain is 524 operations long.
Why does the Java solution not finish the for-loop? Is there some kind of limit in Java on how long it can stay in a loop? I cannot come up with any other explanation. Java code below. I wrote the System.out.println(i) there just to see what is going on.
class ProjectEuler14 {
public static void main(String[] args) {
int largestNumber = 1;
int largestChain = 1;
int currentNumber;
int chainLength;
for (int i = 2; i < 1000000; i++) {
System.out.println(i);
currentNumber = i;
chainLength = 0;
while (currentNumber != 1) {
if (currentNumber % 2 == 0) currentNumber /= 2;
else currentNumber = 3 * currentNumber + 1;
chainLength++;
}
if (chainLength > largestChain) {
largestChain = chainLength;
largestNumber = i;
}
}
System.out.println("\n\nThe number under million that produces the "
+ "longest chain is " + largestNumber +
" and the chain's length is " + largestChain);
}
}
It's not the for loop. It's the while loop. The condition currentNumber != 1 is always true; forever.
In java, an int is specifically defined as an integral number between -2^31 and +2^31 -1, inclusive, and operations 'roll over'. try it!
int x = 2^31 -1;
x++;
System.out.println(x);
this prints a large negative number (in fact, precisely -2^31).
It's happening in your algorithm, and that's why it never finishes.
A trivial solution is to 'upgrade' to longs; they are just as fast, really (yay 64-bit processors!) and use 64 bits, thus giving them a range of -2^63 to +2^63-1.
Python sort of scales up its numbers into slowness silently, java makes different choices (and, for crypto and other purposes, that rollover thing is in fact desired).
If you want to go even further, you can always use BigInteger, which grows as much as you need forever (becoming slower and taking more memory as it goes).
To know rollover occurred, the 3* operation would then result in a number that is lower than the original, and you can check for that:
replace:
else currentNumber = 3 * currentNumber + 1;
with:
else {
int newNumber = currentNumber * 3 + 1;
if (newNumber < currentNumber) throw new IllegalStateException("Overflow has occurred; 3 * " + currentNumber + " + 1 exceeds ints capacities.");
currentNumber = newNumber;
}
and rerun it. You'll see your app nicely explain itself.
The currentNumber is exceeding size of int, use long instead.
Do you hava problem overflow int.
Change int to long.
long largestNumber = 1;
long largestChain = 1;
long currentNumber;
long chainLength;
for (int i = 2; i < 1000000; i++) {
//System.out.println(i);
currentNumber = i;
chainLength = 0;
while (currentNumber != 1) {
//System.out.println("# = " + currentNumber);
if (currentNumber % 2 == 0) {
currentNumber /= 2;
} else {
currentNumber = (3 * currentNumber) +1 ;
}
chainLength++;
}
// System.out.println("################################ " + i);
if (chainLength > largestChain) {
largestChain = chainLength;
largestNumber = i;
}
}
System.out.println("\n\nThe number under million that produces the "
+ "longest chain is " + largestNumber
+ " and the chain's length is " + largestChain);
I have created a program that calculates the mean, median, and variance. the program accepts up to 500 inputs. All of my methods work perfectly when there are 500 inputs (max size of my array). When there are less inputs, only the 'mean' calculator works. Here's the entire program:
public class StatsPackage{
static int i = 0, arrayLength;
static double sum = 0, mean, median, sumOfSquares, variance, stdDev;
static double calcMean (int inputs[], int count) throws IOException{
for (i = 0; i < count; i++){
sum += inputs[i];
}
mean = (sum/count);
return mean;
}
static double calcMedian (int inputs[], int count){
Arrays.sort(inputs);
if (count % 2 == 0){
median = ((inputs[(count/2)] + inputs[(count/2)- 1])/2) ;
}
if (count % 2 != 0){
median = inputs[(count-1)/2];
}
return median;
}
static double calcVariance (int inputs[], int count){
sum = 0;
for (i = 0; i < count; i++){
sumOfSquares += (inputs[i]*inputs[i]);
}
for (i = 0; i < count; i++){
sum = sum + inputs[i];
}
variance = ((sumOfSquares/count) - (sum * sum)/(count * count));
return variance;
}
static double calcStdDev (double varianceInput){
stdDev = Math.sqrt(variance);
return stdDev;
}
public static void main(String[] args) throws IOException {
NumberFormat nf = new DecimalFormat("0.##");
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
String str = "test";
int inputs[] = new int [500];
int counter = 0;
int i = 0;
while ((str = stdin.readLine()) != null && i < 500) {
inputs[i] = Integer.parseInt(str);
i++;
counter++;
}
System.out.println("Mean: " + nf.format(StatsPackage.calcMean(inputs, counter)));
System.out.println("Median: " + nf.format(StatsPackage.calcMedian(inputs, counter)));
System.out.println("Variance: " + nf.format(StatsPackage.calcVariance(inputs, counter)));
System.out.println("Standard Deviation: " + nf.format(StatsPackage.calcStdDev(variance)));
}
}
Here is an example output when 10 random numbers are entered:
Mean: 47.90
Median: 0.00
Variance: 0.00
Standard Deviation: 0.00
Here is the same code when 500 numbers are entered (the max size of my array):
Mean: 47.27
Median: 47.00
Variance: 856.71
Standard Deviation: 29.27
These outputs are consistent. I input 10 numbers, and I only get the mean method to work. I input 500 numbers and I get all of them working. I'm running this program against another tester program, not by inputting the numbers myself in eclipse. The tester program is my instructor's and I trust his program is working correctly.
Can anyone please help? I'm about to tear my hair out.
The problem is that you are initializing an array of size 500, but then not using all 500 indices. That means you have an array like:
[2,5,3,7,8,2,......,0,0,0,0,0,0,0,0,0,0,0,0]
So your code is going to calculate the median and std devation with all those 0s. What you should be using is an ArrayList. An ArrayList will expand in size as you add elements, whereas a regular list cannot change size.
If you cannot use an ArrayList, then you have to do a bit more work.
while ((str = stdin.readLine()) != null && i < 500) {
inputs[i] = Integer.parseInt(str);
i++;
counter++;
}
Your counter variable already has the information you need. Now, before passing this array to your mean/median/stddev methods, you need to reduce the size of the array. The easiest way to do this is to use an existing method provided to all arrays, called CopyOf() : CopyOf() method for Arrays
int[] newArray = Arrays.copyOf(inputs, counter);
Now replace your old input array with your new newArray in your method calls:
System.out.println("Mean: " + nf.format(StatsPackage.calcMean(newArray, counter)));
System.out.println("Median: " + nf.format(StatsPackage.calcMedian(newArray, counter)));
System.out.println("Variance: " + nf.format(StatsPackage.calcVariance(newArray, counter)));
System.out.println("Standard Deviation: " + nf.format(StatsPackage.calcStdDev(variance)));
I assume you tested it with random positive integers, as it seems to be the case for these results.
When you input n (where n is small in comparison to 500) positive integers, your array is mostly full of 0's.
As Array.sort sorts the array in-place, calcMedian modifies the actual array passed, placing all these 0's to the front, and the median is, naturally, 0, as all n of them are in the back.
Then calcVariance calculates the variance of the first n 0's, as the array was sorted previously.
Finally, calcStdDev refers to the result of calcVariance.
To fix this, you should consider:
Sorting the array with this method taking a starting and ending indices.
Making a copy of the array before sorting.
Keeping the class stateless - all these methods could take anything required as arguments (while this is not strictly necessary, it will save you a lot of time in the future).
Your method of calculating variance is wrong. Have a look at the definition of the variance (for instance on wikipedia).
import java.util.Arrays;
public class StatisticalCalculations {
public static void main(String[] args) {
double[] array = { 49, 66, 73, 56, 3, 39, 33, 77, 54, 29 };
double mean = getMean(array);
double var = getVariance(array);
double med = getMedian(array);
System.out.println(Arrays.toString(array));
System.out.println("mean : " + mean);
System.out.println("variance : " + var);
System.out.println("median : " + med);
}
private static double getMean(double[] array) {
int l = array.length;
double sum = 0;
for (int i = 0; i < l; i++)
sum += array[i];
return sum / l;
}
private static double getVariance(double[] array) {
double mean = getMean(array);
int l = array.length;
double sum = 0;
for (int i = 0; i < l; i++)
sum += (array[i] - mean) * (array[i] - mean);
return sum / l;
}
private static double getMedian(double[] array) {
int l = array.length;
// copy array to leave original one untouched by sorting
double[] a = new double[l];
for (int i = 0; i < l; i++)
a[i] = array[i];
Arrays.sort(a);
if (l % 2 == 0)
return (a[l / 2 - 1] + a[l / 2]) / 2;
else
return a[(l - 1) / 2];
}
}
Also, you have an issue with your array, as it is fixed size versus a variable size of user inputs. Consider using ArrayList<Double> or something similar as a container for your values to avoid this problem.
for(i=0; i<array.length; i++){
sum = 4 * 5;
}
What I'm trying to do is add ((array.length - 1) - i) 0's to the value of sum. For this example assume array length is 3. sum equals 20. So for the first iteration of the loop i want to add ((3 - 1) - 0) 0's to the value of sum, so sum would be 2000. The next iteration would be ((3 - 1) - 1) 0's. so sum would equal 200 and so on. I hope what I am trying to achieve is clear.
So my questions are:
Is it possible to just shift an int to add extra digits? My search thus far suggests it is not.
If not, how can i achieve my desired goal?
Thankyou for reading my question and any help would be greatly apreciated.
You can just multiply it by 10 however many times.
200 * 10 = 2000
etc
So in your case, you'd have to use a for loop until the end of the array and multiply sum every iteration. Be careful though, because the max value of an int is 2^31, so it of surpasses that, it will roll back to 0
You can add n zeroes to the end of a number, sum by multiplying sum by 10 * n.
int sum = 20;
for (int i = 0; i < ary.length; ++i) {
int zeroesToAdd = ary.length - 1 - i
sum *= (zeroesToAdd > 0) ? zeroesToAdd * 10 : 1
}
System.out.println("Sum after loop: " + sum);
for(int i=array.length; i>0; i--){
sum = 20;
for(int j=0; j < (i - 1); j++)
{
sum *= 10;
}
}
Use inner loop to multiply by 10 the number of times i is for that iteration. You would need to reset sum in your outer loop each time.
You will want to check your for-loop condition: i>array.length. Since i starts at 0, this loop will not run unless the array's length is also 0 (an empty array). The correct condition is i < array.length.
This "shift" you want can be achieved by creating a temporary variable inside the loop that is equal to the sum times 10i. In Java's Math library, there is a pow(a,b) function that computes ab. With that in mind, what you want is something like this:
int oldSum = 4 * 5;
for (int i = 0; i < array.length; i++) {
int newSum = oldSum * Math.pow(10,i);
}
Multiply by 10 instead, and use < (not >) like
int sum = 20;
int[] array = { 1, 2, 3 };
for (int i = 0; i < array.length; i++) {
int powSum = sum;
for (int j = array.length - 1; j > i; j--) {
powSum *= 10;
}
System.out.println(powSum);
}
Output is (as requested)
2000
200
20
For array of length = n; you will end up adding (n - 1) + (n - 2) + ... + 2 + 1 + 0 zeros for i = 0, 1, ... n-2, n-1 respectively.
Therefore, number of zeros to append (z) = n * (n-1) / 2
So the answer is sum * (10 ^ z)
[EDIT]
The above can be used to find the answer after N iteration. (I miss read the question)
int n = array.length;
long sum = 20;
long pow = Math.pow(10, n-1); // for i = 0
for (int i = 0; i < n; i++) {
System.out.println(sum*pow);
pow /= 10;
}