finding smallest and second smallest number - java

This program is supposed to find the smallest and the second smallest number among x numbers.
The program finds the smallest number every time, but I have problems replacing the second smallest number from the keyboard.
System.out.println("How many numbers?");
int total = keyboard.nextInt();
System.out.println("What is the first number");
int small = keyboard.nextInt();
System.out.println("whats the second number");
int nest = keyboard.nextInt();
// Assigning the first two numbers to smallest and second largest
for (int i =2;i<total;i++) {
System.out.println("whats the next number?");
int number = keyboard.nextInt();
if (number < small) {
small = number;
} // this part works (I think)
if ((number > small) && (number < nest)) {
nest = number;
}//this part dont (I think)
}//end forloop
System.out.printf("The smallest numbers are %d and %d",small,nest);

You just have to get the order right. First, see if the number is smaller than the smallest number, and if so, replace it and move the old smallest number to the second smallest number. Else, if it is smaller than the second smallest number, replace that.
Here's the code that should be in the loop:
if (number < small) {
nest = small;
small = number;
} else if (number < nest) {
nest = number;
}

Add all the numbers to a LinkedList<Integer> then sort the List. The first two items in the List will be the smallest.
public class Sorter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<Integer> numbers = new LinkedList<Integer>();
System.out.println("How many numbers?");
int total = keyboard.nextInt();
System.out.println("What is the first number");
numbers.add( keyboard.nextInt());
System.out.println("whats the second number");
numbers.add( keyboard.nextInt());
// Assigning the first two numbers to smallest and second largest
for (int i =2;i<total;i++) {
System.out.println("whats the next number?");
numbers.add( keyboard.nextInt());
}//end forloop
Collections.sort(numbers);
System.out.printf("The smallest numbers are %d and %d",numbers.get(0),numbers.get(1));
}
}

Related

Problem in code and need a short code to solve problem

