Even, Odd with min and max for the Odd only [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Prompt the user to enter the size of an array and allow the user to
input integer values to your array. Check each element if it is even
or odd. If even, print solved elemets (ascending order), If odd, get
the max and min using conditional statement. Output the result.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
int s[] = new int[n];
for (int i = 0; i < n; i++) {
int e = sc.nextInt();
s[i] = e;
}
Arrays.sort(s);
System.out.println("\nEven numbers in ascending order:");
for (int j = 0; j < n; j++) {
if (s[j] % 2 == 0) {
System.out.print(s[j] + " ");
}
}
System.out.println("\nOdd numbers in descending order:");
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
System.out.print(s[j] + " ");
}
}
}
I don't know how to add min/max for the Odd

If I understand your question, you could try this:
int min = Integer.MAX_VALUE; // init min to the most max value
int max = 0; // store max value
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
if (min > s[j]) {
min = s[j];
}
if (max < s[j]) {
max = s[j];
}
System.out.print(s[j] + " ");
}
}
System.out.println("min = " + min);
System.out.println("max = " + max);
Full code:
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
int s[] = new int[n];
for (int i = 0; i < n; i++) {
int e = sc.nextInt();
s[i] = e;
}
Arrays.sort(s);
System.out.println("\nEven numbers in ascending order:");
for (int j = 0; j < n; j++) {
if (s[j] % 2 == 0) {
System.out.print(s[j] + " ");
}
}
//===========================================
System.out.println("\nOdd numbers in descending order:");
int min = Integer.MAX_VALUE; // init min to the most max value
int max = 0; // store max value
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
if (min > s[j]) {
min = s[j];
}
if (max < s[j]) {
max = s[j];
}
System.out.print(s[j] + " ");
}
}
System.out.println(); // for new line
System.out.println("min = " + min);
System.out.println("max = " + max);
}

The solution to my problem is:
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a Value: ");
int val = s.nextInt();
if (val == 0) {
break;
}
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
System.out.println("min: " + min);
System.out.println("max: " + max);

Related

Java Single Dimensional Arrays

Enter the integers between 1 and 50: 1 2 1 0
1 occurs 2 times
2 occurs 1 times
1 occurs 2 times
How can I do to get 1 occurs only 1 times ?
The problems is to it's print many times.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
System.out.print("Enter the integers between 1 and 50: ");
num[i] = input.nextInt();
while(num[i] != 0){
i++;
num[i] = input.nextInt();
}
for(int j=0;j<i;j++){
int n = 0;
for(int k=0;k<i;k++){
if(num[j] == num[k]){
n++;
}
}
System.out.println(num[j] + " occurs " + n + " times");
}
}
}
Edit this Code
Try this (Refer to code comments for explanations):
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
while (i < 100) { // Check if the array is already full
System.out.print("Enter 0 to Exit or enter the integers between 1 and 50 (Input #" + (i + 1) + ") : ");
int value = input.nextInt();
if (value == 0) {
break;
}
if (value < 1 || value > 50) { // check if input is between 1 and 50
System.out.println("Input is not between 1 and 50");
} else {
num[i] = value;
System.out.println();
}
i++;
}
System.out.println();
System.out.println("Result: ");
for (int j = 0; j < i; j++) {
int n = 0;
boolean isAlreadyPrinted = false; // flag to check if will be printed or not
for (int k = 0; k < i; k++) {
if (num[j] == num[k]) {
if (j > k) { // this means that the same value is already found and printed
isAlreadyPrinted = true;
}
n++;
}
}
if (!isAlreadyPrinted) {
System.out.println(num[j] + " occurs " + n + " times");
}
}
}
}
The problem is with your for loop.
You should not run the j's value up to i. That's why "1 occurs 2 times" is printing twice. What you have to do is checking the value of the array's certain index has been occurred multiple times before print part executed.
public static<T> T[] subArray(T[] array, int beg, int end) {
return Arrays.copyOfRange(array, beg, end + 1);
}
public static boolean hasDuplicateValues (int[] array, int value )
{
boolean result = false ;
int count = 0 ;
for (int i=0 ; i< array.length; i++)
{
if(array[i] == value)
{
count = count+1 ;
}
}
if(count > 1)
{
result = true;
}
return result;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
System.out.print("Enter the integers between 1 and 50: ");
num[i] = input.nextInt();
while(num[i] != 0){
i++;
num[i] = input.nextInt();
}
for(int j=0;j<i;j++){
int n = 0;
for(int k=0;k<i;k++){
if(num[j] == num[k]){
n++;
}
}
int[] subarray = subArray(num, 0, i);
boolean isDuplicate = hasDuplicateValues (subarray , num[i] )
if(isDuplicate == false )
{
System.out.println(num[j] + " occurs " + n + " times");
}
}
}

