Can't sort 3 floating point numbers in Java - java

I am wring program that sorts three integers. But I am not getting result for the input {1,3,2}. Probably some logic mistake in the 4th if statement.
The numbers are taken as input.
// program to sorting 3 double.
import java.util.*;
public class Sorting {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input the numbers for sorting");
double num1 = in.nextDouble();
double num2 = in.nextDouble();
double num3 = in.nextDouble();
double a = 0;
double b = 0;
double c = 0;
if ((num1 > num2) && (num2 > num3)) {
a = num1;
b = num2;
c = num3;
}
if ((num1 > num2) && (num3 > num2)) {
a = num1;
b = num3;
c = num2;
}
if ((num2 > num1) && (num1 > num3)) {
a = num2;
b = num1;
c = num3;
}
if ((num2 > num1) && (num3 > num1)) {
a = num2;
b = num3;
c = num1;
}
if ((num3 > num1) && (num1 > num2)) {
a = num3;
b = num1;
c = num2;
}
if ((num3 > num1) && (num2 > num1)) {
a = num3;
b = num2;
c = num1;
}
System.out.println(" The numbers are in" + c + "< " + b + "< " + a);
}
}

If you are happy with an array, you may use the Arrays.sort() method:
double[] numbers = new double[] { num1, num2, num3 };
Arrays.sort(numbers);
System.out.println("The numbers are " + Arrays.toString(numbers));
Given input 1 3 2 this prints The numbers are [1.0, 2.0, 3.0].

I would do it with arrays. Example :
class DoubleSorter {
public double[] sorted;
public boolean[] deleted;
public int array_position=0;
public int element_to_delete=0;
public DoubleSorter() {
}
public void self_calling_sorter(double[] numbers) {
double bestnum=0;
boolean finished=true;
for (int i=0; i < numbers.length; i++) {
if (deleted[i] == false) {
if (finished==true) { //First set to bestnum
bestnum=numbers[i];
element_to_delete=i;
finished=false;
}
else {
if (numbers[i] >= bestnum) {
bestnum=numbers[i];
element_to_delete=i;
}
}
}
}
deleted[element_to_delete]=true;
if (finished==false) {
sorted[array_position]=bestnum;
array_position++;
self_calling_sorter(numbers);
}
}
public double[] sort(double[] numbers) {
sorted=new double[numbers.length];
deleted=new boolean[numbers.length];
for (int i=0; i < numbers.length; i++) {
deleted[i]=false;
}
self_calling_sorter(numbers);
return sorted;
}
}
This function takes an array, looks for the biggest element, writes it down, sets it to null, calls itself, looks for the biggest element, excludes the taken, because they were set to null, writes the biggest number again...
Example of how it works :
numbers={1,3,2};
result={null,null,null};
First sorting :
result={3,null,null};
numbers={1,null,2};
Second sorting :
result={3,2,null};
numbers={1,null,null};
Third sorting :
result={3,2,1};
numbers={null,null,null};
A fourt sorting isnt executed because it notices that bestnum is null because it couldnt be set.
This function is more flexible and can sort a almost infinite amount of numbers much easier.
And here is how I would integrate it in your code :
import java.util.*;
public class Sorting {
public static void main(String[] args) {
DoubleSorter sorter=new DoubleSorter();
Scanner in = new Scanner(System.in);
System.out.println("How many numbers would you like to sort ?");
int count = in.nextInt();
double[] numbers=new double[count];
for (int i=0; i < count; i++) {
System.out.println("Number "+Integer.toString(i));
numbers[i]=in.nextDouble();
}
System.out.println("The sorted list is : "+Arrays.toString(sorter.sort(numbers)));
}
}
EDIT :
I saw this and realized that you'd probably like to sort them the other way round.
System.out.println(" The numbers are in" + c + "< " + b + "< " + a);
Then you'll only have to change this :
if (numbers[i] >= bestnum) {
bestnum=numbers[i];
element_to_delete=i;
}
to this :
if (numbers[i] <= bestnum) {
bestnum=numbers[i];
element_to_delete=i;
}

