Here's the question:
Write a program that that reads ten integers into an array and
computes the sum of the array of values, except for the largest one.
(Hint: Find the difference between the sum and the largest value of the
array)
And this is the given sample that you have to achieve:
Please input 10 integers: 3 4 1 9 2 10 8 6 7 5
Sum without the max: 45
The program beneath is my personal attempt:
import java.util.Scanner;
public class SumWithoutMax {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please input 10 integers: ");
int [] x = new int [10];
for (int i = 0; i < x.length; i++) {
x[i] = in.nextInt();
}
int max = x[0];
int sum = 0-max;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
}
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
System.out.println("Sum without the max: " +sum);
}
}
And the result of my attempt is just like this:
Please input 10 integers: 3 4 1 9 2 10 8 6 7 5
Sum without the max: 52
What's wrong with the program actually? Can somebody help me find it out and teach me how to solve it? Thanks:)
Problem with your code is you are subtrating x[0] value (which assume max at initial).
Even You can achive the with single for-loop.
int max = x[0];
int sum = 0;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
sum = sum + x[i];
}
sum -=max;
You are subtracting the maximum before you know it. Move int sum = 0-max; after the loop that seeks it.
The first sum=0-max; is wrong because max is not known yet. You need to do it after you find the max.
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
sum -= max;
int sum = -max;
When loop find the maximum number.
Move this line:
int sum = -max;
after the loop that finds the max.
import java.util.Scanner;
public class SumWithoutMax {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please input 10 integers: ");
int [] x = new int [10];
for (int i = 0; i < x.length; i++) {
x[i] = in.nextInt();
}
int max = x[0];
int sum = 0;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
}
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
sum = sum - max;
System.out.println("Sum without the max: " +sum);
}
}
A possible answer in JAVA 8 :
Integer sum = Arrays.asList(3,4,1,9,2,10,8,6,7,5).stream().sorted(Comparator.reverseOrder()).skip(1).reduce(
0,(a, b) -> a + b);
Related
import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
for (int i = 1; i < size; i++)
for (int j = 0; j < size - i; j++)
if (nums[i] > nums[i + 1]) {
temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp;
}
System.out.print(nums[size - 1]);
}
}
Though it gets all the values for the array, it still doesn't print the max number which is the last num in the array.
The error I get for size=5:
Exception in thread "main": java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at maxnuminarray.main(maxnuminarray.java:15)
Once you read in the values, iterate over the array like this.
int max = Integer.MIN_VALUE;
for (int n : nums) {
max = Math.max(max, n);
}
You're trying to get a value with an index that doesn't exist. For instance, at if (nums[i] > nums[i + 1]). Let's say you have 3 numbers in total, your array size will be 3, but your index starts at 0.
Index 0
Index 1
Index 2
5
10
21
If you try to get i + 1 when i = 2 you get an error since i = 3 does not exist.
Also, if you're trying to get the largest number out of the array, you only need to go through the array once.
int[] nums = new int[]{1, 10, 3};
int max = nums[0];
for (int i = 1; i < nums.length; i++)
if (max < nums[i])
max = nums[i];
Or you can use Collections with the Integer[] array.
int max = Collections.max(Arrays.asList(num));
If you are just looking to find the maximum in the array, #Nouredine's code should do the trick.
Your code is comparing consecutive numbers one by one through the array, and swapping them in a bubble sort kind of way.
But if you are really looking to move the maximum in the array to the last position in the array, you can use this piece of code.
The issue in your code is you are accessing 5th index in an array of size 5, where only 0,1,2,3,4 are allowed.
for (int i = 1; i < size; i++)
if (nums[i - 1] > nums[i]) {
temp = nums[i - 1];
nums[i - 1] = nums[i];
nums[i] = temp;
}
}
import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
int max = nums[0];
for (int i = 1; i < size; i++)
if(max < nums[i])
max = nums[i];
}
System.out.println("Max " + max);
}
public class Bonus1{
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] numbers = new int[n];
for (int i = 0; i < n; i++ ) {
numbers[i] = i;
}
for (int i = 0; i < n; i++ ) {
int r = i + (int)(Math.random() * (n - i));
int tmp = numbers[i];
numbers[i] = numbers[r];
numbers[r] = tmp;
System.out.print(numbers[i]);
}
int min = Integer.MAX_VALUE;
int count = 0;
while(data.hasNext()){
int y = data.nextInt();
if(y < min){
min = y;
count += 1;
}
}
System.out.println(count);
}
}
this code isn't complete, the first 2 for-loops will generate an array between 0 to a given number in the commandline -1
So for example java Bonus1 10 would first generate an array between 0-9 and then it will shuffle these numbers around so that it creates a random permutation.
the while loop is something I've used before to read input and determine how many times a new lowest number is detected. so for example if I get the permutation 7 8 2 3 4 5 1 0 6 9 it will count 7 as the lowest, then 2 as the lowest and then 1 as the lowest and finally 0 as the lowest, making the total amount of times a new lowest number has been detected 4.
but this only works if I use inputs, I need to use the previously generated output as the input in the same file, is there a clever way to do that?
You should iterate for the array numbers like this.
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = i;
}
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = numbers[i];
numbers[i] = numbers[r];
numbers[r] = tmp;
System.out.print(numbers[i]);
}
System.out.println();
int min = Integer.MAX_VALUE;
int count = 0;
for (int i = 0; i < n; ++i) {
int y = numbers[i];
if (y < min) {
min = y;
++count;
}
}
System.out.println(count);
}
output:
6457098123
3
Hi in my program I want to display the average number, largest number, lowest number, and the mode in the array. So far only my average works and my methods for min and max both = the first number I enter. For example if I say I want to enter 3 numbers and I put 12, 15,and 6. The min and max will both output 12 since it's the first number entered and that's wrong so please help. Here's my code.
int amount;
System.out.println(" Enter the amount of numbers you would like to enter: ");
amount = scan.nextInt();
int [] arr = new int [amount];
int outcome = 1;
for (int i = 0; i < arr.length; i++){
System.out.println("Enter a number 1 through 50");
outcome = scan.nextInt();
arr [i] = outcome;
}
System.out.println(" ");
System.out.println( " The average is" );
System.out.println(average(arr));
System.out.println(" ");
System.out.println( " The lowest value in the array is " );
System.out.println(min(arr));
System.out.println(" ");
System.out.println( " The largest value in the array is " );
System.out.println(max(arr));
System.out.println(" ");
}
public static double average ( int [] arr) {
double sum = 0;
int value = arr.length;
for ( int i = 0; i < arr.length; i++){
sum += arr [i];
}
sum = sum / value;
return sum;
}
public static int min (int [] arr) {
int shortest = 0;
int smallest = 100;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length < smallest)
shortest += arr[i];
smallest = arr.length;
}
return shortest;
}
public static int max (int [] arr) {
int largest = 0;
int biggest = 0;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length > largest)
biggest += arr[i];
largest = arr.length;
}
return biggest;
}
}
This would be pretty straightforward. The reason both your min and max methods return 12 is because you set both largest and smallest to arr.length and thus immediately stop the for-loop after only one run. Also, there are far easier implementations for this kind of problem. Try doing something along these lines:
public int getMax(int[] arr)
{
int max = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
return max;
}
public int getMin(int[] arr)
{
int min = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < min)
{
min = arr[i];
}
}
return min;
}
This is both far more readable and easier to execute. Just ask if you have any questions :-)
What did I do wrong? I'm really not sure what else to try or where my mistake is. Thanks for any help. It's supposed to calculate the sum of integers between two numbers, e.g. between 3 and 6 it would be 3 + 4 + 5 + 6
import java.util.Scanner;
public class TheSumBetweenTwoNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("First:");
int n = Integer.parseInt(reader.nextLine());
System.out.println("Second:");
int max = Integer.parseInt(reader.nextLine());
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
System.out.println("Sum is " + sum);
}
}
Why all this you need just a piece of code like this :
public static void main(String args[]) {
int min = 3, max = 6, sum = 0;
for (int i = min; i <= max; i++) {
sum += i;
}
System.out.println(sum);
}
With while loop it should be :
...
int i = min;
while (i <= max) {
sum += i;
i++;
}
...
You don't need to find a difference and loop over it, just running a loop from n to max will do. Also, you need to add the value to sum (+=) instead of assigning a value to it (=, which overwrites previous value)
Try this:
int i = n;
while (i <= max) {
sum += i;
i++;
}
You're overwriting the previous sum value with the most recent n + (n + 1), instead of accumulating the previous sum. Also, your loop is one iteration short. Try this:
int sum = 0;
for (int i = n; i <= max; i++) {
sum += i;
}
System.out.println("Sum is " + sum);
Change this snippet
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
In
int sum = 0;
int i = n;
while (i <= max) {
sum = sum + i;
i++;
}
You made it a little bit overcomplicated. All you really need is a for loop that runs from n to max that adds up the incrementing variables:
int sum = 0;
for(int i = n; i <= max; i++){
sum += i;
}
In the following Java code, my average temperature is 1 decimal place off.
For example Instead of being 69.0 it's 6.9.
The input can be any 10 numbers. So lets say I input 10 temperatures and each 1 is 10 degrees. The total for the 10 inputs is 100, so the average should be 10 but instead I'm receiving an average of 1.0.
Code:
import java.util.Scanner;
public class NumberAboveAverage {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int TotalTemps = 10;
double[] numbers = new double[TotalTemps];
double sum = 0;
double average = 0;
double max = 0;
for (int n = 0; n < numbers.length; n++) {
System.out.print("Enter a temperature: ");
numbers[n] = input.nextInt();
if (numbers[n] > max) {
max = numbers[n];
}
sum = numbers[n];
}
for (int i = 0; i < numbers.length; i++) {
sum = numbers[i];
}
average = sum / 10; //average is not an average of the numbers.
System.out.println("Average temp = " + average);
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > average) {
count++;
}
}
System.out.println(count + " days were above average");
}
}
You're not actually summing the numbers together.
It should be sum += numbers[i];
not sum = numbers[i];
You also appear to be attempting to do this twice, which is unnecessary.
You are missing a +
sum = numbers[n];
needs to be
sum += numbers[n];
This does nothing,
for (int i = 0; i < numbers.length; i++) {
sum = numbers[i];
}
You sum twice (second for-loop) and do it wrongly with: sum = numbers[n]; instead of: sum += numbers[n];
You should change your code to:
...
for (int n = 0; n < numbers.length; n++) {
System.out.print("Enter a temperature: ");
numbers[n] = input.nextInt();
if (numbers[n] > max) {
max = numbers[n];
}
sum += numbers[n];
}
// SECOND FOR LOOP REMOVED !!!
average = sum / 10;
System.out.println("Average temp = " + average);
...
Replace
average = sum / 10;
with
average = sum / 10.0;