I am trying to find the largest number in an array of 10 numbers. Here is my code:
public static void getNumber() {
int NumbersArray[] = new int[11];
int num1;
int num2;
int largestNumber = 0;
Scanner scanner = new Scanner(System.in);
for(int i=1; i<11; i++){
System.out.println("Enter number " + i );
int no1 = scanner.nextInt();
NumbersArray[i] = no1;
}
scanner.close();
for(int i=1; i<11; i++)
{
System.out.println(NumbersArray[i]);
num1 = NumbersArray[i];
for(int j=10; j>0; j--)
{
num2 = NumbersArray[j];
if(num1>num2){
largestNumber = num1;
}
}
}
System.out.println("the largest number is " + largestNumber);
}
I found a real simple soultion to this here.
But the reason I am posting this is to find out what mistake have I made.
The first portion gets 10 numbers from the users and the second portion is my code to find the largest number.
Going off Pshemo's suggestion, keep a record of the largest int as the user is typing. This reduces the size of your method by half and makes it much simpler and more readable.
Program with 0-based indexing. So use int NumbersArray[] = new int[10] instead of int NumbersArray[] = new int[11]. When you declare the size of your array, simply put your desired size, you don't have to worry about 0 indexing or anything. For your for-loop, start at int i=0 and end at i<10.
public static void getNumber(){
int NumbersArray[] = new int[10];
int largestNumber = 0;
Scanner scanner = new Scanner(System.in);
for(int i=0; i<10; i++){
System.out.println("Enter number " + i );
int no1 = scanner.nextInt();
NumbersArray[i] = no1;
if(no1 > largestNumber)
largestNumber = no1;
}
scanner.close();
System.out.println("The largest number is: " + largestNumber);
}
The problem is that you are iterating through the list twice (in a nested way). Let's say you have the following numbers: [5, 7, 3, 4]. As you go through the inner loop the first time you'll end up comparing numbers against 5. Only 7 is larger so largestNumber will be set to 7. Then you'll go through again, this time comparing against 7. Nothing is larger than 7, so it'll be left alone. Next you'll compare against 3. The last comparison there is 3 vs. 4, and since 4 is larger you end up setting largestNumber to 4, which is incorrect.
These lines:
for(int i=1; i<11; i++)
{
System.out.println(NumbersArray[i]);
num1 = NumbersArray[i];
for(int j=10; j>0; j--)
{
num2 = NumbersArray[j];
if(num1>num2){
largestNumber = num1;
}
}
}
Don't search for the largest number in the array, but simply search for any value in NumbersArray a value that is bigger than the current element. Thus largestNumber isn't the largest number in the array, but the last number in NumbersArray that is larger than the last element of NumbersArray, unless the last element of NumbersArray is the biggest element, in this case the largestNumber will be the last value in NumbersArray.
A working solution would be:
int max = Integer.MIN_VALUE;
for(int i : NumbersArray)
if(max < i)
max = i;
Though the most efficient solution would be to directly keep track of the currently largest input while reading the input.
And keep in mind that java-arrays are 0-based. This means that the first element is at NumbersArray[0], not NumbersArray[1], like in your code.
As far as I know you can use Java Math max() method to get largest number.
i.e. : dataType max(int number1, int number2), Math.max(number1, number2) gets the maximum between number 1 and 2.
Related
Hi I'm having trouble subtracting one array element to the next element to get the correct answer. The value of the array are given by the user.
Example:
If the user wants to input 3 numbers which are 10, 8, 1
10-8-1 = 1
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
for(int t =0; t<number.length-1; t++)
{
total = number[t] - number[t+1];
}
System.out.println("total: " + total);
Change the 2nd loop to this:
total = number[0];
for (int i=1; i<number.length; i++) {
total -= number[i];
}
You want to subtract the remaining array items from the first one. Therefore total in the beginning should be equal to the first item and in the loop subtract each consequent (start from the index 1) item from the total.
Remember the number of items in the array must be equal to or larger than 2.
this line is totally wrong : total = number[t] - number[t+1]; as in the last loop
total = number[1] - number[2] which will be equivalent to total = 8 - 1 = 7 which is totally wrong because you have to accumulate the total variable .
so as mentioned above the full correct answer code is :
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
total = number[0];
for (int i=1; i<number.length; i++) {
total = total - number[i];
}
System.out.println("total: " + total);
}
}
and here is image of the output:
[][1]
Here is a one liner (computation wise) using streams. Take the first element, stream the array skipping the first element and subtract the sum of the remaining.
int[] arr = { 10, 8, 3, 1 };
int sum = arr[0] - IntStream.of(arr).skip(1).sum();
System.out.println(sum);
But no matter how you do it, you have the potential for int overflow or underflow depending on the size of your values and the length of the array.
I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}
When I try to sort the array, the result that I get is:
The sorted array is [0, 0, 0, 0, 0, 0, 0, 0]
The user fills the array with 8 numbers that should be eventually sorted. But what I'm getting is a bunch of 0s.
Why am I getting 0s?
import java.util.Scanner;
import java.util.Arrays;
public class SortArray {
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int[] numbers = new int[8];
for(int i = 0; i < numbers.length; i++)
{
System.out.println("Enter the number for index " + i);
int number = kbd.nextInt();
}
for(int i = 0; i < numbers.length; i++)
for(int j = 1; j < numbers.length; j++)
{
if (numbers[i] > numbers[j])
{
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
System.out.println("The sorted array is " + Arrays.toString(numbers));
}
}
You are not assigning the user inputs to your array, which is why all the elements remain 0.
change
int number = kbd.nextInt();
to
numbers[i] = kbd.nextInt();
The issue is within these lines of code:
for(int i = 0; i < numbers.length; i++)
{
System.out.println("Enter the number for index " + i);
int number = kbd.nextInt();
}
Specifically int number = kbd.nextInt();
To add a little bit of explanation to Eran's answer, what you did in that line above is create a new variable number, and assign the value you get from the Scanner kbd. As you declare an int (meaning you write int on the left hand side) you're creating a variable that will hold an int value.
The main issue here is that right after you assign it to a variable called number, your loop closes and the variable is not used at all. It gets destroyed/removed/garbage-collected and the value is released. Next time you come around that loop again, a new variable called number is once again assigned with that value from the scanner.
Also notice now number and numbers are of different types, numbers is an array of ints, while number is just an int.
By changing int number to numbers[i], you're telling Java to assign the int received from the scanner kbd to the array numbers at position i. That way you don't lose the value and it gets saved inside the array, which is why when you print the array you no longer get all 0s. (the reason why you previously got all zeros is because you initialized an array of ints, but never given them values, so Java defaults to 0.
I have to save 10 numbers entered by a user into an array using a for loop. After that, I have to use an enhanced for loop to find the largest and smallest values in the array. I don't know how to save numbers in an array. I also have problems finding the smallest and largest values from the array and displaying them. I got an error on the for loop section where I set highestvalue and lowestvalue=inputnumber.
Here is my code:
import java.util.Scanner;
public class ArrayTester
{
public static void main(String[] args)
{
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[inputNumber] = inputNumber;
//for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
//{
//largestNumber=inputNumber;
//smallestNumber=inputNumber;
//}
}
System.out.printf("%s%8s\n", "index", "value");
System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
}
}
Replace
number[inputNumber] = inputNumber;
with
number[counter] = inputNumber;
and thats it. As for finding mix and max, use Collections.sort() on your array. First element will be min, and the last max.
Change
number[inputNumber] = inputNumber;
to
number[counter] = inputNumber;
You want to add each new number to the counter position of the array.
As for finding the minimum, maximum. The same loop that reads the inputs into the array can do that. Initialize largestNumber to Integer.MIN_VALUE and smallestNumber to Integer.MAX_VALUE. Then, each time you get a new number, compare it to both largestNumber and smallestNumber, and update them if the new number is higher/lower respectively.
assuming that you don't have to store the numbers in the same order in which they were entered by the user, you would make a sorted insert. that means, for each value entered, find the index at which this number can be inserted while maintaining a sorted array (if there exists a number at this index you have to move it move it to the right)
provided a sorted array you can find min and max in O(1):
min = number[0];
max = number[n-1];
make the following changes
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber ;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[counter] = inputNumber;
// for loop that will check for largest and smallest no
}
smallestNumber = number[0];
largestNumber = number[0];
for(int i=1; i< number.length; i++)
{
if(number[i] > largestNumber)
largestNumber = number[i];
else if (number[i] < smallestNumber)
smallestNumber = number[i];
}
// System.out.printf("%s%8s\n", "index", "value");
// System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
Also: you cannot use a for loop in this way
for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
this is a conditional case not a loop
I would suggest you to try out this one.Let me know if it works.:-
import java.util.Scanner;
public class Practice {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int num[]=new int[10];
int max=0,min=0;
for(int i=0;i<10;i++){
System.out.println("Enter number:-");
num[i]=in.nextInt();
if(num[i]>=max)
max=num[i];
if(num[i]<=min)
min=num[i];
}
min=num[0];
for(int i=0;i<10;i++){
if(num[i]<=min)
min=num[i];
}
System.out.println("The array elements are:-");
for(int i=0;i<10;i++)
System.out.print(num[i]+" ");
System.out.println();
System.out.println("Largest is:-"+max+" "+"Smallest is:"+min);
}
}
I am trying to find the two smallest numbers in a set WITHOUT USING ARRAYS. Here is the code:
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int min = in.nextInt();
for(int i = 1; i < N; i++){
int a = in.nextInt();
if(a < min){
min = a;
}
}
System.out.println(min);
It find the smallest number but there is nothing about the second smallest number.
How do I do that?
Please, note that I am a complete beginner to Java so easy explanation and help will be much appreciated)
It´s very very easy:
Scanner in= new Scanner(System.in);
int N = in.nextInt();
int min,min2 = Integer.MAX_VALUE,Integer.MAX_VALUE;
for(int i = 0; i < N; i++){
int a = in.nextInt();
if( a < min){
min = a;
min2 = min;
}
else if( a < min2){
min2 = a;
}
}
System.out.println(min);
System.out.println(min2);
It is about one condition you have to add:
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int min = Integer.MAX_VALUE;
int secondMin = Integer.MAX_VALUE;
for(int i = 0; i < N; i++){
int a = in.nextInt();
if(a < min){
secondMin = min; // the current minimum must be the second smallest
min = a; // allocates the new minimum
}
else if (a < secondMin) {
secondMin = a; // if we did not get a new minimum, it may still be the second smallest number
}
}
System.out.println(min);
System.out.println(secondMin);
General hint: You should call the close method of your Scanner, preferably in a try-with-ressources block:
try(Scanner in = new Scanner(System.in)) {
// other code here
}
That way the stream gets closed, which you should do, if you open a stream.
Solution 1:
The easiest way, that uses your existing code, would be also tracking the second smallest number:
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int min = in.nextInt();
int sMin = Integer.MAX_VALUE;
for(int i = 1; i < N; i++){
int a = in.nextInt();
if(a < min){
sMin = min;
min = a;
} else if(a < sMin) {
sMin = a;
}
}
System.out.println(min);
System.out.println(sMin);
Explanation 1:
The two cases, that can occure with a new Value are:
The new value is smaller than min and sMin. Then you have to set the value of min into smin and afterwards set min to the new min value.
The new value is larger than min and smaller than sMin. Then you only have to set the value of sMin to the new value.
Both min-values are smaller. Then nothing is to do.
Solution 2:
Another, more generic approach would be using a PriorityQueue:
int N = in.nextInt();
PriorityQueue<Integer> minQueue = new PriorityQueue<>();
for(int i = 0; i < N; i++) {
int value = in.nextInt();
minQueue.add(value);
}
int minValue = minQueue.poll();
int secondMinValue = minQueue.poll();
This way you can get the n smallest numbers given by using a loop in which you call the poll() method. (n may be a number < N).
Explanation 2:
The Priority Queue is a datastructure, that internally orders the given elements by the natural order. In the case of Integers this order is given by <,> and =. So when calling poll() you remove the smallest element, that the PriorityQueue has yet encountered.
Try this:
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int min2 = in.nextInt();
int min1 = min2;
for(int i = 1; i < n; i++){
int a = in.nextInt();
if( a < min2){
if(a < min1){
min2 = min1;
min1 = a;
}
else{
min2 = a;
}
}
}
System.out.println(min1 + " " + min2);
This problem can be solved in multiple ways, and the first step in choosing the right solution is to decide what is the most important for you:
Space efficiency, that is, use the minimum possible amount of storage. ThreeFx does this, (s)he only uses constant additional space for the variables N, a, min, and secondMin. "Constant space" means that the amount of data that you store does not depend on how many numbers you are going to read from the stream. In contrast, Tarlen uses linear space, storing all the numbers read from the stream. This means that the amount of space required is directly proportional to N instead of being constant.
Time efficiency, that is, perform as few computations as possible. I believe that ThreeFx's solution is one of the most efficient from this point of view. Tarlen's solution will be a bit slower, because managing the priority queue might require more comparisons.
Extensibility, that is, how easily you could adapt your code when the requirements change slightly. Say that your boss makes you solve the problem that you just posted, to find the two smallest numbers. The next day, he wants the first three, and so on, until the end of the week. You get tired of changing your code every day, so you write a general solution, that will work for any number of elements that he asks for. This is where Tarlen's solution is better.
Readability, that is, how short and easy to understand your code is. I will introduce my own solution here, which is based on a simple idea: put all the numbers in a list, sort it, and take out the first two numbers. Note that this is quite wasteful when it comes to resources: the space is linear (I am storing N numbers), and the time efficiency is O(N log N) at best. Here is my code:
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < N; i++) list.add(in.nextInt());
Collections.sort(list);
System.out.println(list.get(0));
System.out.println(list.get(1));