Java find lowest number messes up when inputting negative numbers - java

I have to find the lowest number in an array. It works when I manually make an array, but when I use a scanner to get numbers from the user and they put in a negative number, it does not consider the negative sign and acts as if the number is a positive number. Is there something scan.nextInt does to negative numbers that causes this?
System.out.println("Enter an array size.");
size = scan.nextInt();
int[] numbers = new int[size];
System.out.println("Enter each integer in the array and press Enter after each one.");
for(int i = 0; i < size; i++)
{
numbers[i] = scan.nextInt();
}
for(int j = 0; j < size; j++)
{
smallest = numbers[0];
if (numbers[j] < smallest)
{
smallest = numbers[j];
}
}
System.out.println("Smallest Number is " + smallest);
This is the code for reference

You reset the smallest variable every loop.
Try initializing it before the loop.
smallest = numbers[0];
for(int j = 0; j < size; j++)
{
if (numbers[j] < smallest)
{
smallest = numbers[j];
}
}

You have to initialize your smallest out of the loop, preferably at the beginning. And if you are going to find the smallest, assign it a big value (if largest, assign a very small value);
int smallest = Integer.MAX_VALUE;
Integer.MAX_VALUE is the greatest possible value that you can assign to an integer in Java.
And always remember to release the resources. You have to close the scanner object when you're done with it.
scan.close(); // always release resources
Here is the demo code;
Demo Code
import java.util.Scanner;
public class FindLowest {
public static void main(String[] args) {
// initialization of variables
int size;
Scanner scan = new Scanner(System.in);
int smallest = Integer.MAX_VALUE;
System.out.println("Enter an array size.");
size = scan.nextInt();
int[] numbers = new int[size];
System.out.println("Enter each integer in the array and press Enter after each one.");
for (int i = 0; i < size; i++) {
numbers[i] = scan.nextInt();
}
scan.close(); // always release resources
for (int j = 0; j < size; j++) {
// smallest = numbers[0]; // dont initialize here, initialize at beginning
if (numbers[j] < smallest) {
smallest = numbers[j];
}
}
System.out.println("Smallest Number is " + smallest);
}
}
Output Sample
Enter an array size.
5
Enter each integer in the array and press Enter after each one.
1
-2
3
-4
5
Smallest Number is -4

Related

How can I find the lowest and highest number in 2d array?

