Write a program that reads a list of 10 values from the user. Put the values in an array. The program should read the array and then calculate and display the average of the even input values and the average of the odd input values. This should be done using objects, methods, and a tester class.
I cannot figure out why I am receiving the error:
bad operand types for binary operator.
I do not know what to change. I know something is wrong with my mod (%).
Here is what I have so far for my Average class:
public class Average
{
private int[] numbers = new int[10];
double aveEven, aveOdd,sumEven=0,sumOdd=0;
int oddCounter=0, evenCounter=0;
public Average(int[] n)
{
numbers = n;
if (numbers % 2 == 0)/something is wrong here/
{
evenCounter++;
sumEven+=n;
}
else
{
oddCounter++;
sumOdd+=n;
}
}
public void aveEven()
{
for (int i = 0; i < numbers.length; i++)
{
aveEven = sumEven/evenCounter;
System.out.println("The even average is: " + aveEven);
}
}
public void aveOdd()
{
for(int i = l; i < numbers.length; i++)
{
aveOdd = sumOdd/oddCounter;
System.out.println("The odd average is: " + aveOdd);
}
}
}
For the AverageTester class I have the following:
import java.util.Scanner;
public class AverageTester
{public static void main(String[] args)
{
int[] integer = new int[10];
Scanner input = new Scanner(System.in);
for(int i=0 ; i < 10 ; i++)
{
System.out.print("Please enter a number : ");
integer[i] = input.nextInt();
}
Average example = new Average(integer);
example.aveOdd();
}
}
Also, If you see anything else that could be wrong, please let me know.
Thank you.
numbers is an array, so numbers % 2 is invalid. You should loop over the array and use the % operator on the elements of the array. The += operator should also be applied on a element of the array (i.e. numbers[i]) and not the entire array.
numbers = n;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evenCounter++;
sumEven+=numbers[i];
} else {
oddCounter++;
sumOdd+=numbers[i];
}
}
As for aveEven and aveOdd, since you already compute the sums in the constructor (or at least it seems like that's what you intended to do), you don't need a loop in these methods.
EDIT :
I originally assumed you intended to calculate the average of the numbers in even positions in the array and the average of the numbers in odd positions. After reading the question again, I think the odd/even refers to the numbers themselves, so I changed the code accordingly.
Numbers is an array and comparing an array to an int doesn't work, you could do something like this (depending on your logic):
for(int number : numbers){
if(number % 2 == 0){
evenCounter++;
sumEven += n;
}else{
oddCounter++;
sumOdd += n;
}
}
Few Mistakes
1.) if (numbers % 2 == 0), numbers is an array, use index here and loop. like this if (numbers[i] % 2 == 0).
2.) sumEven += n;, again n is an array here, need to use index.
3.) for (int i = l ; i < numbers.length ; i++) {, you have used l instead of 1.
Related
I need to program a lottery simulator and basically everything works fine but I have one small problem at the end of the problem. There are 2 Arrays(i need to work without Array Lists) which get compared. The generated winning numbers and the numbers entered by the user. I succeeded in showing what numbers are the right guesses. But what doesn't work is showing HOW MANY guesses were correct. I tried System.out.println("You guessed this many numbers right: "+intArray.length[i] but this didn't work. Is there any way to show the exact number of how many numbers were guessed right? Thanks for any help in advance
for (int i=0; i< intArray.length;i++){
for (int j=0; j< ownArray.length;j++){
if (intArray[i] == ownArray[j]){
System.out.println("Your following guess was correct: "+intArray[i]);
Just use a count variable
public static void main(String[] args) {
int[] intArray = {1,2,4,5};
int[] ownArray = {1,0,2,7};
int count = 0;
System.out.println("Your following guesses were correct: ");
for (int i = 0; i < intArray.length; i++){
for (int j = 0; j < ownArray.length; j++){
if (intArray[i] == ownArray[j]){
System.out.print(intArray[i] + " ");
count++;
}
}
}
System.out.println("\nNo. of correct guesses: " + count);
}
Output:
Your following guesses were correct:
1 2
No. of correct guesses: 2
This is actually quite simple to do if your lottery numbers are positive numbers. It is more involved if the numbers can be negative. The basic algorithm is to compare lottery numbers one by one against all the player's guesses repeatedly. If there is a match then we record -1 in the user guess array and increment a counter to track the number of correct entries.
Some code will make this clearer:
public class LotteryNumbers {
public static void main(String[] args) {
int[] lotteryNumbers = {1,2,3,4,5,6};
int[] userGuess = {1,2,3,4,8,9};
int correct = 0;
for(int i=0; i<lotteryNumbers.length; i++) {
for(int j=0; j<userGuess.length; j++) {
if( userGuess[j] == lotteryNumbers[i]) {
userGuess[j] = -1; // 'eliminate' this guess for checking
correct++;
break;
}
}
}
System.out.println("Number of correct numbers = " + correct);
}
}
Outputs:
Number of correct numbers = 4
This works because the algorithm strikes out matches in the player's guesses and guards against future matching next time through the loop. You can imagine that what we are actually doing is striking off numbers in the player's guess that match against the lottery numbers.
I need to write a program that calculates a moving average by a user inputted array. The first element of the array is the window size, and the input is terminated by a 0. The output values are printed with two digits after the decimal point.
Example input: 3 2 4 7 7 8 11 12 0
Corresponding Output: 4.33 6.00 7.33 8.67 10.33
(4.33 is average of 2,4,7 and 6 is average of 4,7,7 etc.)
Here's my code so far:
package movingaverage;
import java.util.Scanner;
public class MovingAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
avg[0] = sum / 5;
int j = 1;
for (int i = 5; i < arr.length; i++) {
sum = sum + arr[i] - arr[i - 5];
avg[j++] = sum / 5;
}
}
}
I think I have the loop right, but I'm not sure how to get the array to end at 0.
This is a possible solution.
public class Test
{
private static final Scanner SCANNER;
static {
SCANNER = new Scanner(System.in);
}
public static final void main(final String... args) {
final String[] numbers = SCANNER.nextLine().trim().split(" ");
final int consideredElements = Integer.parseInt(numbers[0]);
float sum = 0;
int value = 0;
for (int i = 1; i < numbers.length; i++) {
sum = 0;
for (int k = 0; k < consideredElements; k++) {
value = Integer.parseInt(numbers[i + k]);
if (value == 0) {
return;
}
sum += value;
}
System.out.println(new BigDecimal(sum / consideredElements).setScale(2, RoundingMode.HALF_EVEN));
}
}
}
First, you are using 5 in a couple of places in your program, I see no justification for that. Could it be that your expectation of user input lead you to put 5 where the number you really should use, depends on user input? Maybe you should use the window size instead? I’m guessing a bit here.
Next, as #lppEdd pointed out, you are not reading the numbers from your input — only the window size.
Next, you are declaring your array of size n, which I believe was your window size, not your array size. I believe the real solution to this problem is using better and more explanatory variable names.
Your code does not compile since you have not declared the array avg that you try to store your moving average into.
Fifth, when you want your average as a double, you need to convert to double before dividing (this is a classic pitfall that has already generated many questions on Stack Overflow).
I hope this gets you a couple of steps further.
I'm kind of a newbie at Java, and not very good at it. It's a trial and error process for me.
I'm working on a Java program to output the amount of primes in an array. I can get it to output the primes, but I want to also output the quantity of primes. I tried to add each prime to an array list titled "primes" then return "primes.size()" at the end of my program. It doesn't work as intended. The count is actually off. When I create an array of 5 numbers, it outputs 3 primes, 2, 3, and 5. But then it says I have 4 primes. I think it might be counting 1 as a prime. Because when I create an array of 20, the prime numbers output 2,3,5,7,11,13,17 and 19. Then it says the total prime numbers = 9. It should be 8 though.
Here's my code
public class Prime {
public static void main(String[] args) {
int index = 0;
Scanner scan = new Scanner(System. in );
System.out.println("How big would you like the array? ");
int num = scan.nextInt();
int[] array = new int[num];
ArrayList < Integer > primes = new ArrayList < Integer > ();
//System.out.println("How Many threads? ");
//int nThreads = scan.nextInt(); // Create variable 'n' to handle whatever integer the user specifies. nextInt() is used for the scanner to expect and Int.
//Thread[] thread = new Thread[nThreads];
for (int n = 1; n <= array.length; n++) {
boolean prime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
prime = false;
break;
}
}
if (prime) {
primes.add(n);
}
if (prime && n != 1) {
System.out.println(n + "");
}
}
System.out.println("Total Prime numbers = " + primes.size());
System.out.println("Prime Numbers within " + array.length);
}
}
Forgive the sloppiness of it. I actually plan on adding multithreading to it, but I wanted to get this down first.
Any help would be greatly appreciated. Thanks.
You have included 1 in your array of primes, because you started the n for loop at 1. You don't print it because of the final if statement, but it's there in the ArrayList.
Start your n for loop with n = 2. As a consequence, you won't need the final if statement, because n won't be 1 ever. You could print the prime at the same time as you add it to the ArrayList.
this is the question, and yes it is homework, so I don't necessarily want anyone to "do it" for me; I just need suggestions: Maximum sum: Design a linear algorithm that finds a contiguous subsequence of at most M in a sequence of N long integers that has the highest sum among all such subsequences. Implement your algorithm, and confirm that the order of growth of its running time is linear.
I think that the best way to design this program would be to use nested for loops, but because the algorithm must be linear, I cannot do that. So, I decided to approach the problem by making separate for loops (instead of nested ones).
However, I'm really not sure where to start. The values will range from -99 to 99 (as per the range of my random number generating program).
This is what I have so far (not much):
public class MaxSum {
public static void main(String[] args){
int M = Integer.parseInt(args[0]);
int N = StdIn.readInt();
long[] a = new long[N];
for (int i = 0; i < N; i++) {
a[i] = StdIn.readLong();}}}
if M were a constant, this wouldn't be so difficult. For example, if M==3:
public class MaxSum2 {
public static void main(String[] args){
int N = StdIn.readInt(); //read size for array
long[] a = new long[N]; //create array of size N
for (int i = 0; i < N; i++) { //go through values of array
a[i] = StdIn.readLong();} //read in values and assign them to
//array indices
long p = a[0] + a[1] + a[2]; //start off with first 3 indices
for (int i =0; i<N-4; i++)
{if ((a[i]+a[i+1]+a[1+2])>=p) {p=(a[i]+a[i+1]+a[1+2]);}}
//if sum of values is greater than p, p becomes that sum
for (int i =0; i<N-4; i++) //prints the subsequence that equals p
{if ((a[i]+a[i+1]+a[1+2])==p) {StdOut.println((a[i]+a[i+1]+a[1+2]));}}}}
If I must, I think MaxSum2 will be acceptable for my lab report (sadly, they don't expect much). However, I'd really like to make a general program, one that takes into consideration the possibility that, say, there could be only one positive value for the array, meaning that adding the others to it would only reduce it's value; Or if M were to equal 5, but the highest sum is a subsequence of the length 3, then I would want it to print that smaller subsequence that has the actual maximum sum.
I also think as a novice programmer, this is something I Should learn to do. Oh and although it will probably be acceptable, I don't think I'm supposed to use stacks or queues because we haven't actually covered that in class yet.
Here is my version, adapted from Petar Minchev's code and with an important addition that allows this program to work for an array of numbers with all negative values.
public class MaxSum4 {
public static void main(String[] args)
{Stopwatch banana = new Stopwatch(); //stopwatch object for runtime data.
long sum = 0;
int currentStart = 0;
long bestSum = 0;
int bestStart = 0;
int bestEnd = 0;
int M = Integer.parseInt(args[0]); // read in highest possible length of
//subsequence from command line argument.
int N = StdIn.readInt(); //read in length of array
long[] a = new long[N];
for (int i = 0; i < N; i++) {//read in values from standard input
a[i] = StdIn.readLong();}//and assign those values to array
long negBuff = a[0];
for (int i = 0; i < N; i++) { //go through values of array to find
//largest sum (bestSum)
sum += a[i]; //and updates values. note bestSum, bestStart,
// and bestEnd updated
if (sum > bestSum) { //only when sum>bestSum
bestSum = sum;
bestStart = currentStart;
bestEnd = i; }
if (sum < 0) { //in case sum<0, skip to next iteration, reseting sum=0
sum = 0; //and update currentStart
currentStart = i + 1;
continue; }
if (i - currentStart + 1 == M) { //checks if sequence length becomes equal
//to M.
do { //updates sum and currentStart
sum -= a[currentStart];
currentStart++;
} while ((sum < 0 || a[currentStart] < 0) && (currentStart <= i));
//if sum or a[currentStart]
} //is less than 0 and currentStart<=i,
} //update sum and currentStart again
if(bestSum==0){ //checks to see if bestSum==0, which is the case if
//all values are negative
for (int i=0;i<N;i++){ //goes through values of array
//to find largest value
if (a[i] >= negBuff) {negBuff=a[i];
bestSum=negBuff; bestStart=i; bestEnd=i;}}}
//updates bestSum, bestStart, and bestEnd
StdOut.print("best subsequence is from
a[" + bestStart + "] to a[" + bestEnd + "]: ");
for (int i = bestStart; i<=bestEnd; i++)
{
StdOut.print(a[i]+ " "); //prints sequence
}
StdOut.println();
StdOut.println(banana.elapsedTime());}}//prints elapsed time
also, did this little trace for Petar's code:
trace for a small array
M=2
array: length 5
index value
0 -2
1 2
2 3
3 10
4 1
for the for-loop central to program:
i = 0 sum = 0 + -2 = -2
sum>bestSum? no
sum<0? yes so sum=0, currentStart = 0(i)+1 = 1,
and continue loop with next value of i
i = 1 sum = 0 + 2 = 2
sum>bestSum? yes so bestSum=2 and bestStart=currentStart=1 and bestEnd=1=1
sum<0? no
1(i)-1(currentStart)+1==M? 1-1+1=1 so no
i = 2 sum = 2+3 = 5
sum>bestSum? yes so bestSum=5, bestStart=currentStart=1, and bestEnd=2
sum<0? no
2(i)-1(currentStart)+1=M? 2-1+1=2 so yes:
sum = sum-a[1(curentstart)] =5-2=3. currentStart++=2.
(sum<0 || a[currentStart]<0)? no
i = 3 sum=3+10=13
sum>bestSum? yes so bestSum=13 and bestStart=currentStart=2 and bestEnd=3
sum<0? no
3(i)-2(currentStart)+1=M? 3-2+1=2 so yes:
sum = sum-a[1(curentstart)] =13-3=10. currentStart++=3.
(sum<0 || a[currentStart]<0)? no
i = 4 sum=10+1=11
sum>bestSum? no
sum<0? no
4(i)-3(currentStart)+1==M? yes but changes to sum and currentStart now are
irrelevent as loop terminates
Thanks again! Just wanted to post a final answer and I was slightly proud for catching the all negative thing.
Each element is looked at most twice (one time in the outer loop, and one time in the while loop).
O(2N) = O(N)
Explanation: each element is added to the current sum. When the sum goes below zero, it is reset to zero. When we hit M length sequence, we try to remove elements from the beginning, until the sum is > 0 and there are no negative elements in the beginning of it.
By the way, when all elements are < 0 inside the array, you should take only the largest negative number. This is a special edge case which I haven't written below.
Beware of bugs in the below code - it only illustrates the idea. I haven't run it.
int sum = 0;
int currentStart = 0;
int bestSum = 0;
int bestStart = 0;
int bestEnd = 0;
for (int i = 0; i < N; i++) {
sum += a[i];
if (sum > bestSum) {
bestSum = sum;
bestStart = currentStart;
bestEnd = i;
}
if (sum < 0) {
sum = 0;
currentStart = i + 1;
continue;
}
//Our sequence length has become equal to M
if (i - currentStart + 1 == M) {
do {
sum -= a[currentStart];
currentStart++;
} while ((sum < 0 || a[currentStart] < 0) && (currentStart <= i));
}
}
I think what you are looking for is discussed in detail here
Find the subsequence with largest sum of elements in an array
I have explained 2 different solutions to resolve this problem with O(N) - linear time.
I will be creating an array that accepts 10 integers from the user, finds the second largest value, and finally adds all odd numbers. If I use 10-1 as input, it will do everything correctly; the problem arises when the first number entered is an odd number it will ignore it in the summation and I have no idea as to why. Any ideas?
for (int j = 0; j < 10; j++) {
arra[j] = keyboard.nextInt();
if (arra[j] > maxValue) {
secondLargest = maxValue;
maxValue = arra[j];
} else if (arra[j] > secondLargest) {
secondLargest = arra[j];
}
}
System.out.println("The second largest number is: " + secondLargest);
for (int i = 0; i < arra.length; i++) {
if (i % 2 == 0) {
numberOdds++;
}
}
int[] odds = new int[numberOdds];
for (int i = 1; i < arra.length; i++) {
if (arra[i] % 2 == 1) {
odds[count] = arra[i];
count++;
}
}
for (int i = 0; i < odds.length; i++) {
sum = sum + odds[i];
}
System.out.println("The sum of all odd numbers is: " + sum);
[This appears to be homework, so exact code will not be given.]
For good form, consider getting the input array separately -- then call a method to get each computational result you want.
For "second largest" method, you do not appear to be initializing the two values. Make sure you handle the (odd) case in which all values in the array are the same. Perhaps you want to set the max and the second-to-max to the first array value and then loop on the 2nd through the end?
To add all the odd numbers create a method that sets the initial sum to zero and then add a number only if it is odd (n % 2 != 0)