Java - Arrays/Loops

I wanted to display the second highest and second lowest number in a given random array values ranges from(0 to 999999) and also the way the highest number will be printed in tagalog word and the shortest number will be printed in Spanish word. Here is by far is my work,can you cite or add some code for it to work? I'm having a hard time on my Main method and connecting all of them.
package demo;
import java.util.Scanner;
public class MachineProject {
public static void main(String[] args) {
int number = 5;
Scanner in = new Scanner(System.in);
int[] array=new int[5];
System.out.println("Input 6 numbers between 0 and 999,999 :");
number = in.nextInt();
for (int i=0;i<5;i++) {
array[i]=in.nextInt();
}
if(number>=0 && number<=999999){
if(number==0){
System.out.print("NUMBER AFTER CONVERSION:\tZERO");
} else {
System.out.print("NUMBER AFTER CONVERSION:\t");
convertNumberToWordsTagalog(((number / 100) % 10), " HUNDRED");
convertNumberToWordsSpanish((number % 100), " ");
}
} else{
System.out.print("NUMBER OUT OF RANGE");
}
System.out.print("\nPlease type a number between 0 and 999 OR type -1 to exit: ");
number = in.nextInt();
}
public static final String[] unitsSpanish = {
"", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete",
"ocho", "nueve", "diez", "once", "doce", "trece", "catorce",
"quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve"
};
public static final String[] tensSpanish = {
"", // 0
"", // 1
"veinte", // 20
"treinta", // 30
"cuarenta", // 40
"cincuenta", // 50
"sesenta", // 60
"setenta", // 70
"ochenta", // 80
"noventa" // 90
};
public static final String[] unitsTagalog = {
"", "isa", "dalawa", "tatlo", "apat", "lima", "anim", "pito",
"walo", "siyam", "sampu", "labing isa", "labing dalawa", "labing tatlo", "labing apat",
"labing lima", "labing anim", "labing pito", "labing walo", "labing siyam"
// 0-19
};
public static final String[] tensTagalog = {
"", // 0
"", // 1
"dalawampu", // 20
"tatlumpu", // 30
"apat-na-pu", // 40
"limampu", // 50
"anim-na-pu", // 60
"pitumpu", // 70
"walumpu", // 80
"siyam-na-pu" // 90
};
public static String convertNumberToWordsTagalog(final int num) {
if (num < 20) {
return unitsTagalog[num];
}
if (num < 100) {
return tensTagalog[num / 10] + ((num % 10 != 0) ? " " : "") + unitsTagalog[num % 10];
}
if (num < 1000) {
return unitsTagalog[num / 100] + " daan" + ((num % 100 != 0) ? " " : "") + convertNumberToWordsTagalog(num % 100);
}
return convertNumberToWordsTagalog(num / 1000) + " libo" + ((num % 1000 != 0) ? " " : "") + convertNumberToWordsTagalog(num % 1000);
}
public static String convertNumberToWordsSpanish(final int num) {
if (num < 20) {
return unitsSpanish[num];
}
if (num < 100) {
return tensSpanish[num / 10] + ((num % 10 != 0) ? " " : "") + unitsSpanish[num % 10];
}
if (num < 1000) {
return unitsSpanish[num / 100] + " cien" + ((num % 100 != 0) ? " " : "") + convertNumberToWordsSpanish(num % 100);
}
return convertNumberToWordsSpanish(num / 1000) + " mil" + ((num % 1000 != 0) ? " " : "") + convertNumberToWordsSpanish(num % 1000);
}
static void SecondSmallest(int arr[]) {
Scanner in = new Scanner(System.in);
//Input size of an array
int n = in.nextInt();
//Array declaration
int arr1[] = new int[n];
//Taking an input value of an array
for (int j = 0; j < arr1.length; j++) {
arr1[j] = in.nextInt();
}
//Initialize with max value of integer
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
//Traverse an array
for (int i = 0; i < arr1.length; i++) {
if (smallest > arr1[i]) {
secondSmallest = smallest;
smallest = arr1[i];
}
if (arr1[i] > smallest && arr1[i] < secondSmallest) {
secondSmallest = arr1[i];
}
}
in.close();
System.out.println("Second smallest number is " + secondSmallest);
}
public static void SecondHighest(int arr[], int second_max) {
int max = 0, temp, numbers;
Scanner in = new Scanner(System.in);
numbers = in.nextInt();
for (int i = 0; i < numbers; i++) {
if (i == 0) {
max = in.nextInt();
} else {
temp = in.nextInt();
if (temp > max) {
second_max = max;
max = temp;
}
else if(temp>second_max)
{
second_max=temp;
}
}
}
in.close();
System.out.println("Second highest number :" + second_max);
}
}
In your code you store the numbers into an array, but you never use it.
The same for
System.out.print("\nPlease type a number between 0 and 999 OR type -1 to exit: ");
number = in.nextInt();
If you want to just find the min and max, you don't need to store every value.
You can look for min and max while the user inputs the numbers.
public static void main(String[] args) {
final int MAX_VALUE = 999999;
int min = Integer.MAX_VALUE;
int second_min = Integer.MAX_VALUE;
int second_max = Integer.MIN_VALUE;
int max = Integer.MIN_VALUE;
final Scanner in = new Scanner(System.in);
System.out.println("How many numbers do you want to insert? (0 or a negative number to exit)");
int n = in.nextInt();
if (n <= 0) {
System.out.println("Goodbye");
System.exit(0);
}
System.out.println("Input "+n+" integers between 0 and " + MAX_VALUE + " :");
int val; // this integer will be used to check the input
for (int i = 0; i < n; i++) {
do {
val = in.nextInt();
if ((val < 0) || (val > MAX_VALUE)) {
System.out.println("Error: NUMBER OUT OF RANGE");
System.out.println("Please insert a valid number");
}
} while ((val < 0) || (val > MAX_VALUE));
// Now we're sure that val contains a valid number
if (val < min) {
second_min = min;
min = val;
} else if (val < second_min) {
second_min = val;
}
if (val > max) {
second_max = max;
max = val;
} else if (val > second_max) {
second_max = val;
}
}
in.close();
System.out.print("Min (in Spanish):\t");
if (min == 0) {
System.out.println("Zero");
} else {
System.out.println(convertNumberToWordsSpanish(min));
}
System.out.println("Second smallest number: " + second_min);
System.out.println("Second highest number: " + second_max);
System.out.print("Max (in Tagalog):\t");
if (max == 0) { // Keep in mind that the user could input N zeros
System.out.println("Zero");
} else {
System.out.println(convertNumberToWordsTagalog(max));
}
}
If you need to store the numbers into an array, you could remove the code for searching min and max, and use Arrays.sort() so
final int min = array[0];
final int second_min = array[1];
final int second_max = array[n-2];
final int max = array[n-1];

