Second smallest number in array - incorrect output - java

So this has been bugging me for a hour and a half and it's getting really annoying. I'm not sure what's the issue because I've rechecked several times my code, I've googled and searched for other ways or if I did something wrong and I still don't see anything.
This is an excerpt from my code:
// MAX AND MIN NUMBER
int maxnum = array[0];
int minnum = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] > maxnum) {
maxnum = array[i];
} else if (array[i] < minnum) {
minnum = array[i];
}
}
System.out.println("Maximum number is " + maxnum + ", minimum is " + minnum + ".");
// --------------------------------------------------------------------------------
// SECOND SMALLEST NUMBER
int secondnum = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] == minnum) {
secondnum = minnum;
} else if (array[i] < minnum) {
secondnum = minnum;
minnum = array[i];
} else if (array[i] < secondnum) {
secondnum = array[i];
}
}
System.out.println("Second smallest number is " + secondnum + ".");
array[i] is an input from the user. At the beginning, the program asks you to enter how many numbers you wish to enter and then you proceed to enter them.
I put in five and I enter five numbers but my second smallest number is the same as my smallest number. Sometimes I get a correct answer.
Any ideas?
EDIT:
Works with user3591111's help. Thanks!

In the first for you can start in i =1 in the second for try.
int secondnum = maxnum;
for (int i = 0; i < array.length; i++) {
if (array[i] != minnum && array[i] <secondnum )
secondnum = array[i];
}
This wont work if you have repeated numbers because your small can be equal to your second small for that you will need to store the location of your small number and in the if change to if ((array[i] != minnum || smallPos != i) && array[i] <secondnum )

Related

Printing the Bigger to smaller with Array on Java

I have this program:
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
for (i = 0; i < 10; i++) {
System.out.println("Give " + (i+1) + " number") ;
array[i] = input.nextDouble();
}
double max = array[0], min =array[0];
int negative = 0 ;
for (i = 0; i < 10; i++){
if(array[i] > max){
max = array[i] ;
}
if (array[i] < min){
min = array[i];
}
}
//Difference between Biggest to Smaller number
for (i = 0; i < 10; i++){
// ...
}
for (i = 0; i < 10; i++){
if(array[i] < 0){
negative = negative + 1;
}
for (i = 0; i < 10; i++){
System.out.println("The double of " + (i+1) + " is: " + (array[i] * 2) );
}
System.out.println("\n" + "The Maximum is: " + max);
System.out.println("The Minimum : " + min);
System.out.println("The Difference between Biggest to Smaller is : ");
System.out.println("Τhe count of negative objects are : " + negative);
I want to print the bigger to smaller number difference with values I have now.
I forgot what I need to add. I searched online, but the most of answers that I found, conflict with the whole program.
Any suggestion here?

JOptionPane Looping

I have an issue. My lecturer wants me to make a loop, with an input of JOptionPane and an output of console. How can I use loop for JOptionPane and send an output through console.
Here's my code:
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
String a1 = JOptionPane.showInputDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++){
int a = Integer.parseInt(a1);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
I would try using a DO-WHILE loop with and an int[], example:
int size = 10;
int count = 0;
int[] yourNumbers = new int[size];
do {
yourNumbers[count] = Integer.parseInt(JOptionPane.showInputDialog(null,
"Your message here."));
count++;
} while (count < 10);
This way you can loop through and grab all the numbers. Then you can use a FOR-LOOP to cycle through and print what you need
System.out.println("Even Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 == 0) {
System.out.println(yourNumbers[i]);
}
}
System.out.println("Odd Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 != 0) {
System.out.println(yourNumbers[i]);
}
}
The problem with your current code is that you only ask the user one time to input a number but you actually seem to want 10 values. So you parse ten times the same value.
The solution is simple, put the dialog inside the loop (only changed the lines with comments):
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
// No return type, just a message
JOptionPane.showMessageDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++) {
// Dialog inside the loop, asking to
// input a number in every iteration
String value = JOptionPane.showInputDialog(null, "Type in "
+ (counter + 1) + ". value");
int a = Integer.parseInt(value);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);

How to check next number and compare it to the previous one

