How does number swapping work with if statements? - java

I want to know exactly how these if statements are switching the numbers. I have never been asked to do non-descending order before so I took a little snip off the internet.
import java.util.Scanner;
/**
* Created by Nicholas on 10/26/2015.
*/
public class Main {
final static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please enter three numbers.");
System.out.println();
System.out.print("Number 1: ");
int num1 = userInput.nextInt();
System.out.println();
System.out.print("Number 2: ");
int num2 = userInput.nextInt();
System.out.println();
System.out.print("Number 3: ");
int num3 = userInput.nextInt();
System.out.println();
if (num1 > num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
if (num2 > num3) {
int temp = num2;
num2 = num3;
num3 = temp;
}
if (num1 > num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
System.out.print("The numbers in non-descending order are, " + num1 + " " + num2 + " " + num3);
}
}

The if statements switch the numbers by creating a temporary value to store the old number in before setting it to the new number, the other number is then set to the old, saved number
A more interesting way of switching numbers is with bitwise operators
num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;
This works from xoring the bits together, and because xor inverts itself when given the same value ((A xor B) xor B) == A

Related

validating char user input loop

I'm writing a simple calculator program, the user inputs two integers and a symbol (+ - * etc) which represents the operation (add, subtract, multiply, etc) to be applied to the integers and the program calculates what they asked.
I have a do-while loop to continually ask for input if the input does not match the given symbols.
I've tried comparing them but I'm unsuccessful and very uncertain on what to do
CODE:
Scanner scan = new Scanner(System.in);
int num1, num2, sum, difference, product;
String a, b, c, userInput;
char choice, plus, minus, times;
System.out.print(First Integer: --> ");
num1 = scan.nextInt();
System.out.print(Second Integer: --> ");
num2 = scan.nextInt();
a = "+";
b = "-";
c = "*";
plus = a.charAt(0);
minus = b.charAt(0);
times = c.charAt(0);
do {
System.out.print("Choose + - or *");
userInput = scan.Next();
choice = userInput.charAt(0);
} while(choice != '+' || choice != '-' || choice != '*');
switch(choice) {
case 1:
sum = num1 + num2;
System.out.println("Sum is " + sum);
break;
case 2:
difference = num1 - num2;
System.out.println("Difference is " + difference);
break;
case 3:
product = num1 ' num2;
System.out.println("Product is " + product);
break;
}
There were some errors in your code, I have tried to rectify them.
Take a look,
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num1, num2, sum, difference, product;
String userInput;
char choice, plus, minus, times;
System.out.println("First Integer: --> ") ;
num1 = scan.nextInt();
System.out.println("Second Integer: --> ") ;
num2 = scan.nextInt();
plus = '+';
minus = '-';
times = '*';
do {
System.out.println("Choose + - or *") ;
userInput = scan.next();
choice = userInput.charAt(0);
}while(choice != '+' && choice != '-' && choice != '*');
switch(choice) {
case '+':
sum = num1 + num2;
System.out.println("Sum is " + sum);
break;
case '-':
difference = num1 - num2;
System.out.println("Difference is " + difference);
break;
case '*':
product = num1 * num2;
System.out.println("Product is " + product);
break;
default :
System.out.println("Wrong Choice!");
break;
}
}
}

How can I add exponent in my code

import java.util.Scanner;
public class Calculator
{
public static void main(String[] args )
{
Scanner userInput = new Scanner(System.in);
String operator;
double num1,num2,answer = 0;
System.out.println("Enter first number: ");
num1 = userInput.nextDouble();
System.out.println("Enter operator: ");
operator = userInput.next();
System.out.println("Enter second number: ");
num2 = userInput.nextDouble();
if (operator.equals ("+")){
answer = num1 + num2;
}
else if (operator.equals ("-")){
answer = num1 - num2;
}
else if (operator.equals ("*")){
answer = num1 * num2;
}
else if (operator.equals ("/")){
answer = num1 / num2;
}
System.out.println("First number:" + num1);
System.out.println("Operator:" + operator);
System.out.println("Second number:" + num2);
System.out.println("Answer: " + answer);
}
}
Use this function:
Math.pow(x, y)
In this way: place the code
else if (operator.equals ("^")){
answer = Math.pow(num1, num2);
}
just after your present code
else if (operator.equals ("/")){
answer = num1 / num2;
}
So this part of code will then be
else if (operator.equals ("/")){
answer = num1 / num2;
}
else if (operator.equals ("^")){
answer = Math.pow(num1, num2);
}

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 print out the GCD in different format

I am trying to ask the user to enter two integers and have the message to say
"The GCD of "first integer" and "second integer" is "GCD"
I have all my calculations right but it is just printing out my num1 for all values.
import java.util.Scanner;
public class Assignment3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first integer: ");
int num1 = scan.nextInt();
System.out.print("Enter the second integer: ");
int num2 = scan.nextInt();
while (num1 != num2)
{
if (num1> num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}
System.out.println("The gcd of" + num1 + " and " + num2 + " is " + num1);
}
}
In your while loop you check if num1 != num2 so when the println gets executed num1 will have the same value as num2.

Java debug help needed: display largest of 3 numbers

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.

Categories