package HighLow;
import javax.swing.JOptionPane;
public class HighLow {
public static void main (String[]args) {
int [][] arr= new int[3][4];
int smallest=arr[0][0];
int largest= arr[0][0];
int i = 0;
int j = 0;
{
arr[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Please enter 12 numbers: "));
{
if (arr[i][j] < smallest) {
smallest = arr[i][j];
}
if (arr[0][0] > largest) {
largest = arr[i][j];
}
{
JOptionPane.showMessageDialog(null, "The smallest value in the Array is:" + smallest);
JOptionPane.showMessageDialog(null, "The largest value in the Array is:" + largest);
}
}
}}}
How can I find the lowest and highest number in 2d array?
I'm getting an error with my code? what seems to be wrong?
I just need to find the highest and lowest among the 12 numbers user will input. here is what I have so far.
How can I find the lowest and highest number in 2d array?
I'm getting an error with my code? what seems to be wrong?
I just need to find the highest and lowest among the 12 numbers user will input. here is what I have so far.
You do not have a loop to take in your array and therefore are receiving an error. To take in the input of the Array use this
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++)
arr[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Please enter 12 numbers: "));
Therefore you will have the box outputted 12 times for the user to input 12 Integers and then once you have the Array just run a simple sort to get the smallest and the largest.
int smallest = arr[0][0];
int largest = arr[0][0];
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++) {
if (arr[i][j]<smallest)
smallest = arr[i][j];
else if(arr[i][j]>largest)
largest = arr[i][j];
}
}
Final Code being
public class Solution {
public static void main (String[]args) {
int [][] arr= new int[3][4];
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++)
arr[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Please enter 12 numbers: "));
int smallest = arr[0][0];
int largest = arr[0][0];
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++) {
if (arr[i][j]<smallest)
smallest = arr[i][j];
else if(arr[i][j]>largest)
largest = arr[i][j];
}
}
JOptionPane.showMessageDialog(null, "The smallest value in the Array is:" + smallest);
JOptionPane.showMessageDialog(null, "The largest value in the Array is:" + largest);
}
}
The error is mainly in the initialization part where you have assumed the element in the first row and first column to be either the minimum or maximum element in the array.
You have to initialize the minimum value of the array with a value that is sure to be higher than all the values in the array, why? because only then will there be an update to the actual minimum value of the array, so for example if you set minimum to be 1000 then if the actual minimum of the array is 300, it would get updated. But if you set your minimum to be for example 30 then 300 which is the actual minimum wont get logged and there would be an error.
The absolute opposite applies to the initialization of the largest value of the array. While initializing, safe ball park estimates usually work so carry out the initializations accordingly.
Personally, I don't think you should use JOptionPane to get data from the user and to display data to the user in a Java console application such as yours. I prefer to use Scanner.
(Below code demonstrates. Notes after the code.)
Note that calling a method of JOptionPane will launch the Event Dispatch Thread (EDT) which means that your application will not terminate – unless you add System.exit(0);.
package HighLow;
public class HighLow {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.print("Please enter 12 numbers: ");
String line = stdin.nextLine();
String[] numbers = line.split(" ");
int k = 0;
int[][] arr = new int[3][4];
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = Integer.parseInt(numbers[k++]);
if (arr[i][j] < smallest) {
smallest = arr[i][j];
}
if (arr[i][j] > largest) {
largest = arr[i][j];
}
}
}
System.out.println("The smallest value in the Array is: " + smallest);
System.out.println("The largest value in the Array is: " + largest);
}
}
I assume that the user enters twelve numbers separated by a space in a single line.
Method split returns an array of size twelve where every element is one of the entered numbers.
I initialize smallest to the largest int which guarantees that the first int that I compare it to is guaranteed to be smaller.
Similarly for largest. I initialize it to the smallest possible int.
You need a loop in order to populate all the elements of arr.
Here is output from a sample run of the above code.
Please enter 12 numbers: 1 2 3 4 5 6 7 8 9 0 -1 -2
The smallest value in the Array is: -2
The largest value in the Array is: 9
EDIT
Since you claim that JOptionPane is required, below code uses JOptionPane.
String line = JOptionPane.showInputDialog("Please enter 12 numbers: ");
String[] numbers = line.split(" ");
int k = 0;
int[][] arr = new int[3][4];
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = Integer.parseInt(numbers[k++]);
if (arr[i][j] < smallest) {
smallest = arr[i][j];
}
if (arr[i][j] > largest) {
largest = arr[i][j];
}
}
}
JOptionPane.showMessageDialog(null, "The smallest value in the Array is:" + smallest);
JOptionPane.showMessageDialog(null, "The largest value in the Array is:" + largest);
System.exit(0);

How do I make a calculator that multiplies more than two numbers?