fist thing first , the code :
package com.company;
import java.util.Scanner;
public class index {
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
//let a= 2 7 4
int b= a%10;//4
int c=a/10;//27
int d= c%10;//7
int e=c/10;//2
//e=first num;
//d=middle num;
//b= last num ;
// for searching the greatest number
if (d>e && d>b )
System.out.printf(" the greatest number is %d%d%d",d,e,b);
else if(e>d && e>b )
System.out.printf(" the greatest number is %d%d%d",e,d,b);
else if (b>e && b>d )
System.out.printf(" the greatest number is %d%d%d",b,e,d);
// for the smallest number
else if(d<e && d<b && b>e)
System.out.printf(" the smallest number is %d%d%d",b,e,d);
else if(d<e && d<b && e>b)
System.out.printf(" the smallest number is %d%d%d",e,b,d);
else if (e<d && e<b && b>d)
System.out.printf(" the smallest number is %d%d%d",b,d,e);
else if(e<d && e<b && d>b)
System.out.printf(" the smallest number is %d%d%d",d,b,e);
else if (b<e && b<d && e>d)
System.out.printf(" the smallest number is %d%d%d",e,d,b);
else
System.out.printf(" the smallest number is %d%d%d",d,e,b);
}
}
now the problem:
this code is make to take number from the user as the input **of any three digit number ** and change it to the greatest number and smallest number ,
for example:
input number =274
output :
greatest number=742
smallest number=247
the above code is giving the greatest number but not the smallest number and the code is very lengthy ,
my output:
enter any three digit number
546
the greatest number is 654
so please help ,any error in code and if there is any short code then please help
I think that the problem is in the way of solution. As for me that is better to use some array or list and sort it. Something like that
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int[] array = new int[3];
for (int i = 0; i < 3; i++) {
array[i] = a % 10;
a = a / 10;
}
Arrays.sort(array);
int smallest = 0;
int greatest = 0;
for (int i = 0; i < 3; i++) {
smallest += array[i];
if (i != 2) {
smallest *= 10;
}
}
for (int i = 2; i > -1; i--) {
greatest += array[i];
if (i != 0) {
greatest *= 10;
}
}
System.out.println(Arrays.toString(array));
System.out.println(smallest);
System.out.println(greatest);
}
May I suggest a whole different approach?
void printGreatestAndSmallest(int number) {
char[] digits = String.valueOf(number).toCharArray();
Arrays.sort(digits);
String smallest = new String(digits);
String greatest = new StringBuilder(smallest).reverse().toString();
System.out.println("Greatest number is " + greatest);
System.out.println("Smallest number is " + smallest);
}
What happens here, is that we convert the digits to a char[], which can be sorted using Arrays.sort(...). This way, the smallest digit comes in front, the largest at the end. The char[] is converted back to a string with the String(char[]) constructor.
That is the smallest value. The largest value is the reverse of it! We can get the largest number using StringBuilder's reverse() method.
Note that this code cannot handle negative numbers.
The problem with your current approach is that it contains a lot of repetitions, and is not quite flexible; it is bound to an input of exactly three digits.
In order to fix the issue your are facing, remove the else keyword from the line else if(d<e && d<b && b>e). Each if-elseif-else statement only executes a single branch, but you need two branches to be executed, one for the smallest number, and one for the greatest number.
Further:
Use descriptive variable names. You have a comment in your code:
//e=first num;
//d=middle num;
//b= last num ;
but why don't you rename e, d and b to firstDigit, middleDigit and lastDigit respectively?
Follow the Java Naming Conventions. Variable and method names are written in camelCase, and class names in PascalCase. So class index should be class Index. Also make sure to rename index.java to Index.java.
You are defining variables with almost the same function: in your case firstNum, middleNum and lastNum. They all allow to store a specific digit of the input number. In such a case, you should use an array instead of separate variables. Loops work well with arrays.
If your code somehow iterates over all possible permutations of some collection, using if-else statements, that is probably not the best way.
For example:
if (d>e && d>b )
else if(e>d && e>b )
else if (b>e && b>d )
You should ask yourself: should these digits be in a certain order? The answer here is yes, they need to be sorted from low to high (and high to low). In that case, you probably want to sort them.

Find a maximum and minimum value using for loop