Related

Factorial Calculator

How can I make the program to perform a new or repeat the operation or ask the user to input again a number and know the factorial of it.
import java.util.Scanner;
public class Loops {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int num, num2 = 1, x, i;
System.out.println("-------------Factorial Calculator-------------");
System.out.print("Enter a positive integer: ");
num = input.nextInt();
if (num > 0) {
System.out.print(num + "! = ");
for (i = 1; i <= num; i++) {
if(i < num){
System.out.print(i + " x ");
num2 = num2 * i;
}
if(i == num){
System.out.print(i);
num2 = num2 * i;
System.out.println("\nThe factorial of " + num + " is " + num2);
System.out.println();
}
}
}else if (num < 0) {
System.out.println("Please input a valid integer. Program stopped.");
}
}
}
Put the code that computes the factorial in a separate method and call it from within a loop in main().
import java.util.Scanner;
public class Loops {
public static void printFactorial(int num) {
int i = 0;
int num2 = 0;
if (num > 0) {
System.out.print(num + "! = ");
for (i = 1; i <= num; i++) {
if(i < num){
System.out.print(i + " x ");
num2 = num2 * i;
}
if(i == num){
System.out.print(i);
num2 = num2 * i;
System.out.println("\nThe factorial of " + num + " is " + num2);
System.out.println();
}
}
}else if (num < 0) {
System.out.println("Please input a valid integer. Program stopped.");
System.exit(0);
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int num = 0;
System.out.println("-------------Factorial Calculator-------------");
while ( true ) {
System.out.print("Enter a positive integer: ");
num = input.nextInt();
printFactorial(num);
}
}
}
Use a while loop
import java.util.Scanner;
public class Loops {
static boolean readInput = true;
public static void main(String[] args) {
while(readInput) calculateFactorial();
}
}
private static void calculateFactorial() {
Scanner input = new Scanner(System.in);
int num, num2 = 1, x, i;
System.out.println("-------------Factorial Calculator-------------");
System.out.print("Enter a positive integer: ");
num = input.nextInt();
if(num <= 0) {
readInput = false;
return;
}
if (num > 0) {
System.out.print(num + "! = ");
for (i = 1; i <= num; i++) {
if(i < num){
System.out.print(i + " x ");
num2 = num2 * i;
}
if(i == num){
System.out.print(i);
num2 = num2 * i;
System.out.println("\nThe factorial of " + num + " is " + num2);
System.out.println();
}
}
}else if (num < 0) {
System.out.println("Please input a valid integer. Program stopped.");
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean runMore = true;
while(runMore){
int num, num2 = 1, x, i;
System.out.println("-------------Factorial Calculator-------------");
System.out.print("Enter a positive integer: ");
num = input.nextInt();
if (num > 0) {
System.out.print(num + "! = ");
for (i = 1; i <= num; i++) {
if(i < num){
System.out.print(i + " x ");
num2 = num2 * i;
}
if(i == num){
System.out.print(i);
num2 = num2 * i;
System.out.println("\nThe factorial of " + num + " is " + num2);
System.out.println();
}
}
}else if (num < 0) {
System.out.println("Please input a valid integer. Program stopped.");
}
System.out.println("Want to contine : Enter '1' for yes and '0' for no");
int wantToContinue = input.nextInt();
if(wantToContinue==0){
runMore = false;
}
}
}
}
use while loop when user not typing a positif number :
System.out.print("Enter a positive integer: ");
num = input.nextInt();
while(num<0) {
System.out.println("Please input a valid integer. Program stopped.");
num = input.nextInt();
}
code :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num, num2 = 1, x, i;
System.out.println("-------------Factorial Calculator-------------");
System.out.print("Enter a positive integer: ");
num = input.nextInt();
input.nextLine();
while (num < 0) {
System.out.println("Please input a valid integer. Program stopped.");
System.out.print("Enter a positive integer: ");
num = input.nextInt();
}
if (num > 0) {
System.out.print(num + "! = ");
for (i = 1; i <= num; i++) {
if (i < num) {
System.out.print(i + " x ");
num2 = num2 * i;
}
if (i == num) {
System.out.print(i);
num2 = num2 * i;
System.out.println("\nThe factorial of " + num + " is " + num2);
System.out.println();
}
}
}
}
}
import java.util.Scanner;
public class FactorialCalculator1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println("<------Factorial Calculator------>");
while ( true ) {
System.out.print("Enter a positive integer: ");
num = input.nextInt();
boolean runMore = true;
int i;
int num2 = 1;
if (num > 0) {
System.out.print(num + "! = ");
for (i = 1; i <= num; i++) {
if(i < num){
System.out.print(i + " x ");
num2 = num2 * i;
}
if(i == num){
System.out.print(i);
num2 = num2 * i;
System.out.println("\nThe factorial of " + num + " is: " + num2);
System.out.println();
}
}
}else if (num < 0) {
System.out.println("Invalid input! Program stopped!");
System.exit(0);
}
}
}
}