How to understand why this does not return the minimum value?

Please help to understand why, in the following, I didn't get output of minimum value in array. Using scanner for input value, the program should output also the minimum number.
** without using .sort.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);
}
}
I will suggest two improvements at the bare minimum.
Initialize your min to the first value. Right now you have min initialized to 0 and user never enters any number smaller than 0. That's why you keep getting 0 for min.
Don't run your loops 1000 times. Run it as many times as there are non zero elements.
See the following working snippet:
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
min = value;
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length && list[i] !=0; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);

Check the sum of array must be less than maximum time [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Check if the sum of array is less than maximum time and if yes then the generator of the random numbers will stop and the output will be like this:
No of customer = 3
max time = 4;
customer 1 = 3
customer 2 = 1
total time = 4
//so the customer 3 a
class CstplangsBadango
package cstplangsbadango;
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class CstplangsBadango {
static int customer = 0;
static int maxTime = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rand = new Random();
System.out.print("Enter number of customer: ");
customer = sc.nextInt();
System.out.print("Enter number of Maximum time: ");
maxTime = sc.nextInt();
System.out.println(" ");
int[] cust = new int[customer];
int j = 0;
int sum = 0;
int sum1 = 0;
int chu = 0;
for (int i = 0; i < cust.length; i++) {
cust[i] = (int) randomFill();
j += 1;
sum += cust[i];
System.out.println("Customer #" + j + " = " + cust[i]);
}
System.out.println(" ");
System.out.println("Maximum time: " + sum);
}
public static double randomFill() {
Random rand = new Random();
int randomNum = rand.nextInt(3) + 1;
return randomNum;
}
}
for (int i = 0; i < cust.length; i++) {
cust[i] = (int) randomFill();
}
for (int i = 0; i < cust.length; i++) {
int newSum = sum + cust[i];
if (sum < maxTime) {
sum = newSum;
} else if(sum == maxTime) {
sum = newSum;
break;
} else {
break;
}
j++;
System.out.println("Customer #" + j + " = " + cust[i]);
}
you must exclude your statement
j+=1;
sum += cust[i];
System.out.println("Customer #" + j + " = " + cust[i])
and create another loop below your created loop when you fill your array
for(int i=0;i<cust.length;++i)
{
j+=1;
sum+=cust[i];
if(sum>=MAX_TIME)
{
i=cust.length;
System.out.println("Customer #" + j + " = " + cust[i]);
}
}
if(sum>MAX_TIME)
{
int subtractor=sum-MAX_TIME;
sum-=subtractor;
}

