How do I find the smallest number in an array? The problem with my code is it always print out 0 as the smallest number.
here's my code:
import java.util.Scanner;
public class Exercise1 {
public static void main (String [] args){
Scanner kb = new Scanner(System.in);
System.out.print("Please type the total number of marks: ");
int SIZE = kb.nextInt();
double [] marks = new double [SIZE];
double smallest = marks [0];
for (int i=0;i<SIZE;i++){
System.out.print("Enter the mark: ");
marks[i]=kb.nextDouble();
if(marks[i] < smallest) {
smallest = marks[i];
}
}
System.out.println("The lowest number is " + smallest);
}
}
Because you create fixed size array. So when you assign smallest, all the item in your array is 0, so it will be 0.
You should change your code to:
double smallest;
for (int i = 0; i < SIZE; i++) {
System.out.print("Enter the mark: ");
marks[i] = kb.nextDouble();
if (i == 0) {
smallest = marks[0];
}
if (marks[i] < smallest) {
smallest = marks[i];
}
}
Your array doesn't have anything in it. Fill the array with valid values and try it again and see what happens. In Java, arrays consisting of doubles are initialized according to this spec, so your whole array currently contains values of 0.0d.
Related
This question already has answers here:
How to find the index of an element in an int array?
(19 answers)
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
This program takes ten user-input integers, and stores them into an array. It is supposed to find the largest value, and find the index of the value. Currently, it finds the largest value.
However, I'm not sure how to make it find the index of that value. I feel like I may be over-complicating a simple solution. Any help or advice would be appreciated, thank you!
public static void main(String[] args) {
int[] numbers;
numbers = new int[10];
int largest = numbers[0];
int counter;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter 10 numbers: ");
for (counter = 0; counter < numbers.length; counter++) {
numbers[counter] = keyboard.nextInt();
}
for (int i : numbers) {
if (i > largest) {
largest = i;
}
}
System.out.print("The largest number is: " + largest);
System.out.println(" ");
System.out.print("That number is stored at index " + );
}
}
Track largest and its position simultaneously
public static void main(String[] args) {
int[] numbers;
numbers = new int[10];
int largest = numbers[0];
int largest_i = 0;
int counter;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter 10 numbers: ");
for (counter = 0; counter < numbers.length; counter++) {
numbers[counter] = keyboard.nextInt();
if (numbers[counter] >= largest) {
largest = numbers[counter];
largest_i = counter;
}
}
System.out.print("The largest number is: " + largest);
System.out.println(" ");
System.out.print("That number is stored at index " + );
}
}
You can probably create a variable called 'largestIndex' to store the index value.
Rather than using a foreach loop, use a for loop which iterates from 0 to numbers.length and each time you find a number bigger than 'largest' update the largestIndex variable.
So I need some help and maybe you guys can check my code and see why it isn't working and what I'm missing.
Here is the code:
import java.util.Scanner;
public class min;
public static void main(string[] args) {
Scanner input = new Scanner(System.in);
double[] list = new double[4];
double min = list[0];
System.out.print("Enter " + list.length + " numbers: ");
for (int i = 0; i < list.length; i++) {
list[i] = input.nextDouble();
if (list[i] < min) {
min = list[i];
}
}
System.out.println(min);
}
}
So, why does it bring back 0.0 when I have the greater than facing min?
When I flip the sign around it works and brings back the greatest number, when I put out a list of numbers it works both min and max, just not for minimum input.
You could also just initialize min as input.nextDouble after the user input, and change your for loop to start at 1
I'm trying to get both, the largest number and the largest occurring number, from a user input. The problem with my code is it only returns the first value of the array.
public class CountMax {
public static void main(String [] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Obtain user input
System.out.println("Enter numbers: ");
int num = input.nextInt();
int array[] = new int[num];
//loop through array
int max = array[0];
int count = 1;
for (int i = 0; i < array.length; i++) {
array[i] = num;
if(array[i] > max) {
max = array[i];
count = 1;
} else if(array[i] == max) {
count++;
}
}
//output results
System.out.println("The largest number is " + max);
System.out.println("The occurrence count of the largest number is " + count);
}}
I know this post is old, but Wyatt Lowery's solution is incorrect, just in case someones stumbles upon it from Google just like I did. You cannot count the number of max values in an array in the same loop like that until you have found the max value.
Example using Wyatt's class: 2 is obviously an incorrect answer.
Enter numbers:
1, 2, 3, 4, 5, 5, 7
The largest number is 7
The occurrence count of the largest number is 2
I would do:
int max = array[0];
int sum = 0;
for(int i = 1; i < array.length; i++) {
if(array[i] > max) max = array[i];
}
for(int i = 0; i < array.length; i++) {
if(array[i]==max) sum++;
}
One problem I noticed:
int num = input.nextInt();
When you do this, it is only going to take the first int (Meaning, only 1 number) As well when you are creating your array int array[] = new int[num], you are creating an array with the SIZE of num, and not actually creating an array with the VALUES of num. (Even though num is only a single number) To actually create an array of numbers, do something like this:
System.out.pritnln("Enter in numbers:");
String[] array = input.nextLine().split(", ");
An example input would be: "13, 12, 14, 14". Then the contents of the array would be those terms (And would remove spaces & commas). Your program should look something like this when finished:
public class CountMax {
public static void main(String [] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Obtain user input
System.out.println("Enter numbers: ");
String[] array = input.nextLine().split(", ");
//Loop through array
int max = Integer.parseInt(array[0]);
int count = 0;
for (int i = 0; i < array.length; i++) {
if(Integer.parseInt(array[i]) > max) {
max = Integer.parseInt(array[i]);
} else if(Integer.parseInt(array[i]) == max) {
count++;
}
}
//Output
System.out.println("The largest number is " + max);
System.out.println("The occurrence count of the largest number is " + count);
}
}
Hope this helped :-)
Think more carefully about each step you need to take.
Do you know how many numbers will be entered by the user?
Right now you are only taking in one number because you are not looping on the input
int num = input.nextInt();
int array[] = new int[num];
Here, you are creating an array the size of whatever number the user entered. This is a correct approach, more typical of C, if the user will tell you "I will enter 10 numbers" and then enters the 10 numbers. This is convenient because you will know to loop 10 times, and you will need to count a maximum of 10 different numbers.
If we don't know how many numbers will be entered you will need to loop until EOF.. something like
while(input.hasNext()) {
int currentInt = input.next();
...
}
Now you have to consider how you will be counting these items.
I hope this gives you some things to think about towards your solution..
I'm having problems figuring out why returns for my minimum value in my array keep ending up as 0. I've checked several questions with the same problem but can't use those solutions because my array is being created in one method and my min/max values are calculated in another method.
Is there anyway I can keep my min/max value in a separate method and still get a non-zero answer for my min value? Also, there is more code in the processSalesReport method but I left it out because it was irrelevant. Thanks ahead of time!
import java.util.Arrays;
import java.util.Scanner;
public class CarSalesReport {
int sum;
int count = 0;
int[] num = new int[1500];
String ans = "";
Scanner userInput = new Scanner(System.in);
public CarSalesReport(Scanner input) {
String regex = "\\d+|done";
System.out.println("Type sales (type \"done\" when finished)");
do{
System.out.print("Sale Number " + (count + 1) + ": ");
ans = userInput.nextLine();
while(!ans.matches(regex)){
System.out.println("Please enter a positive number");
ans = userInput.nextLine();
}
if(!ans.equalsIgnoreCase("done")){
int ans1 = Integer.parseInt(ans);
num[count] = ans1;
count++;
}
}while(!ans.equalsIgnoreCase("done"));
}
public void processSalesReport(){
int max = num[0];
for(int a=0;a<num.length;a++){
if(max<num[a]){
max=num[a];
}
}
//This is where I'm having my problems.
int min = Integer.MAX_VALUE;
for(int a=1;a<num.length;a++){
if(min>num[a]){
min=num[a];
}
}
Arrays.sort(num);
System.out.println("\nMaximum sale: $" + max);
System.out.println("\nMinimum sale: $" + min);
}
}
It's because you've got 1500 entries in your array, which are all initialised to 0. You're iterating through all of them trying to find the minimum, instead of just iterating through the ones you've explicitly populated.
In the loop where you calculate the minimum, change
for (int a = 1; a < num.length; a++) {
to
for (int a = 0; a < count; a++) {
so that you only look at the entries that you've populated.
I am in a beginner Java class and just learning the concept of arrays. We have to use comments to denote the code.
I am trying to make a program that asks the user to enter 20 numbers, stores them in an array and then calculates and displays: the lowest number, the highest number, the total of the numbers and the average of the numbers.
I have a ton of errors when running it through jGrasp and am unsure how to fix them.
Any advice?
public class NumberAnalysisProgram
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
//A constant for the array size
final int SIZE = 20;
//Declare an array to hold the numbers entered by the user
int[] numbers = new int[SIZE];
//Declare variables to hold the lowest and highest
int lowest = numbers[0];
int highest = numbers[0];
//Declare variable to hold the total
int sum;
//Declare a variable to hold the average
double average;
//Declare a counting variable to use in the loops
int index = 0;
//Explain the program
System.out.println("This program gets a list of 20 numbers. Then displays:");
System.out.println(" the lowest number, the highest number, the total of the numbers,
and the average.");
//Get the numbers from the user
for (int i = 0; i< numbers.length; i++)
{
System.out.print("Please enter 20 numbers, each seperated by a space: ");
numbers[i] = input.nextInt();
}
//Call a method to calculate the lowest and highest numbers
getLowHigh(numbers);
//Display the lowest and highest numbers
System.out.println("The lowest number is: " + lowest);
System.out.println("The highest number is: " + highest);
//Call a method to calculate the total of the numbers
sum = getTotal(numbers);
//Display the sum/total of the numbers
System.out.println("The total of these numbers are: " + sum);
//Call a method to calculate the average of the numbers
average = getAverage(sum, numbers);
//Display the average of the numbers
System.out.println("The average of these numbers are: " + average);
}
//Method getLowHigh
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
//Method getTotal
public static int getTotal(int[] array)
{
//Loop counter variable
int index;
//Accumulator variable initialized to 0
int total = 0;
//Pull in the numbers from the main method to calculate the total
for(index = 0; index < numbers.length; index++)
{
total = total + number[index];
}
return total;
}
//Method getAverage
public static int getAverage(int[] array)
{
//Loop counter variable
int index;
//Pull in the sum and the numbers from the main method to calculate the average
for(index = 0; index < numbers.length; index++)
{
average = sum / number[index];
}
return average;
}
}
The first problem I can see is that in all of the methods, you never used the arguments. You used a different array, which doesn't exist within those methods.
The second problem is that you're trying to return two values from one method. You can only return one value from a method. So you have to get rid of "return highest;" and make a copy of the method in which there is no "return lowest;", and use each where needed.
The third thing I see (although it isn't causing any errors) is that you could shorten the code by saying
int total = 0;
for(int index = 0; index < numbers.length; index++)
{
total += number[index];
}
instead of
int index;
int total = 0;
for(index = 0; index < numbers.length; index++)
{
total = total + number[index];
}
For starters, the below code is trying to initialize variables to array values that don't exist… These should be removed entirely.
//Declare variables to hold the lowest and highest
int lowest = numbers[0];
int highest = numbers[0];
There will also be an error with these in the code below because you're not passing them to the function therefore it doesn't exist within this scope.
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
You are also supplying 2 parameters for a function that only calls for one. See below:
//Call a method to calculate the average of the numbers
average = getAverage(sum, numbers);
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
I think that this is more clean:
public class Main {
public static final int SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
Double total = 0d;
System.out.println("This program gets a list of 20 numbers. Then displays:");
System.out.println(" the lowest number, the highest number, the total of the numbers, and the average.");
// Get the numbers from the user
System.out.print("Please enter 20 numbers, each seperated by a space: ");
for (int i = 0; i < SIZE; i++) {
Integer currInput = input.nextInt();
numbers.add(currInput);
total += currInput;
}
System.out.println("The lowest number is: " + Collections.min(numbers));
System.out.println("The highest number is: " + Collections.max(numbers));
System.out.println("The total of these numbers are: " + total);
System.out.println("The average of these numbers are: " + (total / SIZE));
}
}
Hope it helps :]