I made a calculator that does multiple things (adding consecutive numbers, adding multiple numbers, etc) but I am having trouble making it so that the calculator can multiply multiple numbers. So far, I've basically copied the code that adds multiple numbers, but I can't figure out how to make it multiply instead of add.
Here is my code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String arg[])
{
int n;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to add up to: ");
n = s.nextInt();
System.out.println("you entered: " + n + "");
sum = addConsecutiveNumbers(n);
System.out.println("sum of 1 to "+n+" = "+sum);
//following code is sum of any numbers you entered from console
//store the numbers into an array
int num;
int sumOfNums=0;
System.out.print("Please enter how many numbers you want to sum: ");
num=s.nextInt();
System.out.println("you want to sum "+num+" numbers ");
sumOfNums = addNumbers(num);
System.out.println("sum of "+num+" numbers = "+sumOfNums);
}
//Define a method which add consecutive numbers based on user's input and return the sum of the numbers
private static int addConsecutiveNumbers (int number)
{
int sum = 0;
for (int i = 1; i <= number; i++)
{
sum = sum + i;
}
return sum;
}
//Define a method which add numbers based on user's input and return the sum of the numbers
private static int addNumbers (int num)
{
Scanner s = new Scanner(System.in);
int a[] = new int[num];
int sumOfNums = 0;
for(int k = 0; k < num; k++)
{
System.out.println("enter number "+(k+1)+":");
a[k] = s.nextInt();
System.out.println("The array of a[" + k + "] = " + a[k]);
}
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
return sumOfNums;
}
//below is the part of code that I am having trouble with.
public static int multiplyNumbers(int num)
{
int Area = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[num];
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
for(int l = 0; l < num; l++)
{
System.out.println("enter number "+(l+1)+":");
a[l] = s.nextInt();
System.out.println("The array of a[" + l + "] = " + a[l]);
}
return Area;
}
}
I see one thing right away; The way I see your code, the following two lines a redundant:
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
You should have already asked the user how many numbers they want to multiply, because it's passed in as a parameter. As for your actual problem, take a look at these lines from the addNumbers() method:
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
All you gotta do is copy that code in right before your return statement (return Area;). You'll need to tweak it a bit so instead of using the sumOfNums variable, it uses the Area variable, and instead of adding, it multiplies. This can be done like so:
for(int j = 0;j < num ; j++) //j also needs to start at 0, I think you may have made a mistake when writing the summing method
{
Area *= a[j];
}
You'll notice there's an issue with this algorithm though (almost didn't catch it myself). Area starts off with a value of 0, so 0 multiplied by any number will always still be 0. Simple fix; just manually set Area to the first value before the loop. Something like this:
Area = a[0];
for(int j = 1; j < num; j++)
{
sumOfNums += a[j];
}
Also notice I started the for loop at j = 1 this time. This is because I already started Area as a[0], so we don't want to multiply that number twice.
You don't need to store values in an array for multiplication similarly for addition you can directly update the final result
public static int multiplyNumbers(int num) {
int Area = 1;
Scanner s = new Scanner(System.in);
System.out.println("Please enter how many numbers you want to multiply:");
num = s.nextInt();
for (int l = 0; l < num; l++) {
System.out.println("enter number " + (l + 1) + ":");
int temp = s.nextInt();
Area *= temp;
System.out.println("The array of a[" + l + "] = " + temp);
}
return Area;
}

Adding Items to an array in Java

I wanted to create an array that has a length specified by the user, and also wanted to have it filled by a loop command, and then it should be copied to another array by another loop command, so I wrote a code but it generates an error when trying to run it
Scanner input = new Scanner(System.in);
System.out.print("Hello, Please enter the amount of numbers: ");
int n = input.nextInt();
int array1[] = new int[n];
int array2[] = new int[n];
System.out.print("Please enter your numbers: ");
for (int i = 0; i < n; i++) {
int index = input.nextInt();
array1 [index] = array1 [i];
}
for (int i = 0; i < n; i++) {
array2[i] = array2[i];
}
System.out.println("Array 1 is: " +Arrays.toString(array1));
System.out.println("Array 2 is: " +Arrays.toString(array2));
so the code runs with a single issue that all the elements are set to zero if I entered the elements of the array less than the size of the array "n".
but if for example, I entered the size is 5, and tried to fill the array, the program crash if I tried to add any number larger than 5 in the array.
I know that the problem sounds silly, but I'll be grateful if you guys helped me out with it.
You have two problems in your code.
Substitute your for(s) with the following code:
for (int i = 0; i < n; i++) {
int element = input.nextInt(); //elemet inserted by the user
array1[i] = element;
}
for (int i = 0; i < n; i++) {
array2[i] = array1[i];
}
for add item in array
for (int i = 0; i < n; i++) {
int index = input.nextInt();
array1 [i] = index ;
}

Random int array not printing min and max

I am new to Java (and coding in general). I need to write a method that gets an integer, creates an array made of random numbers of the length of the integer, range 1-50
(inclusive) and finds the maximum and minimum number.
I was able to fill the array with random numbers. However, my min and max are not printing. I have been looking at this for hours with no luck - any advice would be very helpful! Thank you.
import java.util.Scanner;
import java.util.Random;
class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
//user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in .nextInt();
System.out.println();
int x;
int randNum;
int y;
//create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
} //for
} //for
} //main method
} //class
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
Look closely at this code. Inside the loop, you are setting
largest = array[s];
and then immediately checking
if (array[s] > largest)
Of course it's not, you just made them equal!
Put the assignments inside the conditions:
// Remove largest = array[s]
if (array[s] > largest) {
largest = array[s];
}
Similarly for smallest.
Note: I would recommend against commenting on closing braces. Note only is it unnecessary effort, it is confusion-prone: in this snippet of code above, the //for and //if are reversed. Additionally, it doesn't tell you which "if" or "for" it is closing.
Simply looking at the indentation is an easier way.
Your program does not fill the array with random numbers. It creates several arrays and fills each of them with a single number. You should change this part of the program:
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
/* min-max code */
}
}
to this:
Random r = new Random();
int[] array = new int[userNum];
for (int i = 0; i <= userNum; i++) {
array[i] = r.nextInt(50) + 1;
System.out.println(array[i]);
}
/* min-max code */
This will create a single array, fill it with random numbers, and print each element of the array, which seems to be what you intended.
The code that finds the minimum and maximum is also incorrect.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
} else if (array[s] < smallest) {
System.out.println(smallest);
}
}
You should only set largest or smallest when array[s] is actually the largest or smallest value in the array so far. To check whether or not this is the case, you can use Math.min() and Math.max(), which return the smallest or largest, respectively, of two values.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = Math.max(array[s], largest);
smallest = Math.min(array[s], smallest);
}
System.out.println(largest);
System.out.println(smallest);
This is what you looking for::
import java.util.Scanner;
import java.util.Random;
public class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
// user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in.nextInt();
System.out.println();
int x;
int randNum;
int y;
int[] array = new int[userNum];
// create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println("number " + i + ":: " + randNum);
array[i - 1] = randNum;
}
// print array
for (int s = 0; s < array.length; s++) {
System.out.println("array[" + s + "] number :: " + array[s]);
}
// find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
if (array[s] > largest) {
largest = array[s];
// find min
} else if (array[s] < smallest) {
smallest = array[s];
}
}
System.out.println("\nLargets Number:: " + largest);
System.out.println("Smallest Number:: " + smallest);
} // main method
} // class
Don't confuse too much when you are using loops.Some mistakes you done while writing code.
1> You have declared array int[] array = new int[userNum];
in for loop. which mean it will create as much arrays as loop iterate. and not accessible outside loop.
2> Same with variables largest and smallest int largest = array[0];
int smallest = array[0];
3> for (x = 1; x < 1; x++) control never ever enter the loop since your condition x<1 is never satisfy because you have initiated x=1 and and it will never ever be less than 1 as in condition (x<1).
Suggestion :: To find largest you have to traverse through array and check every element for largest and smallest and store it in separate variable rather than printing it at every check.
In my code i have used three for loops::
1>> to generate and print random number. In same loop i'm filling array with generated number.
2>> Here just printing array separately for better presentation in output.
3>> Finding largest and smallest by assigning values in if block if they satisfy condition.
I hope this will help you to understand code.