I have got an array of numbers of size 14 which is filled with -1 where its blank, rest of numbers are as in following example [2,3,4,7,8, -1, -1...].
How would I compare the numbers so that they are 1 apart, and take first and last number from that comparison. So here I would compare |2-3|=1, |3-4|=1, |4-7|=3, I would take 2 as first number and 4 as last number and then compare the other half, so |7-8|=1 and then 7 is first number and 8 is last number.
int diff = 0;
int firstNum = 0;
int lastNum = 0;
for (int j=0; j < temp.length; j++){
if (temp[j] != -1){
diff = Math.abs(temp[j] - temp[j+1]);
if (diff <= 1){
// first and last number
firstNum = temp[j];
lastNum = temp[j+1];
}
else {
firstNum = temp[j];
lastNum = temp[j+1];
}
}
}
You can try this:
int diff = 0;
int firstNum = temp[0];
int lastNum = temp[0];
for (int j=0; j < temp.length - 1; j++){
if (temp[j] != -1){
diff = Math.abs(temp[j] - temp[j+1]);
if (diff <= 1){
// last number
lastNum = temp[j+1];
}
else {
System.out.println("First number: " + firstNum + ", last number: " + lastNum);
firstNum = temp[j+1];
lastNum = temp[j+1];
}
}
}
Try this..,
int diff = 0;
bool flag = false;
int firstNum = 0;
int lastNum = 0;
for (int j=0; j < temp.length-1; j++){
if (temp[j] != -1 && temp[j+1] != -1){
diff = Math.abs(temp[j] - temp[j+1]);
if (diff <= 1){
if(firstNum == 0)
firstNum = temp[j];
lastNum = temp[j+1];
flag = false;
}
else {
System.out.println(firstNum + ", " + lastNum);
firstNum = 0;
flag = true;
}
}
if (!flag)
System.out.println(firstNum + ", " + lastNum);
}
If i didn't do the flag thing, it'd print it twice. There might be some other efficient way to do this.

How to calculate the average of even and odd numbers in an array?

As a class exercise I have to code using methods a program that:
1) Calculates the average of even and odd numbers in an array.
I expect on using one method to find the average of even and odd numbers. However, I'm having trouble on returning the right average. For example, if I enter only odd numbers I get an error, and vice versa.
This error:
"java.lang.ArithmeticException: / zero"
Also, if it were possible I would like to get some help on coding the rest of the exercise which asks for:
2) Print the highest and lowest number in the array
3) Allow the user to modify any of the numbers of the array
So far I have this code:
public static void main (String args[]){
int x[] = new int[4];
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length ; i++){
System.out.println("Enter a number: ");
x[i] = input.nextInt();
}
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
}
public static int getAverage(int a[]){
int add_even = 0;
int counter_even = 0;
int average_even = 0;
int add_odd = 0;
int counter_odd = 0;
int average_odd = 0;
for(int i = 0; i < a.length; i++){
if(a[i] % 2 == 0){
add_even += a[i];
counter_even++;
}
else if(a[i] % 2 == 1) {
add_odd += a[i];
counter_odd++;
}
}
if (add_even % 2 == 1 && add_odd % 2 == 1){
average_even = 0;
average_odd = add_odd / counter_odd;
return average_even;
}
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
else{
average_even = 0;
average_odd = add_odd / counter_odd;
return average_odd;
}
}
Thank you!
Your get average looks more complicated then it needs to be.
First off the getAverage(x):
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
will return the same value, so if you wanted to get the average for odds or evens the method should require a boolean arg to represent odd or even.
In your method you should loop through all the numbers and check if it is even. If it is even and you are averaging evens add it to a "total" and add one to a counter. At the end divide "total" by the counter and return the value. The average will most likely include a decimal value, so you should return a double or a float.
Example:
public static double getAverage(int a[], boolean even){
double total = 0;//These are doubles so dividing later does not require casting to retain a decimal (this can be an int if you only want to return integers)
double counter = 0;
for(int i = 0; i<a.length; i++){
if(a[i] % 2 == 0 && even){//even
counter++;
total += a[i];
}else{//odd
counter++;
total += a[i];
}
}
if(total == 0){//Avoid dividing by 0.
return 0; //You can also throw an exception instead of returning 0.
}
return total / counter; //Returns the average for even or odd numbers.
}
For the second part of your question you need to loop through the numbers and find the highest and lowest while looping.
Example:
int highest = 0;
int lowest = 0;
for(int i = 0; i<x.length; i++){
if(x[i] > highest){
highest = x[i];
}
if(x[i] < lowest){
lowest = x[i];
}
if(i == 0){
highest = x[i];
lowest = x[i];
}
}
You have a divide by zero error cropping up here.
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
0 % 2 == 0 so even if add_even is 0 (and as a result, so is counter_even) you're attempting to use it to divide. You'll need to account for that in your code by checking if counter_even is 0.
else if (counter_even != 0 && add_even % 2 == 0 && add_odd % 2 == 0){
1)Using one method to get the average of the even and odd numbers isn't proper because you only return one int. It would be simpler to use two methods but if you're insistent on using one method you could add a boolean as a parameter like this to decide which to do. To handle the ArithmeticException just return 0 if there are no values.
public static int average(int[] n, boolean even) {
int total = 0;
int count = 0;
for (int i = 0; i < n.length; i++) {
if (even == (n % 2 == 0)) {
total += n;
count ++;
}
}
if (count == 0)
return 0;
return total / count;
2)To check find the max and min value simply loop through the array like this
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++) {
if (x[i] < min)
min = x[i];
if (x[i] > max)
max = x[i];
}
3)To allow the user to modify the array, you could print the values and prompt them as to which value they would like to change like this.
System.out.print("Array: ");
for (int i = 0; i < x.length; i++) {
System.out.print(i + ",");
}
System.out.println();
System.out.println("Which value would you like to change?");
int index = input.nextInt();
System.out.println("What do you want the new value to be?");
int value = input.nextInt();
You can then run a method that changes the value of the array
edit(x, index, value);
public static int edit(int[] n, int index, int value) {
n[index] = value;
return n;
}
I used JS for this task, you can just rewrite my code to Java language.
A number is divisible by 2 if the result of its division by 2 has no
remainder or fractional component - in other terms if the result is an
integer. Zero is an even number because when 0 is divided by
2, the resulting quotient turns out to also be 0 - an integer (as a
whole number that can be written without a remainder, 0 classifies as
an integer).
function compareEvenOddAverage(arr) {
let even = 0,
odd = 0,
evenCounter = 0,
oddCounter = 0,
str = '';
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
even += arr[i];
evenCounter++;
} else {
odd += arr[i];
oddCounter++;
}
}
if (even / evenCounter > odd / oddCounter) {
str += 'Average value of even numbers is greater';
} else if (even / evenCounter < odd / oddCounter) {
str += 'Average value of odd numbers is greater';
} else {
str += 'Average values are equal';
}
return str;
}
console.log(compareEvenOddAverage([0, 1, 2, 3, 4, 5]));

