The code compiles, but all my answers come out to be 0.
import java.util.Scanner;// use the Scanner class located in the "java.util" directory
public class Assignment2
{
public static void main(String[] args)//main method that runs the program using methods below
{
double[] numbers = new double[100];
Scanner input = new Scanner(System.in);
int count;
int c=0;
do
{
count = input.nextInt();
c++;
} while (count != 0 && c < numbers.length);
double min = findMin(numbers, numbers.length);
int countNeg = countNegative(numbers, numbers.length);
double sum = computePositiveSum(numbers, numbers.length);
System.out.println("The minimum number is " +min);
System.out.println("The sum of the positive numbers is $" +countNeg) ;
System.out.println("The total number of negative numbers is " +sum);
}
public static double findMin(double[] numbers, int count) //finds and displays the minimum input value
{
double min = numbers[0];
for(count =1; count<numbers.length; count++)
{
if(numbers[count] <min)
{
min = numbers[count];
}
}
return min;
}
public static int countNegative (double[] numbers, int count) //counts the number of times a negative number is added to the array
{
int countNeg =0;
for (count = 0; count < numbers.length; count++)
{
if(numbers[count] < 0)
{
countNeg = countNeg + 1;
}
}
return countNeg;
}
public static double computePositiveSum(double[] numbers, int count)//calculates the sum of the positive integers in the array
{
double sum = 0;
for(count=0; count<numbers.length; count++)
{
if(numbers[count] > 0)
{
sum = sum + numbers[count];
}
}
return sum;
}
}
You are not assigning the entered values to the array numbers. Add this
numbers[c] = count;
inside the do-while loop:
do {
count = input.nextInt();
numbers[c] = count;
c++;
} while (count != 0 && c < numbers.length);
Note that if you just input positive (> 0) numbers and don't fill the whole array numbers, findMin() will return 0, because it is the default value for the elements of the array.
Edit:
I would say that the print statement
System.out.println("The sum of the positive numbers is $" + countNeg);
System.out.println("The total number of negative numbers is " + sum);
are not coherent with the methods called. It should be:
System.out.println("The sum of the positive numbers is " + sum);
System.out.println("The total number of negative numbers is " + countNeg);
double[] numbers = new double[100];
Scanner input = new Scanner(System.in);
int count;
int c=0;
do
{
count = input.nextDouble();
numbers[c] = count;
c++;
} while (count != 0 && c < numbers.length);
This code should work. You have to add the numbers to the array which you are entering through stdin
double[] numbers = new double[100];
Here you are initializing the array with all 0.0 elements. You want to take input int he array from stdin?
You don't put anything into numbers array so they are all 0. The corrected code is this:
do
{
numbers[c] = input.nextDouble();
c++;
} while (numbers[c] != 0 && c < numbers.length);
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
Here is my code:
package project4;
import java.util.Scanner;
public class ScoreAnalyzer {
//#OfScores is the length of the scores array
public static int numberOfScores = 0;
public static double[] scores = new double[numberOfScores];
public static double sum = 0.0;
public static double place = 0.0;
//Of sorted list
public static double[] sortedList = new double[numberOfScores];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of scores you'd like to average: ");
numberOfScores = input.nextInt();
scores = new double[numberOfScores];
for (int count = 0; count < scores.length; count++) {
System.out.print("Enter score #" + count + ": ");
place = input.nextDouble();
scores[count] = place;
System.out.println("The score of " + scores[count] + " is " + getGrade(count));
}
sumOfScores();
System.out.println("The average of these scores is: " + averageOfScores());
sort();
System.out.println("The sorted list of scores (above average scores are "
+ "marked with an\n" + "asterisk '*'): " + sortedList[numberOfScores]);
}
public static char getGrade(int i) {
//this
if (scores[i] >= 90.0) {
return 'A';
}
if (scores[i] >= 80.0) {
return 'B';
}
if (scores[i] >= 70.0) {
return 'C';
}
if (scores[i] >= 60.0) {
return 'D';
}
else {
return 'F';
}
}
public static double sumOfScores() {
//sum = 0.0;
for (int i = 0; i < numberOfScores; i++) {
sum += scores[i];
}
return sum;
}
public static double averageOfScores() {
double average = sum / numberOfScores;
return average;
}
public static void sort() {
for (int i = 0; i < scores.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = scores[i];
int currentMinIndex;
currentMinIndex = i;
for (int j = i + 1; j < scores.length; j++) {
if (currentMin > scores[j]) {
currentMin = scores[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
sortedList[currentMinIndex] = scores[i];
scores[i] = currentMin;
}
}
}
}
The program's purpose is to prompt the user for the number of scores to be entered first, then allow the user to enter that number of scores. As each score is entered, the program should give them a grade for each score inputted. The program then should use a method to find the sum, pass that sum into a method that finds the average, and sort the array in a method.The sorted array should be displayed along with the average and each score which is above the average should be noted with an asterisk beside it.
When I run the program, I am able to enter the number of scores I want to average, input those scores, obtain the sum and average but I'm having problem sorting it to have the asterisk to above average numbers:
Enter the number of scores you'd like to average: 3
Enter score #0: 90
The score of 90.0 is A
Enter score #1: 80
The score of 80.0 is B
Enter score #2: 70
The score of 70.0 is C
The average of these scores is: 80.0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at project4.ScoreAnalyzer.sort(ScoreAnalyzer.java:86)
at project4.ScoreAnalyzer.main(ScoreAnalyzer.java:32)
There is a problem with the terminating condition of your for loop. Since the array index starts with 0, the highest index will go up to 2 for an array of size 3. However, count, using which you are accessing elements of scores[], is going up to 3 in your for loop and that is the reason for the ArrayOutOfBoundsException. Change the for loop as follows:
for (int count = 0; count < scores.length ; count++)
I am trying to find sum and averags of user inputed numbers and i also Need my program to only sum the positive numbers entered.
It needs to calculate only the positive numbers sum and ignore the negative inputs, would i put my num=0 or not?
import java.util.Scanner;
public class J12ForSumPos {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int maxNumbers, i, num, average;
int sum = 0;
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for (i = 1; i <= maxNumbers; i = i + 1) {
System.out.print("Enter Value " + i + ": ");
num = console.nextInt();
sum = sum + num;
}
average = sum / maxNumbers;
if (sum >= 0) {
System.out.println();
System.out.println("Sum: " + sum);
System.out.println();
System.out.println("Average: " + average);
System.out.println();
} else {
System.out.println("Sum is: " + sum * 0);
System.out.println();
System.out.println("Cannot Calculate Average - no positives entered");
}
}
}
You can try something like this:
Scanner console = new Scanner(System.in);
int maxNumbers = 0;
int totalSum = 0; // Sum of all numbers (positive and negative)
int totalAverage = 0; // Average of all numbers (positive and negative)
int positiveSum = 0; // Sum of all positive numbers
int positiveAverage = 0; // Average of all positive numbers
int positiveNumberCount = 0; // Amount of positive numbers entered
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for(int i=1; i<=maxNumbers; i=i+1)
{
System.out.print("Enter Value " + i + ": ");
int num = console.nextInt();
if(num >= 0) {
positiveSum = positiveSum + num;
positiveNumberCount = positiveNumberCount + 1;
}
totalSum = totalSum + num;
}
positiveAverage = positiveSum / positiveNumberCount;
totalAverage = totalSum / maxNumbers;
It's up to you to decide whether or not to include 0 as a positive or a negative number, or exclude it. In my example it's being treated as a positive number.
The purpose for the code is to prompt the user for 10 integers and then display the largest and smallest integer. I was able to ask the user for the 10 integers and display the largest number; however, the smallest number isn't shown. I believe the issue is with me setting smallest to 0.
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
int counter = 1;
int largest = 0;
int smallest = 0;
int number = 0;
Scanner input= new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else {
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}
Initialize your values like this so we guarantee that we start with the smallest/largest possible reference for our numbers to compare against to:
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int number;
int old = Integer.MIN_VALUE;
...and then some tweaks have to be made:
Change the way you check for dupe numbers (use and old variable).
Check if every new number is smaller than smallest number always (so, in the first iteration we assign the first value to smallest and largest)
Like this:
number = input.nextInt();
if (old != number) {
old = number;
if (number > largest) {
largest = number;
}
if(number < smallest) {
smallest = number;
}
/* consider moving next line here (this will guarantee to go to the next
iteration only if the numbers are different, and get in the final messages,
valid values for `smallest` and `largest` */
// counter = counter + 1;
} else {
System.out.print("Number isn't distinct");
}
Just make > into >= and < into `<=
Since 0 < 0 evaluates to false, your code block does not run. Thus the correction.
Variable smallest is always 0 so the program never go into this block else if(number < smallest)
You should add this code before if(number < smallest)
if(smallest == 0) {
smallest = number;
}
Also your code doesn't catch the distinct numbers. To find the distinct number you should define a list List<Integer> numbers = null; at the start of the program.
Then you can check if the input is entered or not in the while loop like this:
if(numbers.contains(number))
System.out.print("Number isn't distinct");
else
numbers.add(number);
Sets the largest and smallert variables with the user's first input and then compare
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner input= new Scanner(System.in);
int number = input.nextInt();
int counter = 1;
int largest = number;
int smallest = number;
while (counter < 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}
I am moving along in this program just fine, but as I have progressed I have seemingly made some logic errors that are tough to find & need some help. I have methods that sort the array from least to greatest. Whenever I print the smallest number to the screen it always shows that number as 0 even if I haven't typed any zero. I can get the correct highest number, except for when the user enters the max amount of numbers, then it prints the second highest number. Sometimes I get the correct output for the median, but never get the correct output for the average. Any help is greatly appreciated! I feel like I am close to the correct code, but these errors are giving me a tough time.
public static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {
//change to 100 when done testing
final int MAXSIZE = 10;
int[] nums = new int [MAXSIZE];
int usedSize, indexOfNextSmallest = 0;
double median, average;
System.out.println("Please enter each number starting from least to greatest(a negative number will quit input): ");
usedSize = getNums(nums);
for (int index = 0; index < nums.length -1; index++) {
indexOfNextSmallest = getIndexOfSmallest(index, nums);
interchange(index, indexOfNextSmallest, nums);
}
median = medians(nums);
average = averages(nums);
System.out.println("The smallest number entered is " + nums[0] + ".");
System.out.println("The largest number entered is " + nums[nums.length-1] + ".");
System.out.println("The median is: " + median);
System.out.println("The average is: " + average);
}
public static int getIndexOfSmallest(int startIndex, int[] nums) {
int min = nums[startIndex];
int indexOfMin = startIndex;
for (int index = startIndex +1; index < nums.length; index++) {
if (nums[index] < min) {
min = nums[index];
indexOfMin = index;
}
}
return indexOfMin;
}
private static void interchange(int index, int indexOfNextSmallest, int[] nums) {
int temp = nums[index];
nums[index] = nums [indexOfNextSmallest];
nums[indexOfNextSmallest] = temp;
}
public static int getNums(int nums[]) {
int usedSize = 0, userValue = 0;
while(userValue >= 0 && usedSize < nums.length) {
nums[usedSize] = userValue;
userValue = kbd.nextInt();
usedSize++;
}
if(!(userValue >= 0)) {
--usedSize;
System.out.println(usedSize + " numbers entered.");
}
else if(!(usedSize < nums.length)) {
System.out.println("Maximum amount of inputs (" + nums.length + ") reached.");
}
return usedSize;
}
public static double medians(int nums[]) {
double median;
if (nums.length % 2 == 0)
median = ((double)nums[nums.length / 2] + (double)nums[nums.length / 2 - 1]) / 2;
else
median = (double)nums[nums.length / 2];
return median;
}
public static double averages(int nums[]) {
double average;
int sum = 0;
for (int index = 0; index < nums.length; index++){
sum = sum + nums[index];
}
average = ((double)sum / (double)nums.length);
return average;
}
}
This is the output that I am getting if I enter 1, 2, 3, 4, 5, -7(the negative is to stop user input(could that be a problem?))
Please enter each number starting from least to greatest(a negative number will quit input):
1 2 3 4 5 -7
5 numbers entered.
The smallest number entered is 0.
The largest number entered is 5.
The median is: 0.5
The average is: 1.5
The answers I should be getting with correct code is 1, 5, 3.0, & 3.0
Thank you again for any help.
Your medians() and averages() methods look fine. I would recommend that you get rid of the getIndexOfSmallest() and interchange() methods. You only ostensibly need these methods because you are trying to sort. But I believe the sort is instead altering the array. Use the following method to find the minimum value:
public int getMin(int[] nums) {
int min = nums[0];
for (int i=1; i < nums.length; ++i) {
if (nums[i] < min) {
min = nums[i];
}
}
return min;
}
I will leave it as a homework assignment for you to code a method to find the maximum value.
The whole thing goes worng in two places:
The first one
final int MAXSIZE = 10;
int[] nums = new int [MAXSIZE];
This means that even though the program stopped accepting values after a negative value; all the rest of the array is filled with 0s.
To resolve this, you can choose to use ArrrayList instead on int array.
The second issue
The existing code for getnums is
public static int getNums(int nums[]) {
int usedSize = 0, userValue = 0;
while(userValue >= 0 && usedSize < nums.length) {
nums[usedSize] = userValue;
userValue = kbd.nextInt();
usedSize++;
}
if(!(userValue >= 0)) {
--usedSize;
System.out.println(usedSize + " numbers entered.");
}
else if(!(usedSize < nums.length)) {
System.out.println("Maximum amount of inputs (" + nums.length + ") reached.");
}
return usedSize;
}
Here in the while loop, the statements
nums[usedSize] = userValue;
userValue = kbd.nextInt();
will ensure that the value at num[0] will always be zero(as userValue is initialised to 0) and it won't be fetched from user input.
Instead it should be:
while(userValue >= 0 && usedSize < nums.length) {
userValue = kbd.nextInt();
nums[usedSize] = userValue;
usedSize++;
}
If you take care of these two issues; then the rest of the code should work out fine.
This is what I get when I run the program after updating it for the second issue:
Input
Please enter each number starting from least to greatest(a negative number will quit input):
5
8
4
32
-5
Output
The smallest number entered is -5.
The largest number entered is 32.
The median is: 0.0
The average is: 4.4
Which is correct cause the average and median are calculated for 10 numbers and the rest of the numbers (after entering negative number) are just 0
Update as per comments
If you just wish to reject the negative number the you can update the while loop in getnums method as:
while(userValue >= 0 && usedSize < nums.length) {
userValue = kbd.nextInt();
if(userValue >= 0) {
nums[usedSize] = userValue;
usedSize++;
}
}
Also, the if loop after that shouldn't decrease the value of usedSize
if(!(userValue >= 0)) {
System.out.println(usedSize + " numbers entered.");
}
I am working on an assignment which prompts the user to input an integer, and displays that integer with the digits separated by spaces, and provides the sum of those digits. I have this working, but my individual digit display is form the last digit to the first. How can I make it display the digits from first to last?
Here is what I have so far:
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
System.out.print(" " + temp + " ");
}while (num > 0);
System.out.println("The sum of the digits = " + sum);
}
}
One option would be to use the String#valueOf(Integer) method.
Example
int input = 12345;
String inputStr = String.valueOf(input);
for(char c : inputStr.toCharArray()) {
// Print out each letter.
}
if you use the method String.valueOf(12345)
you can easily reverse the String with the method in this library:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverse(java.lang.String)
StringUtils.reverse(String.valueOf(input));
Here is the solution
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
ArrayList<Integer> values = new ArrayList<>();
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
values.add(temp);
}while (num > 0);
Collections.reverse(values);
Iterator<Integer> it = values.iterator();
while(it.hasNext()){
System.out.println(" "+it.next()+" ");
}
System.out.println("The sum of the digits = " + sum);
}
}
BTW you should have to import ArrayList etc.
I would highly recommend putting the number into a String and then reading it, parsing it, and use the number however you want. As follows,
int input = 12345;
String inputString = input + "";
int sum = 0;
for (int i = 0; i < inputString.length(); i++) {
sum += Integer.parseInt(inputString.charAt(i) + "");
}
System.out.println(sum);
However an alternative way, not as pretty is..
int input = 12345;
int sum = 0;
while (input > 0) {
int i = (input + "").length() - 1;
int n = (int) (input / Math.pow(10, i));
input -= (int) (n * Math.pow(10, i));
sum += n;
}
System.out.println(sum);