Displaying odd values in an array

I am trying to display the odd numbers in an array, but only once per number (i.e. numbers[3] = 3,3,1; would only display 3 and 1 instead of 3, 3 and 1.)
this is the code that I have as of now, the program completely will create an with the specific length entered by the user and then will calculate the max min, and odd values in the array.
import java.util.Scanner;
public class ArrayLab
{
static Scanner input = new Scanner (System.in);
public static void main(String[] args)
{
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
numbers[i] = input.nextDouble();
}
input.close();
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
System.out.println("The max is: " + max);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] < min)
{
min = numbers[i];
}
}
System.out.println("The min is: " + min);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
System.out.println ("The odd numbers are: " + numbers[i]);
}
}
}
}
thanks for any help.
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
set.add(numbers[i]);
}
}
System.out.println ("The odd numbers are: " +set);
This can be done a lot simpler using Java8:
double[] d = Arrays.toStream(numbers).filter(d -> (d % 2) == 1).distinct().toArray();
for(double tmp : d)
System.out.println(tmp);
System.out.println("min: " + Arrays.toStream(numbers).min((a , b) -> new Double(a).compareTo(b)));
System.out.println("max: " + Arrays.toStream(numbers).max((a , b) -> (new Double(a).compareTo(b))));
For you're solution: you never eliminate repeating numbers, thus the duplicates remain in the array until you print all odd numbers and the maximum-number.
This elimination can be done in several ways:
Using Java8 as above
add all values to a Set, since these don't allow duplicate values
eliminate them in your own way (i won't provide any code for this since it's rather complicated to design an efficient solution for this)
Updated solution for what you need. And Please use a better coding standard. Do note the condition check !oddNumbers.contains(numbers[i]) is not very necessary as HashSet never takes any duplicate values.
import java.util.HashSet;
import java.util.Scanner;
public class ArrayLab {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
numbers[i] = input.nextDouble();
}
input.close();
HashSet<Double> oddNumbers = new HashSet<Double>(NUMBER_OF_ELEMENTS);
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
if (numbers[i] % 2 != 0 && !oddNumbers.contains(numbers[i])) {
oddNumbers.add(numbers[i]);
}
}
System.out.println("The max is: " + max);
System.out.println("The min is: " + min);
System.out.println("The odd numbers are: " + oddNumbers);
}
}
A more meaningful solution to your approach would be as follows:
int[] tempArray; //temporary array to store values from your original "array"
int count=0;
for(int i=0; i<numbers.length; i++) {
if(numbers[i]%2 != 0) {
count++;
}
}
tempArray = new int[count]; //initializing array of size equals to number of odd digits in your array
int j = 0;
for(int i=0; i<numbers.length; i++) {
boolean check = true;
for(int k=0; k<j; k++) {
if(tempArray[k] == numbers[i]) {
check = false; //this will prevent duplication of odd numbers
}
}
if(numbers[i]%2 != 0 && check) {
tempArray[j]=numbers[i];
j++;
}
}
//Now print the tempArray which contains all the odd numbers without repetition
A few people have mentioned sets, but there is a different way as well. Simply sort the array, then scan through it, checking each number against the last one printed. i.e.,
int lastPrinted = 0;
// Sort the array
Arrays.sort(numbers);
System.out.print("The odd numbers are: ");
// Scan through the array
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
// if it's odd and doesn't match the last one...
if (numbers[i] % 2 != 0 && numbers[i] != lastPrinted)
{
// ...print it and update lastPrinted
System.out.print( "" + numbers[i] );
lastPrinted = numbers[i];
}
}
System.out.println("");
As a side note, you really don't have to scan through the array twice to find your max and min, you can do that in one go.
I think you can use inbuilt hashmap class and its method to achieve the task without affecting the complexity of algorithm to any great extent .
import java.util.HashMap;
public class Hashing {
public static void main(String[] args) {
//declare a new hasmap
HashMap<Integer, Integer> map = new HashMap<>();
//consider Arr as your Array
int Arr[] = {3,3,1,4,5,5,7,8};
//traverse through the array
for(int i=0;i<Arr.length;i++){
//check if the required condition is true
if(Arr[i]%2==1){
/*now we insert the elements in the map but before
that we have to make sure that we don't insert duplicate values*/
if(!map.containsKey(Arr[i])){// this would not affect the complexity of Algorithm since we are using hashMap
map.put(Arr[i], Arr[i]);//We are storing the Element as KEY and as VALUE in the map
}
}
}
//now We can get these element back from map by using the following statement
Integer[] newArray = map.values().toArray(new Integer[0]);
//All the required elements are now present in newArray
for(int ele:newArray){
System.out.println(ele);
}
}
}

Categories

Resources