Find largest and smallest numbers number using Arrays

Trying to let users enter number of integers so I can set array length then find the max and min value. However, I can't find max and min. Please help.
import java.util.Scanner;
import java.util.Arrays;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
System.out.println("Enter some integers:");
int integers = keyboard.nextInt();
int numbers [] = new int [numberEnter];
int maxValue = numbers[0];
int minValue = numbers[0];
int max = 0;
int min = 0;
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
You don't seem to be entering more then one value (and you never store integers in your array). Also, you aren't setting the min. I think you wanted
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number of integers to enter:");
int numberEnter = keyboard.nextInt();
int numbers[] = new int[numberEnter];
int pos = 0;
do {
System.out.printf("Please enter integer #%d/%d:%n", pos, numberEnter);
numbers[pos++] = keyboard.nextInt();
} while (pos < numberEnter && keyboard.hasNextInt());
int min = numbers[0];
int max = numbers[0];
for (pos = 1; pos < numbers.length; pos++) {
if (numbers[pos] < min) { // <-- test min.
min = numbers[pos];
}
if (numbers[pos] > max) { // <-- test max.
max = numbers[pos];
}
}
// Display everything.
System.out.printf("%s Min: %d Max: %d%n", Arrays.toString(numbers),
min, max);
}
Your numbers[] is empty. The user's input is not stored into the array.
Here is your fixed code:
package com.company;
import java.util.Scanner;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
int numbers [] = new int [numberEnter];
for (int i = 0; i < numberEnter; i++) {
System.out.println("Enter integer:");
numbers[i] = keyboard.nextInt();
}
int maxValue = numbers[0];
int minValue = numbers[0];
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
import java.util.Scanner;
class StdR {
public static void main(String[] args) {
// TODO Auto-generated method stub
StdR st = new StdR();
st.stdR();
//System.out.println(st.stdR();
}
void stdR()
{
char[] grade = {'A','B','C','D','E','F'};
Scanner input = new Scanner(System.in);
byte[] st = new byte[3];
double[] percentage = new double[st.length];
for(byte s = 0; s < st.length; s++){
System.out.println("\nStudent " + s);
short noOfMarks = 0;
short totalMarks = 450;
percentage[s] = 0.0;
byte[] marks = new byte[5];
for (byte i = 0; i < marks.length; i++){
System.out.println("Enter marks of Chapter "+ i + ": ");
marks[i] = input.nextByte();
noOfMarks += marks[i];
percentage[s] += (marks[i] * 100) / totalMarks;
}
System.out.print("No of marks: " + noOfMarks + "\t");
System.out.print("Percentage: " + percentage[s] + "\t");
if (percentage[s] > 79.0 && percentage[s] < 100.1)
System.out.print("Grade: " + grade[0]);
else if (percentage[s] > 69.0 && percentage[s] < 80.0)
System.out.print("Grade: " + grade[1]);
else if (percentage[s] > 59.0 && percentage[s] < 70.0)
System.out.print("Grade: " + grade[2]);
else if (percentage[s] > 49.0 && percentage[s] < 60.0)
System.out.print("Grade: " + grade[3]);
else if (percentage[s] > 39.0 && percentage[s] < 50.0)
System.out.print("Grade: " + grade[4]);
else if (percentage[s] < 40.0)
System.out.print("Grade: " + grade[5]);
}
double smallest = percentage[0] , largest= percentage[0];
for (int i=0 ;i< percentage.length; i++) {
if (percentage[i] < smallest) {
smallest = percentage[i];
} // end finding smallest
if (percentage[i] > largest) {
largest = percentage[i];
}
}
System.out.println("\n1st Position and Top percentage is " + largest);
System.out.println("\nLast Position and Least percentage is "+smallest);
}
}

Categories