Array java help needed

I have this program that takes user input and displays the number of times each integer is entered. I pretty much have it down pat but need another loop to omit the shown occurrence of 0. In other words any number with 0 in it cannot be read, also for some reason i am getting two outputs from the same number in my program. For example, if I enter 3,3 I will get 3 occurs 1 time and 3 occurs 2 times as output. The 2 times one being correct and the first one being incorrect.
public class Six_Three {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("enter integers between 1 and 100: ");
int[] num = new int[100];
int data = input.nextInt();
while ((data = input.nextInt()) != 0) {
num[data]++;
}
for (int i = 1; i < 100; ++i) {
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
}
You need two separate loops: the first to gather the information, and the second to print the results:
int data = 0;
while ((data = input.nextInt()) != 0)
{
num[data]++;
}
for (int i = 0; i < 100; ++i)
{
if (num[i] != 0) { /* print num[i] */ }
}
Just loop over the num array after your while loop to print the counts.
for (int index = 0; index < num.length; index++) {
if (num[index] != 0)
System.out.println(data + " occurs " + num[data] + " time(s).");
}
You are printing an output every time an integer is read. Your program is behaving as expected.
To get what you want, you need to scan all the input before you produce any output.
Try this instead:
while (data != 0){
data = input.nextInt();
num[data]++;
}
for (int i = 1; i < 100; ++i) { // your version is 0...99, else array index out of bounds
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
The way you write it the last number has to be 0 to make the scanning stop. It might be a good idea to check if there's another int available and use that as a condition for the scanning loop. That way your program can accept any integer.
while (input.hasNextInt()){
num[input.nextInt()]++;
}
it's so simple
int data = 0;
int[] num = new int[100];
int i = 0;
while (i < num.length) {
if ((data = input.nextInt()) == 0)
break;
num[i] = data;
i++;
}
for (i = 0; i < 100; ++i) {
int times = 0;
if (num[i] != 0) {
for (int j = 0; j < 100; j++) {
if (num[j] == 0) {
break;
} else if (num[i] == num[j]) {
times++;
}
}
System.out.println(num[i] + " occurs " + times + " times ");
} else {
break;
}
}

Categories