How to find factorial and show result of counting in console?

public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+"!="+factorial(n));
}
public static int factorial(int num) {
return (num == 0) ? 1 : num * factorial (num - 1);
}
}
how make this code to text in console 3! = 1*2*3 = 6?
Don't use recursion for this. Besides, it isn't really efficient or necessary.
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int fact = 1;
String s = n + "! = 1";
for (int i = 2; i <= n; i++) {
fact *= i;
s += "*" + i;
}
s += " = ";
System.out.println(s + fact);
There can be many ways to do it e.g. you can build the required string or print the trail while calculating the factorial. In the following example, I have done the former.
As an aside, you should check the input whether it is a positive integer.
import java.util.Scanner;
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = in.nextInt();
if (n >= 0) {
StringBuilder strFact = new StringBuilder();
int fact = factorial(n, strFact);
if (strFact.length() > 0) {
// Delete the last '*'
strFact.deleteCharAt(strFact.length() - 1);
System.out.println(n + "!= " + strFact + " = " + fact);
} else {
System.out.println(n + "!= " + fact);
}
} else {
System.out.println("This is an invalid input.");
}
}
public static int factorial(int num, StringBuilder strFact) {
int fact;
if (num == 0) {
fact = 1;
} else {
fact = num * factorial(num - 1, strFact);
strFact.append(num + "*");
}
return fact;
}
}
A sample run:
Enter an integer: 3
3!= 1*2*3 = 6

Finding the smallest, largest, and middle values in Java

