Program only works whe negative numbers entered in array last - java

For some reason my computePositiveSum final output for "The sum of the positive numbers" is wrong when a negative number is entered before any positive numbers. It seems like what's happening is instead of ignoring the negative numbers it subtracts it's sum from the total. So if my input was (-4,2,3) it would say the sum of positive numbers was 1. I'm not really sure what is wrong with the method.
/* Description: Write a program that reads in a sequence of numbers
(not necessary integers) from standard input until 0
is read, and stores them in an array. This is done
using iteration (choose for, while, or do while loop).
You may assume that there will not be more than 100 numbers.*/
import java.util.Scanner;
import java.text.DecimalFormat;
public class Assignment2
{
public static void main (String[] args)
{
Scanner scan= new Scanner(System.in);
int count=0;
double[] num= new double[100];
for(int i=0;i<num.length;++i)
{
num[i]= scan.nextDouble();
if (num[i] == 0) {
break; }
count++;
}
double min= findMin(num,count);
double pos= computePositiveSum(num, count);
int c= countNegative(num,count);
DecimalFormat fmt = new DecimalFormat ("0");
DecimalFormat fmt2 = new DecimalFormat ("$0.00");
System.out.println("The minimum number is " +fmt.format(min));
System.out.println("The sum of the positive numbers is "+fmt2.format(pos));
System.out.println("The total number of negative numbers is " +c);
}//End Main
public static double findMin(double[] num, int count)
{
double min = num[0];
for(int i=1;i<count;i++){
if(num[i] < min)
{
min = num[i];
}
}
return min;
}//end findMin
public static double computePositiveSum(double[] num, int count)
{
double pos=num[0];
for(int i=1;i<count;i++){
if(num[i] > 0)
{
pos=pos+num[i];
}
}
return pos;
}
public static int countNegative(double[] num, int count)
{
double a=num[0];
int c=0;
for(int i=0;i<count;i++){
if(num[i] < 0)
{
c++;
}
}
return c;
}//end countNegative
}

