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);
}
}
}
Related
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);
}
}
}
}
I am working on Java code. I have a menu, the user selects an option, does something in the option then returns to the menu until the exit is selected. I'm not sure how to get it to go back to the menu.
Here is what I have:
/**
*
* #author Lisa Hergert
*/
import java.util.Scanner;
import java.util.Random;
public class MathTutor {
//Create scanner for user input
Scanner keyboard = new Scanner(System.in);
//Declare variables
int choice;
Random generator = new Random();
public MathTutor () {
choice = 0;
}
public int getQuestionType() {
while (choice < 1 || choice >3) {
System.out.println("Math Tutor");
System.out.println("\t1) Addition problem");
System.out.println("\t2) Subtraction problem");
System.out.println("\t3) Quit");
System.out.println("Enter your choice (1 - 3): ");
choice = keyboard.nextInt();
if (choice < 1 || choice > 3) {
System.out.println("You must choose a number from 1-3");
}
}
return choice;
}
public void askQuestions () {
for (int i = 0; i < 4; i++) {
int num1 = genRandomNum();
int num2 = genRandomNum();
int max = choice;
if (max == 3) {
max = (int)(Math.random() * 3 + 1);
}
switch (max) {
case 1: addition(num1, num2);
break;
case 2: subtraction(num1, num2);
break;
default: System.out.println("Error");
System.exit(1);
}
}
}
public int genRandomNum() {
return (int)generator.nextInt(1000);
}
public void addition(int num1, int num2) {
if (num1 > num2) {
System.out.printf("%5d\n", num1);
System.out.printf("+ %3d\n", num2);
System.out.println("-------");
} else {
System.out.printf("%5d\n", num2);
System.out.printf("+ %3d\n", num1);
System.out.println("-------");
}
int sum = num1 + num2;
int answer = keyboard.nextInt();
if (num1 + num2 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + sum);
}
}
public void subtraction (int num1, int num2) {
if (num1 > num2) {
System.out.printf("%5d\n", num1);
System.out.printf("- %3d\n", num2);
System.out.println("-------");
int diff = num1 - num2;
int answer = keyboard.nextInt();
if (num1 - num2 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + diff);
}
} else {
System.out.printf("%5d\n", num2);
System.out.printf("- %3d\n", num1);
System.out.println("-------");
int diff = num2 - num1;
int answer = keyboard.nextInt();
if (num2 - num1 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + diff);
}
}
}
public static void main(String[] args) {
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
tutor.askQuestions();
return;
}
}
Maybe I'm missing something but can't you just loop all the functionality?
public static void main(String[] args) {
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
while(choice != 3) {
tutor.askQuestions();
choice = tutor.getQuestionType();
}
return;
}
import java.util.Scanner;
import java.util.Random;
/**
*
* #author Lisa Hergert
*/
public class MathTutor {
//Create scanner for user input
Scanner keyboard = new Scanner(System.in);
//Declare variables
int choice;
Random generator = new Random();
public MathTutor () {
choice = 0;
}
public int getQuestionType() {
while (choice < 1 || choice >3) {
System.out.println("Math Tutor");
System.out.println("\t1) Addition problem");
System.out.println("\t2) Subtraction problem");
System.out.println("\t3) Quit");
System.out.println("Enter your choice (1 - 3): ");
choice = keyboard.nextInt();
if (choice < 1 || choice > 3) {
System.out.println("You must choose a number from 1-3");
}
}
return choice;
}
public void askQuestions () {
int num1 = genRandomNum();
int num2 = genRandomNum();
int max = choice;
if (max == 3) {
max = (int)(Math.random() * 3+3);
}
switch (max) {
case 1: addition(num1, num2);
break;
case 2: subtraction(num1, num2);
break;
default: System.out.println("Thank you for your time.");
System.exit(1);
}
}
public int genRandomNum() {
return (int)generator.nextInt(1000);
}
public void addition(int num1, int num2) {
if (num1 > num2) {
System.out.printf("%5d\n", num1);
System.out.printf("+ %3d\n", num2);
System.out.println("-------");
} else {
System.out.printf("%5d\n", num2);
System.out.printf("+ %3d\n", num1);
System.out.println("-------");
}
int sum = num1 + num2;
int answer = keyboard.nextInt();
if (num1 + num2 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + sum);
}
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
tutor.askQuestions();
}
public void subtraction (int num1, int num2) {
if (num1 > num2) {
System.out.printf("%5d\n", num1);
System.out.printf("- %3d\n", num2);
System.out.println("-------");
int diff = num1 - num2;
int answer = keyboard.nextInt();
if (num1 - num2 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + diff);
}
} else {
System.out.printf("%5d\n", num2);
System.out.printf("- %3d\n", num1);
System.out.println("-------");
int diff = num2 - num1;
int answer = keyboard.nextInt();
if (num2 - num1 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + diff);
}
}
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
tutor.askQuestions();
}
public static void main(String[] args) {
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
tutor.askQuestions();
}
}
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;
}
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]);
}
}
This is a program that is supposed to prompt the user to enter three numbers and
then display the largest of these numbers. However, there are logic errors in it. I'm stuck on trying to figure out where this little bugger is. Please use your expertise to lend me a hand. I am a student, so please don't rage on me \:p
import java.util.*;
public class HA8LargestErr {
private int num1;
private int num2;
private int num3;
public HA8LargestErr() {
num1 = 0;
num2 = 0;
num3 = 0;
}
public void getNumsFromUser() {
Scanner input = new Scanner (System.in);
System.out.println("Enter three numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
num3 = input.nextInt();
}
public int returnLargest() {
if (num1 > num2 && num1 > num3)
return num1;
if (num2 > num3 && num2 > num1)
return num2;
return num3;
}
public static void main(String[] args) {
HA8LargestErr data = new HA8LargestErr();
data.getNumsFromUser();
System.out.println ("The largest is : " + data.returnLargest());
}
}
Replace your implementation of returnLargest with
public int returnLargest() {
if (num1 >= num2 && num1 >= num3)
return num1;
if (num2 >= num3)
return num2;
return num3;
}
Or use Math.max as suggested above.
Edit:
You need to use >= instead of > because otherwise num3 will be returned when num1 and num2 are equal and larger than num3.