I am trying to take 10 integers from the user's input and find the minimum and maximum using for loop. But my final print statement just prints the list of numbers entered. I'm lost.
public static void main(String[]args) {
Scanner scan=new Scanner(System.in);
double a = 0;
double max = 0;
double min = 0;
System.out.print("Enter ten floating points: \n");
for(a=0; a <10; a++) {
a=scan.nextDouble();
if(a == 0) {
min=a;
max=a;
}
else if(a < min) {
min=a;
}
else if (a > max){
max=a;
}
}
System.out.println("Minimum value: " +min);
System.out.println("Maximum value: " +max);
}
Issue is in your for loop change it to
for (int x = 0; x < 10; x++) {
there is another issue, you need to change
if(a == 0){
To
if (x == 0) {
Try this
Scanner scan=new Scanner(System.in);
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
for( int i=0; i<10 && scan.hasNextInt(); i++ ) {
int next = scan.nextInt();
maximum = Math.max( next, maximum);
minimum = Math.min( next, minimum);
}
System.out.println("Found maximum :"+maximum+", minimum:"+minimum);
scan.close();
First, we create the scanner.
Next, we set a value for your maximum - since integers can be negative, we can not use 0, but have to use the smallest possible integer.
Same for minimum.
In the for loop, we have to make sure that we terminate the loop after 10 iterations, or if the input stream does not have any more int's.
Next, we use the mathematical function max to find out which number is largest - the previously found maximum, or the next int from the Scanner.
And same for minimum.
Finally, remeber to close the Scanner, to avoid resource leakage.
First your code should not run correctly since you use the same variable a as the counter and as the variable to store user input. You should use two different variable.
Second declare your variable that store the input from user inside the loop, otherwise it may keep the value from the previous loop.
Third your if(a == 0) condition will reset min and max when the user enter the number 0. Which is not what you want.
Finally you should not initialize max/min like that. By defining min as 0, if the user enter only positive number the min will be 0 but the user never entered 0. You instead initialize them at the first entry from user.
This should look like this :
public static void main(String[]args) {
Scanner scan=new Scanner(System.in);
System.out.print("Enter ten floating points: \n");
double tmp = scan.nextDouble(); //read first number from user
double max = tmp; //intialize with the first input
double min = tmp;
for(int i=0; i <9; i++) { //from 0 to 8, 9 numbers since the first has already been read
double a = scan.nextDouble(); //at every loop read a number from the input
if(a < min) {
min=a;
}
//removed else since max and min are independant
if (a > max) {
max=a;
}
}
System.out.println("Minimum value: " +min);
System.out.println("Maximum value: " +max);
}

Smallest and largest number array using index?

I am creating a program that asks the user for ten numbers, then outputs the smallest and largest number. This is my code:
import java.util.Scanner; // program uses Scanner
public class ArrayTester {
// begin execution
public static void main(String[] args) {
// declare and create array object
// declare smallest and largest int variables
int[] numbers;
numbers = new int[10];
int smallest = numbers[0], largest = numbers[0];
// create Scanner object
Scanner input = new Scanner(System.in);
// prompt user
System.out.print("Please enter 10 numbers: \n");
// use for loop to obtain user input
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
// enhanced for loop to find largest and smallest values
for (int i : numbers) {
if (i < smallest) {
smallest = i;
} // end finding smallest
else if (i > largest) {
largest = i;
} // end finding largest number
} // end finding largest and smallest values
// for loop to print user input
System.out.printf("%s%8s\n", "Index", "Input");
for (int counter = 0; counter < numbers.length; counter++) {
System.out.printf("%5d%8d\n", counter, numbers[counter]);
} // end printing input values
// print smallest and largest numbers
System.out.printf("Smallest number: %d\nLargest number: %d\n", smallest, largest);
} // end main
} // end ArrayTester
The problem I am having is when the numbers output, it's giving me 0 as the smallest and 9 as the largest. I know this is because of the 10 number array but how would it be fixed to show the smallest integer and largest integer?
numbers = new int[10];
The above statement initialises the array with all 0s, since you are assigning numbers[0] to smallest, it will always be 0.
Also, another way of achieveing this would be by using Java 8's stream, e.g.:
int[] array = new int[] {1,2,3,10,0};
IntSummaryStatistics summaryStatistics = Arrays.stream(array).summaryStatistics();
System.out.println(summaryStatistics.getMax());
System.out.println(summaryStatistics.getMin());
Put this line:
int smallest = numbers[0], largest = numbers[0];
Below this line:
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
You're initializing "smallest" to 0, because your array doesn't have any values yet. Unless the user puts in a negative number, smallest will always be zero.

Issue in displaying correct largest and smallest numbers

i'm very new to programming, and am attempting to create a program that will allow me to enter several integers and a separate one to quit, and upon quitting will return with the largest and smallest numbers. Everything works well except when displaying the largest and smallest numbers it only displays the quit integer, in this case -99. Here is my code, any help would be great.
import java.util.Scanner;
public class LargestSmallest
{
public static void main(String [] args)
{
//identifier declarations
int number;
int numberend = -99;
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
//create a Scanner object to read from the keyboard & input
Scanner keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//display prompts and get input
System.out.println("Enter an integer, or -99 to quit:");
number = keyboard.nextInt();
if (number == -99){
System.out.println("You did not enter any numbers.");
}else{
//loop
while ((number = input.nextInt()) != -99) {
System.out.println("Enter an integer, or -99 to quit:");
}
}
//largest & smallest
{
if (number > largest)
largest = number;
if (number < smallest)
smallest = number;
System.out.println("Largest:" + largest);
System.out.println("Smallest:" + smallest);
}
}
}
Your code is not keeping track of the current largest and smallest numbers as they are entered in. Please see the modifications below:-
public static void main(String[] args) {
//identifier declarations
int number;
int numberend = -99;
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
//create a Scanner object to read from input
Scanner input = new Scanner(System.in);
//display prompts and get input
System.out.println("Enter an integer, or -99 to quit:");
while ((number = input.nextInt()) != numberend) {
System.out.println("Enter an integer, or -99 to quit:");
if (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
}
//largest & smallest
System.out.println("Largest:" + largest);
System.out.println("Smallest:" + smallest);
}
When inside your loop, you only save the last entered number in number. To exit the loop you must enter -99 which also makes that the only number you have saved. Therefore, in your code, number will always be -99. -99 is both larger than your largest (INTEGER.MIN_VALUE) and smaller than your smallest (INTEGER.MAX_VALUE) so this is why -99 is printed.
To solve this, you can use two variables to save the current largest and current smallest number.
You can also solve this by using a list instead. Save all the inputs in the loop in some kind of list like ArrayList. Then, when the user has entered -99, you must examine the list to find the largest and smallest number. This is not an optimal solution, but may help you understand what is happening.

Sum of Digits in Java

import java.util.Scanner;
public class CubesSum {
public static void main (String [] args){
int input;
System.out.println("Enter a positive integer:");
Scanner in = new Scanner(System.in);
input = in.nextInt();
int number = input; //number is a temp variable
int sum = 0;
while(number>0){
int t= number%10;
sum += t*t*t;
number = number/10;
}
System.out.println("The sum of the cubes of the digits is:" +sum);
}
}
Okay so I'm using a while loop. For part B which is to modify to determine what integers of two, three, and four digits are equal to the sum of the cubes of their digits. So for example, 371 = 3³+7³+1³. Can someone tell me how to do it? I need to wrap a for loop around my while loop...
Take the part of your code that computes the sum of the cubes of the digits of a number, and make that a function:
int sumOfCubedDigits(int number) {
int sum = 0;
// compute sum from number
return sum;
}
Then, loop through all the 2-to-4 digit numbers and check whether they equal the sum of the cubes of their digits:
for (int n = 10; n < 10000; n++) {
if (n == sumOfCubedDigits(n)) {
// do whatever with n
}
}
You could keep the sum-of-cubed-digits computation inside the for loop if you want, but it'd be a bit less readable.
Okay, so it looks like you haven't learned about function definitions yet. I shouldn't have assumed. Let's do it with a nested loop, then.
As you said, you need to wrap a for loop around your while. We need to consider all 2-to-4 digit numbers, so our loop will start at the first 2-digit number and end when it reaches the first 5-digit number:
for (int n = 10; n < 10000; n++) {
// More code will go here.
}
Inside the loop, we need to compute the sum of the cubed digits of n. The code you wrote earlier to compute that modifies the number it's operating on, but we can't modify n, or we'll screw up the for loop. We make a copy:
for (int n = 10; n < 10000; n++) {
int temp = n;
int sum = 0;
// Compute the sum of the digits of temp, much like you did before.
}
Finally, if the sum is equal to n, we do something to indicate it. Let's say your assignment said to print all such numbers:
for (int n = 10; n < 10000; n++) {
int temp = n;
int sum = 0;
// Compute the sum of the digits of temp, much like you did before.
if (sum == n) {
System.out.println(n);
}
}
For an arbitrary integer i, it's nth digit dn is, (being n=1 the rightmost digit)
dn = (i % (10^n)) / (10^(n-1)) // all integer operations
as you can see, you'll need to know beforehand the number of digits of your i, otherwise, yes, you'll need a loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter number : ");
int num = input.nextInt();
int temp = num, remainder;
int sum = 0;
while(temp %10 != 0){
remainder = temp %10;
sum = sum+ remainder ;
temp = temp/10;
}
System.out.println("Sum of digit : " + sum);
=====OUTPUT====
Please enter number : 123
Sum of digit : 6

Categories

Resources