You are assigning to the actual sum pos the value of the first element in the array. So if the first element is negative it will be added to the sum (there is no check in the code to know if it's positive or not).
To fix this, initialize the sum pos (by the way, it is not a descriptive name) with 0. Then iterate in the for loop from 0, not from 1.
public static double computePositiveSum(double[] num, int count)
{
double pos = 0;
for (int i = 0; i < count; i++) {
if (num[i] > 0) {
pos = pos + num[i];
}
}
return pos;
}
Note: I would recommend you to name your variables with a more descriptive name. I would have declared pos with the name sum. Of course this has nothing to do with the result, but is useful for people to understand the code.

because you are doing
double pos = num[0];
then going through the remainder of the array you need to do
double pos = 0;
for (int i = 0; ...)

You're not checking the first element of the array
public static double computePositiveSum(double[] num) {
double sum = 0.0;
for(double d : num) {
if(d > 0) {
sum += d;
}
}
return sum;
}

You need to check if element 0 is greater than zero.

Related

Space between inputs doesn't give exception on array index?

I'm not sure what to title this question(if anyone has input on what to name the question, please let me know). My program asks the user for 5 int and 5 doubles. Then those numbers are put in an array and passes it to a method to get the average. My question is if I separate the user input by spaces and press enter(like so, 5 space 6...enter; it allows me to enter more than what is allowed in the array index. Why doesn't it give you a error? and how do you prevent this? Also any advice on how I write code would be helpful too!
Here is the code.
import java.util.*;
public class Lab7A_BRC{
public static void main(String[] args) {
System.out.println("\t\t Average arrays ");
Scanner input = new Scanner(System.in);
//array count varriable
int n = 5;
//array declaration
int [] list1 = new int[n];
double [] list2 = new double[n];
System.out.print("Enter 5 integer values. ");
for(int i = 0; i < n; i++) {
list1[i]= input.nextInt();
if(i == (n - 1)){
System.out.println("\t The average of the 5 integers is "
+ average(list1, n));
}
}
System.out.println("Enter 5 double values. ");
for (int i = 0; i < n; i++){
list2[i]= input.nextDouble();
if(i == (n-1)){
System.out.println("\t The average of the 5 doubles is "
+ average(list2, n));
}
}
}
public static int average(int[] array, int n){
int sum = 0;
for(int i = 0; i < n; i++){
int holdNumber = array[i];
sum += holdNumber;
}
int average = sum / n;
return average;
}
public static double average(double[] array, int n){
double sum = 0;
for(int i = 0; i < n ; i++){
double holdNumber = array[i];
sum += holdNumber;
}
double average = sum / n;
return average;
}
}
It doesn't give you an error because you only read the first 5 values, as stated in your for loop.
The first thing is you should decouple your input logic from your output logic, so you know for sure you're in your 5th number when you exit the for loop.
Then you can check if there's anything else than a blank string left, if there is then you can throw an exception stating it has too many numbers.
I've adapted the integer part, you can easily adapt the doubles logic.
Feel free to ask if you have any doubts.
The adapted code:
import java.util.Scanner;
public class Lab7A_BRC {
public static void main(String[] args) {
System.out.println("\t\t Average arrays ");
Scanner input = new Scanner(System.in);
//array count varriable
int n = 5;
//array declaration
int[] list1 = new int[n];
double[] list2 = new double[n];
System.out.print("Enter 5 integer values. ");
for (int i = 0; i < n; i++) {
list1[i] = input.nextInt();
}
if (!input.nextLine().equals("")) {
throw new RuntimeException("Too many numbers entered!");
}
System.out.println("\t The average of the 5 integers is "
+ average(list1, n));
System.out.println("Enter 5 double values. ");
for (int i = 0; i < n; i++) {
list2[i] = input.nextDouble();
if (i == (n - 1)) {
System.out.println("\t The average of the 5 doubles is "
+ average(list2, n));
}
}
}
public static int average(int[] array, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
int holdNumber = array[i];
sum += holdNumber;
}
int average = sum / n;
return average;
}
public static double average(double[] array, int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
double holdNumber = array[i];
sum += holdNumber;
}
double average = sum / n;
return average;
}
}
I think you're confusing two different concepts.
One is the input, and another one is your variable.
Input is a buffer (read: block of data) managed by the shell and the Scanner. It can contain an arbitrary amount of data, you have nothing to do with it.
What happens in your code is that the scanner takes the buffer and parses (read: interprets) the next valid value from the buffer and transforms it into the right data type - until the "nth" element. So, because you're taking "n" elements (controlled by the for), it doesn't matter how much data is available in the input buffer, you always read a finite amount.
The only way the amount of data matters is when there's no more input for the scanner to read from, in which case it asks for more input.
The reason is that you are iterating till the n number that you defined in the beginning.
for(int i = 0; i < n; i++) {
list1[i]= input.nextInt();
So if you try to enter 1 1 1 1 1 124124 1241 you will see that the average is 1 because the rest is ignored and not added to the list. Because it doest not try nextInt() more than n given.
I am a beginner, so my answer might be wrong:), sorry for that. This code is working for me. Like #iajrz mentioned, you can do spaece or newline when try to use system.in.
Because the for loop does n iterations so you pick up only the first n integers of the input. If your input is 1 2 3 4 5 6 7 8 it will select only 1 2 3 4 5 (because in your code n=5). You can also insert multiple digits number separated by spaces, so input 15 0 00 0010 0 has average=5

Write a method to work out the sum of the first n odd numbers

