Finding the index of an array value [duplicate] - java

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.

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.

About saving and printing distinct numbers in an array

before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.
package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[10];
int d = 0;
System.out.println("Enter Ten Numbers: ");
for(int i = 0; i < numArray.length; i++){
int num = input.nextInt();
if(inArray(numArray,num,numArray.length)){
numArray[i] = num;
d++;
}
}
System.out.println("The number of distinct numbers is " + d);
System.out.print("The distinct numbers are: ");
for(int i = 0; i < d; i++){
System.out.print(numArray[i] + " ");
}
}
public static boolean inArray(int[] array, int searchval, int numvals){
for (int i =0; i < numvals; i++){
if (searchval == array[i]) return false;
}
return true;
}
}
You can use a set to identify distinct values:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> distinctNumbers = new LinkedHashSet<>();
System.out.println("Enter ten Numbers: ");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
distinctNumbers.add(number);
}
System.out.println("The number of distinct numbers is " + distinctNumbers.size());
System.out.print("The distinct numbers are: ");
for (Integer number : distinctNumbers){
System.out.print(number + " ");
}
}
If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.
Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.

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.

How to return the Max Value and Max Count from a user input

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..

Categories