Minimum value in array java - java

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

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

Generating random number sequences & sorting them out in java

Good day,
I am currently working on this program, which has to generate as many numbers as I enter (between 1-100) and the number has to be in the range of 0 - 1 000 000.
Then, the program must print them out in a random order and after that using the insertion sort, it must sort the randomly generated numbers.
I've been tackling this for about 7 hours now, searched online for answers, but haven't found anything yet. I was hoping to get a fix for my problem here!
What the program is supposed to do:
Person enters how many random numbers they want the program to generate (between 1-100)
Print out the amount of random numbers (random numbers must must be in the range of 0 - 1 000 000), the person entered before.
Sort the numbers using insertion sorting and print them out.
This is what I currently have:
It doesn't print out the sorted list.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the amount:");
int amount = scan.nextInt();
int []numbers = new int[amount];
Random rand = new Random();
System.out.println("Random order:");
int MAX = 1000000;
int MIN = 0;
for (int i = 0; i < amount; i++) {
numbers[i] = rand.nextInt(MAX - MIN + 1) + MIN;
System.out.print(numbers[i] + ", ");
}
System.out.println("");
System.out.print("From smallest to biggest:");
sort(numbers);
}
public static int[] sort(int[] list) {
int i, j, key, temp;
for(i = 1; i < list.length; i++) {
key = list[i];
j = i-1;
while (j >= 0 && list[j] > key) {
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
j--;
}
System.out.print(list);
}
return list;
}
}
I think u forgot to call the sort method.

Smallest number in array

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.

Create an array based on a range of values given by the user

What I'm trying to do is create an array based on values given by the user. The user has to give the length of the array plus the max and min values. I've managed to get the program to the point where it does output the correct amount of values (the correct length), but it just keeps outputting the exact same number (which is the max and min added). Based on research I did I tried converting them to a string so that wouldn't happen, but it still isn't working correctly. I've tried a couple of different methods including: Integer.toString, String.valueOf, and creating a whole new string. Any help would be greatly appreciated. Here's the code so far:
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum / data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Now, after I added that bit with the average calculation, the program did work once, though it did not compute the average (so it just created an array with min and max at the ends, sorted). It appears to be a fluke, because this is the exact same code and it hasn't done that since. Though maybe the average code somehow affected the rest?
If I understood you problem correctly, you need to change this line
System.out.println(min + userArray[i] + max);
to this:
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
My guess is, that it is java you are using. That tag would be helpful, too.
Edit:
You only need to sort your array once, and these do nothing: Integer.toString(min);
So the print routine could look like this:
selectionSort(userArray);
for (int i = 0; i < userArray.length; i++) {
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
}

Min value of array returns as 0

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.

Categories