First of all let me say I am quite new to programming its been my second week since I started so if you see any bad practice or error in code please accept my apologies.
I want to print sum of first n odd numbers. But so far I can only do the sum of odd number up to the given number. kindly help.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int sum = 0;
for (int i = 0; i <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
}
}
return sum;
}
}
You don't have to use a loop at all
static int sumOfOdd(int num) {
return num*num;
}
For Any Arithmetic Progression, the sum of numbers is given by,
Sn=1/2×n[2a+(n-1)×d]
Where,
Sn= Sum of n numbers
n = n numbers
a = First term of an A.P
d= Common difference in an A.P
Using above formula we can derive this quick formula to calculate sum of first n odd numbers,
Sn(odd numbers)= n²
Try this it uses a for loop that increments by two to only account for odd numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
System.out.println("The sum of the first " + n + " odd numbers is: " + sumOfOddNumbers(n));
}
public static int sumOfOddNumbers(int n) {
int sum = 0;
for(int i = 1; i < n*2; i+=2) {
sum += i;
}
return sum;
}
}
Example usage:
Enter the value of n: 5
The sum of the first 5 odd numbers is: 25
Try this:
static int sumOfOdd(int num) {
int sum = 0;
for (int i = 0; i < num; i++){
sum += i*2+1;
}
return sum;
}
It sums up all odd numbers until the limit is reached.
With i*2+1 you get the next odd number. Then you add it to the sum.
Tested with System.out.println(sumOfOdd(4)); and got the expected result 16 (1+3+5+7)
Change the counter to the number of times you add an odd number to the sum value...
static int sumOfOdd(int num) {
int sum = 0;
int i = 0;
int count = 0;
do {
if(i % 2 != 0) {
sum += i;
count++;
}
i++;
} while (count < num);
return sum;
}
Or even cleaner:
static int sumOfOdd(int num) {
int sum=0;
for (int i=1;i<num*2;i+=2) {
sum=sum+i;
}
return sum;
}
You should count how many numbers have you added and in the condition to check if count of numbers you summed is less or equal than your n. Just add the counter in your for loop and set condition to: count <= num and it should work.
Every time you add a number to the sum increment the count by count++.
The code suppose to look like this:
static int sumOfOdd(int num)
{
int sum = 0;
int count = 0;
for (int i = 0, count= 0; count <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
count++;
}
}
return sum;
}
I haven't checked it, but it should be correct
Since you don't know how many loop cycles are required you have to change the exit condition of the for loop.
Or you can use a while loop exploiting the same exit condition.
static int sumOfOdd(int num){
int sum = 0;
int counter = 0;
int currentNumber = 0;
while (counter<num){
if(currentNumber % 2 != 0){
sum += currentNumber;
counter++;
}
currentNumber++;
}
return sum;
}
Here is the complete code you'd be using:
public class YourClass {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int counter = 0;
for (int i = 0;; i++)
{
int sum = 0;
if(i % 2 != 0)
{
counter++;
sum += i;
}
if(counter == num) return sum;
}
}
}
Another alternative.
static int sumOfOdd(int num) {
int sum = 0;
int last = 2*num-1;
for (int i = 1; i <= last; i+=2){
sum += i;
}
return sum;
}
Obviously return num*num; is the most efficient but if you're obliged to use a loop then this method avoids a * inside the loop.
This will be a tiny (tiny) bit more efficient than:
for (int i = 0; i < num; ++i){
sum += 2*i+1;
}
import java.util.*;
class karan{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = n;
int sumOddNumber = n * i;
System.out.println(n*i);
}
}

Whats wrong in this code? Why it is printing "1"?

This is a Java code for printing the armstrong number from a user input a minimum digit to a user input maximum digit.
I'm getting no errors. The problem is that I the program prints an output of value 1.
How can I fix this?
package armstrong;
import java.util.Scanner;
public class armstrong {
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
System.out.println("enter min number");
int min=obj.nextInt();
System.out.println("enter max number");
int max=obj.nextInt();
int a;
for (int j = min; j <=max; j++)
{
int temp = j ;
int l=digit(j);
System.out.println(l);
int sum=0;
if(j>0)
{
a=j%10;
sum=(int) (sum+Math.pow(a,l));
j=j/10;
}
if(sum == temp)
System.out.println(temp);
//else
//System.out.println(n+ " is not an armstrong number");
}
}
//java.lang.Math.pow(double a, double b)
public static int digit(int x){
int z=0;
if(x<0)
{
x=x * -1;
}
else if(x==0)
{
x=1;
}
while(x>0)
{
x=x/10;
z++;
}
return z;
}
}
This is because you are altering your for loop index variable, j, inside the loop. The j = j/10 line automatically makes j go back to 0, and it can never increase when inside the loop, making your for loop stuck.
You should be altering the temp variable you created instead
this should work to not have your for loop be infinite:
for (int j = min; j <=max; j++)
{
int temp = j ;
int l=digit(j);
System.out.println(l);
int sum=0;
if(j>0)
{
a=temp%10;
sum=(int) (sum+Math.pow(a,l));
temp=temp/10;
}
if(sum == j)
System.out.println(j);
//else
//System.out.println(n+ " is not an armstrong number");
}
You still have a lot of work to do on your algorithm, however.
Take a look at this: http://www.programmingsimplified.com/java/source-code/java-program-armstrong-number