I did with this code. Is it correct way? I want to sort the numbers in ascending order. Is there better way for this?
import java.lang.Math;
public class Numbers
{
public static void main(String[] args)
{
int a=1;
int b=2;
int c=3;
if (a<b && a<c)
System.out.println("Smallest: a");
else if (a>b && a>c)
System.out.println("Biggest: a");
else if (a>b && a<c)
System.out.println("Mid: a");
else if (a<b && a>c)
System.out.println("Mid: a");
if (b<c && b<a)
System.out.println("Smallest: b");
else if (b>c && b>a)
System.out.println("Biggest: b");
else if (b>c && b<a)
System.out.println("Mid: b");
else if (b<c && b>a)
System.out.println("Mid: b");
if (c<a && c<b)
System.out.println("Smallest: c");
else if (c>a && c>b)
System.out.println("Biggest: c");
else if (c>a && c<b)
System.out.println("Mid: c");
else if (c<a && c>b)
System.out.println("Mid: c");
}
}
Expanding on Steve's answer (I assume you are new to Java and need a more complete example):
import java.util.Arrays;
public class Numbers
{
public static void main(String[] args)
{
int a=3;
int b=2;
int c=1;
int[] numbers = {a,b,c};
Arrays.sort(numbers);
System.out.println("The highest number is "+numbers[2]);
System.out.println("The middle number is "+numbers[1]);
System.out.println("The lowest number is "+numbers[0]);
}
}
You can store the three numbers in an array and then do
Arrays.sort(numbers);
/* numbers[0] will contain your minimum
* numbers[1] will contain the middle value
* numbers[2] will contain your maximum
*/
That's all!
In general it would be best to use a loop and a array for this type of thing that way if you have more than 3 numbers it will still work. Also you wont have to type nearly as much. Try something like this for finding the smallest number.
MyArray = new int[3];
MyArray[0] = 1;
MyArray[1] = 2;
MyArray[2] = 3;
int temp = a;
for (int i = 0; i < (number of numbers to check in this case 3); i++){
if (MyArray[i] < temp){
temp = MyArray[i];
}
}
System.out.println("Smallest number is: " + temp);
import java.util.Scanner;
public class SortingIntegers {
public static void main (String[] args){
int num1;
int num2;
int num3;
int largerstNum;
int smallestNum;
int middleNum;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the First Integer");
num1 = sc.nextInt();
System.out.println("Pleas enter the Second Integer");
num2 = sc.nextInt();
System.out.println("Please enter the third Integer");
num3 = sc.nextInt();
if (num1 > num2){
if (num1 > num3){
largerstNum = num1;
if (num2 > num3){
middleNum = num2;
smallestNum = num3;
}else {
middleNum = num3;
smallestNum = num2;
}
}
}else {
if (num1 > num3){
middleNum = num1;
if (num2 > num3){
largerstNum = num2;
smallestNum = num3;
}else {
largerstNum = num3;
smallestNum = num2;
}
}else {
smallestNum =num1;
if (num2 > num3){
largerstNum = num2;
middleNum = num3;
}else {
largerstNum = num3;
middleNum = num2;
}
}
System.out.println("Highest Number is : " + largerstNum);
System.out.println("Smallest Number is : " + smallestNum);
System.out.println("Middle Number is : " + middleNum);
}
}
}

How to modify this code to print the 3 integers in order?

I have a code that prints the biggest integer between 3 integers and I want to sort these 3 integers (like num < num1 < num2).
I want to modify my code to achieve this, how can I do it?
import java.util.Scanner;
public class digits {
public static void main(String[] args) {
int num = 0;
int num1 = 0;
int num2 = 0;
int big = 0;
System.out.println("Please insert 3 numbers: ");
Scanner number = new Scanner(System.in);
if (number.hasNextInt()) {
num = number.nextInt();
big = num;
}
if (number.hasNextInt()) {
num1 = number.nextInt();
if (num1 > num) {
big = num1;
}
}
if (number.hasNextInt()) {
num2 = number.nextInt();
if (num2 > num && num2 > num1) {
big = num2;
}
System.out.println(big + ">" + num1 + ">" + num);
} else {
System.out.println("Error: Invalid Value.");
}
}
}
Try below code
public static void main(String[] args) {
System.out.println("Please insert 3 numbers: ");
Scanner number = new Scanner(System.in);
Integer[] input = new Integer[3];
int i = 0;
while (i != 3) {
input[i++] = number.nextInt();
}
number.close();
Arrays.sort(input, Collections.reverseOrder());
StringBuffer sb = new StringBuffer();
for (Integer a : input) {
sb.append(a).append(">");
}
System.out.println(sb.substring(0, sb.length() - 1));
}
if(num1>num)
{
big=num1;
}
Change this to:
if(num1>num)
{
big=num1;
}
else
{
// swap num1 and num
int tmp = num;
num = num1;
num1 = num;
}
Also change
if(num2>num && num2>num1)
{
big=num2;
}
to
if(num2>num1)
{
big=num2;
}
else
{
// num1 is largest, so swap num1 and num2
int tmp = num1;
num1 = num2;
num2 = tmp;
if(num > num1){
//swap num and num1
int t = num1;
num1 = num;
num = t;
}
}
Look at your code: you're choosing the biggest of the three numbers (big), but you never change num1 or num.
So, your result will always be: greater number>second value from System.in>third value from System.in.
In other words, you're sorting only the higher value.
Something like this should work
import java.util.Scanner;
public class digits {
public static void main(String[] args)
{
int[] nums = new int[3];
int k = 0;
System.out.println("Please insert 3 numbers: ");
Scanner number = new Scanner (System.in);
while (number.hasNext() && k < 3) {
int i = 0;
try {
i = Integer.parseInt(number.nextLine());
}
catch (NumberFormatException e) {
System.out.println("Error: Invalid Value.");
}
nums[k] = i;
k++;
}
Arrays.sort(nums);
System.out.println(nums[2]+ ">" +nums[1]+ ">" +nums[0]);
}
}