How to find the largest value from an array in Java?

I am writing a program which can tracking three dices' total appears.Here are my codes:
import java.util.*;
class dice{
public static void main (String[] args){
Random rnd = new Random();
int[] track = new int[19];
for (int roll=0; roll<10000; roll++){
int sum=0;
for(int i = 0; i < 3; i++) {
//roll the 6-face dice
int n = rnd.nextInt(6) + 1;
sum+=n;
}
++track[sum];
}
System.out.println("Sum\tFrequency");
for(int finalSum=3; finalSum<track.length;finalSum++){
System.out.println(finalSum+"\t"+track[finalSum]);
}
System.out.println("the largest frequency is %d", //how to find it?)
}
}
Now I am almost done. But how can I find the largest appearance and print it separately? Thank you.
You can try below code:
Arrays.sort(arr);
System.out.println("Min value "+arr[0]);
System.out.println("Max value "+arr[arr.length-1]);
public int largest(int[] myArr) {
int largest = myArr[0];
for(int num : myArr) {
if(largest < num) {
largest = num;
}
}
return largest;
}
Set the variable largest to the first item in the array. Loop over the array, whenever the current num you're in is bigger than the current largest value, set largest to num.

Not ignoring a value?

import java.util.Scanner;
import java.util.Arrays;
public class Improved {
//I resize the array here so that it only counts inputs from the user
//I want to ignore the 0 input from the user
//I think the error happens here or in my main method
public static double[] resizeArray(double[] numbers, double size) {
double[] result = new double[(int)size];
for (int i = 0; i < Math.min(numbers.length, size); ++i) {
result[i] = numbers[i];
}
return result;
}
//compute average nothing is wrong here
public static double getAverage( double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; ++i)
sum += numbers[i];
double average = sum/numbers.length;
return average;
}
//SD nothing is wrong here
public static double getSD( double[] numbers, double average) {
double sd = 0;
for ( int i = 0; i < numbers.length; ++i)
sd += ((numbers[i] - average)*(numbers[i] - average)/ numbers.length);
double standDev = Math.sqrt(sd);
return standDev;
}
//maximum nothing is wrong here
public static double getMax( double[] numbers) {
double max = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] > max){
max = numbers[i];
}
return max;
}
//minimum nothing is wrong here
public static double getMin( double[] numbers) {
double min = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] < min) {
min = numbers[i];
}
return min;
}
//median value nothing is wrong here
public static double getmed( double[] numbers) {
double median;
if (numbers.length % 2 == 0)
median = (((numbers[numbers.length/2 - 1])
+ (numbers[numbers.length/2]))/2);
else
median = numbers[numbers.length/2];
return median;
}
//the problem is in the main method i think or in the call method to resize
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] statArr = new double[99];
double size = 0;
int i = 0;
System.out.println("Type your numbers: ");
double number = input.nextDouble();
//I don't want the zero in the array, I want it to be excluded
while (number != 0){
statArr[i] = number;
i++;
number = input.nextDouble();
++size;
if ( size == statArr.length) {
statArr = resizeArray(statArr, statArr.length * 2);
}
++size;
}
statArr = resizeArray(statArr, size);
java.util.Arrays.sort(statArr);
double average = getAverage(statArr);
System.out.println( "The average is " + getAverage(statArr));
System.out.println( "The standard deviation is " + getSD(statArr, average));
System.out.println( "The maximum is " + getMax(statArr));
System.out.println( "The minimum is " + getMin(statArr));
}
}
// I don't have any concerns with computing the math parts, but I can't seem to make it so my array ignores the 0 that ends the while loop. In other words, I want every number included up until the user enters the number 0. Everything else is right. Thank you very much!
You have ++size twice. This means your resizeArray method won't work correctly:
double[] result = new double[(int)size];
Here you're allocating more than what you actually want. This is why you're getting zeroes in your array. Java arrays are initialized to 0 (in case of numeric primitive types).
As Giodude already commented, I suggest you using List implementations (typically ArrayList) instead of arrays everytime you can.
Also size could be declared as int altogether and avoid that cast (and save some extremely slight memory), you're not using it as a double anywhere.

Categories