Amicable numbers Java program

So I am having this strange output in which only the first number is checked twice while the second number is not even considered.Please help.
Code :-
import java.util.Scanner;
public class Amicable
{
private static int a,b;
private static String m,n;
public static void main()
{
acceptNumbers();
if (firstNumber() == secondNumber())
{
System.out.println(a+" and "+b+" are amicable numbers");
}
else System.out.println(a+" and "+b+" are not amicable numbers");
}
public static void acceptNumbers()
{
Scanner sc = new Scanner(System.in);
int count=0;
System.out.print("Enter two numbers [ separated by a ',' ] : ");
String input = sc.nextLine();
System.out.println();
for (int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
if (c == ',')
{
count++;
if (count == 1)
{
m = input.substring(0,i);
n = input.substring(0,i);
}
break;
}
}
if (count == 0)
{
System.out.println("Invalid operation : You have entered only 1 number");
}
m = m.trim(); n = n.trim();
a = Integer.valueOf(m);
b = Integer.valueOf(n);
}
public static int firstNumber()
{
int a1,a2=0;
for (int i = 0; i < m.length()-1; i++)
{
a1 = Integer.valueOf(m.charAt(i));
if (a%a1 == 0) a2 = a2+a1;
}
return a2;
}
public static int secondNumber()
{
int b1,b2=0;
for (int i = 0; i < n.length()-1; i++)
{
b1 = Integer.valueOf(n.charAt(i));
if (b%b1 == 0) b2 = b2+b1;
}
return b2;
}
}
And here is the output :-
Enter 2 numbers [ separated by a ',' ] : 248 , 222
248 and 248 are amicable numbers
your m and n are equal, because you have:
m = input.substring(0,i);
n = input.substring(0,i);
change it to:
m = input.substring(0,i);
n = input.substring(i+1);
Btw you are doing a lot of unnecessary stuff, complete solution (I don't care about exceptions):
import java.util.Scanner;
public class Amicable {
public static void main(String args[]) {
try {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers [ separated by a ',' ] : ");
String input = sc.nextLine();
String[] numbers = input.split(",");
int num1 = Integer.parseInt(numbers[0].trim());
int num2 = Integer.parseInt(numbers[1].trim());
int sum1 = 0, sum2 = 0;
for (int i = 1; i <= num1; i++) {
if (num1 % i == 0)
sum1 += i;
}
for (int i = 1; i <= num2; i++) {
if (num2 % i == 0)
sum2 += i;
}
if (sum1 == sum2)
System.out.println(num1 + " and " + num2
+ " are amicable numbers");
else
System.out.println(num1 + " and " + num2
+ " are not amicable numbers");
} catch (Exception e) {
e.printStackTrace();
}
}
}
parts of code from: http://www.daniweb.com/software-development/java/code/304600/amicable-numbers
a and b are derived from m and n, and the latter are initialized to exactly the same value:
m = input.substring(0,i);
n = input.substring(0,i);
Did you mean to set n to
n = input.substring(i+1);
?
m = input.substring(0,i);
n = input.substring(0,i);
m and n are having the same value.
n should be:
n = input.substring(i+1);
And now the second number will be assigned to n.

Categories