Beginning Java : Finding the greatest number out of a list - java

I am trying to write a code that prompts the user for three numbers and the program is supposed to say what number is the greatest. I didn't want to do a bunch of "System.out.print" in the if and else if statements. The error according to the debugger is that "greatest" and "greatest1" have not been initialized.
import java.util.Scanner;
public class number1
{
public static void main(String[] args)
{
double a, b, c;
double greatest, greatest1;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter one number :");
a = keyboard.nextDouble();
System.out.print("Enter another number :");
b = keyboard.nextDouble();
System.out.print("Enter a third number :");
c = keyboard.nextDouble();
if(a > b && a > c) {
greatest = a;
} //end of if statement
else if(b > a && b > c){
greatest = b;
}
else if(c > a && c > b) {
greatest = c;
}
else if(a==b && c < a) {
greatest = a;
greatest1 = b;
}
else if(a==c && b < a) {
greatest = a;
greatest1 = c;
}
else if(b==c && a < b) {
greatest = b;
greatest1 = c;
}
else {
System.out.print("All of the numbers are greatest");
}
System.out.print("The greatest number is: " +greatest+ "and" +greatest1);
}
}

Since, the others have already point out the problem. I am going to point out that you can find the biggest number out of three number by just doing :
biggest = Math.max(a, Math.max(b,c));
You can replace all the conditionals in your code.
Imagine that you want the max of a set of integers (e.g., an array of ints). You can do something like:
biggest = array[0]; // initialize max to the first number of the set
iterate over the set and checking the max:
for(int i = 1; i < array.size; i++)
biggest = Math.max(biggest,array[i]);
or with Java Streams:
Arrays.stream(array).max().getAsDouble()
You can also make your own max function, for your case can the following:
public double maxDouble (double a, double b){
if(a > b) return a;
else return b;
}
You can read here more detailed information about the Math class and their methods (such as public static double max(double a,double b).

To fix this, you need to make sure greatest and greatest1 are always assigned to a value. What would happen if it went into this code block:
if (a > b && a > c) {
greatest = a;
} //end of if statement
greatest1 would not be assigned so when it printed it out in the last statement that says
System.out.print("The greatest number is: " + greatest + "and" + greatest1);
It's giving you an error.

Another tip: If you press enter after entering each number, you should read the newline \n after you read each number.
E.g.
a = keyboard.nextDouble();
Should be changed to
a = keyboard.nextDouble();
keyboard.nextLine();
etc.

Take input from keyboard and create a double array and then try below code.
double dblArray[] = {24.0,40.2,38.9};
Arrays.sort(dblArray);
System.out.print("The greatest number is: " +dblArray[dblArray.length-1]+ " and " +dblArray[dblArray.length-2]);
You can print n greatest numbers.

As a general hint: Initialize with 0:
double greatest = 0;
double greatest1 = 0;
But be warned, in your case this indicates an error in your code logic.
Fix that logic, otherwise the result will be 0, which can be wrong.

Related

Trying to write a program for Highest common factor of two numbers. But the output is showing the initialized value that is 1

The output is not showing the HCF but showing the initialized value that is 1.
package questionsOnLoops;
import java.util.Scanner;
public class hg {
public static void main(String[] args) {
Scanner srv = new Scanner(System.in);
System.out.print("Enter the first number: ");
int n1 = srv.nextInt(); //first number
System.out.println("Enter the second number: ");
int n2 = srv.nextInt(); //second number
int HCF=1; // Highest Common factor
int s; //smaller of two number
s = Math.min(n1, n2);
for(int i = s; i <= 1 ; i--) {
if(n1%i==0&&n2%i==0) {
HCF=i;
break;
}
}
System.out.println(HCF);
}
}
for(i = 1; i <= a || i <= b; i++) {
if( a%i == 0 && b%i == 0 )
hcf = i;
}
Use this logic. here a is the first number and b is the second.
Your code is never executing the "for" loop because you set i=s and i will never be i<=1...
Change to i>=1 and you're good to go
You have just to change your operator in your 'for' loop.
for(int i = s; i >= 1 ; i--) {
Because in your code you loop while i is less than 1. But in your inizialization i is equal to s. So you never enter in the 'for' loop and your HCF is the default value of your HCF variable which is 1.
For your culture if you want an optimized way to calculate the HCF, you can use the Euclidean algorithm which reduce drastically the number of operation. Because you transform several division and condition into a few Euclidean division.
Here an exemple
public int hcf(int m, int n) {
// the remainder of the Euclidean division
int r = 0;
// The algorithm says "the HCF of m and n is the last non-zero remainder"
while(n != 0) {
r = m % n;
m = n;
n = r;
}
return m;
}

How to print single number only once using nested loops in Java?

Everything runs fine in my Java code except at the very end of the code. So basically I can't figure out how to print out the User's Number if it is the same. For example I am prompt the User for a starting number and an ending number (integers). So say the user enters in the same integer "10" for starting number and "10" for ending number. I want the output to only be "10" to be printed only just once. I've tried everything I can think of with trying While Loop, Do-While Loop, and For Loops but I just can't figure it out?
------------------------JAVA CODE BELOW-------------------------------------------
import java.util.Scanner;
public class LoopsAssignment {
public static void main(String[] args) {
// input Scanner
Scanner input = new Scanner(System.in);
// ask user for a starting number and a ending number
System.out.println("Now I'll print whatever numbers you'd like!");
System.out.println("Give me a starting number: ");
startNum = input.nextInt();
System.out.println("Give me an ending number: ");
endNum = input.nextInt();
// count the users range of numbers
System.out.println("I counted your range of numbers: ");
int a = startNum;
int b = endNum;
while (a <= b) {
System.out.println(a);
a = a + 1;
}
while (a >= b) {
System.out.println(a);
a = a - 1;
}
while (a == b) {
System.out.println(a);
}
}
}
---------------------OUT PUT BELOW -----------------------------------------------------
Now I'll print whatever numbers you'd like!
Give me a starting number:
10
Give me an ending number:
10
I counted your range of numbers:
10
11
10
----jGRASP: operation complete.
You could restructure your code as follows:
while (a < b) {
System.out.println(a);
a = a + 1;
}
while (a > b) {
System.out.println(a);
a = a - 1;
}
if (a == b) {
System.out.println(a);
}
You can use for loop:
public static void printRange(int minInclusive, int maxInclusive) {
for (; minInclusive <= maxInclusive; minInclusive++)
System.out.println(minInclusive);
}
So you are either counting up, down or there's just one.
So
int step = endNum>startNum ? +1 : -1;
int a = startNum;
int b = endNum;
while (a != b) {
System.out.println(a);
a = a + step;
}
System.out.println(b);
Or put a break in the middle of a for loop. Also there's +=, and a few things we can make more conventional.
int step = endNum>startNum ? +1 : -1;
for (int i=startNum; ; i+=step) {
System.out.println(i);
if (i == endNum) {
break;
}
}
The issue is in your first two while loops where you are using ">=" and "<=". You can remove "=" from the condition.
However you can improve your code as suggested in other comments.

factorable trinomial / polynomial

so I want to create a program that prints out a factorable quadratic equation when the user enters a value, c, and a = 1,. The program should determine all the possible Integer values of b so that the trinomial prints out in the form x^2 + bx + c
An example would be if the user entered -4 for c the program should print out:
x^2 - 4
x^2 - 3x - 4
So far this is what I have done with my code, I am trying to figure out how to execute the program but I really am having trouble of where to go from here. If anyone can offer some help that would be much appreciated!
public class FactorableTrinomials
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("A trinomial in standard form is ax^2 + bx +
c. \nIf a = 1, this program will output all factorable trinomials
given the entered c value.");
System.out.print("\nEnter an integer ā€œcā€ value: ");
int numC = scan.nextInt();
final int NUMA= 1;
int numB;
if (numC > 0)
{
int factors;
System.out.print("\nThe factors of " + numC + " are: ");
for(factors = 1; factors <= numC; factors++) //determines
factors and how many there are
{
if(numC % factors == 0)
{
System.out.print(factors + " ");
}
}
First, find the pairs of integer which multiplies to c.
all possible values of b will then be the sum of the pair of integer.
A simple way to find the pairs of integer is to loop 2 variables from -c to c and check if the product is c. eg:
for(int i = -1 * numC; i <= numC; i++) {
for(int j = -1* numC; j<= numC;j++) {
if(i * j == numC) {
int b = i + j;
//print solution, if b == 0 then don't print the second term
}
}
}

recursively add integers from 1^2 to n^2

i'm having some trouble recursively adding integers in java from 1^2 to n^2.
I want to be able to recursively do this in the recurvMath method but all i'm getting is an infinite loop.
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
}//end if
if (n == 1){
return 1;
}//end if
if (n > 1){
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
}//end if
return 0;
}//end method
}//end class
I'm not fully grasping the nature of defining this recursively, as i know that i can get to here:
return (int) (Math.pow(n, 2));
but i can't incorporate the calling of the recurvMath method correctly in order for it to work.
Any help would be appreciated. Thanks!
In general, when trying to solve recursive problems, it helps to try to work them out in your head before programming them.
You want to sum all integers from 12 to n2. The first thing we need to do is express this in a way that lends itself to recursion. Well, another way of stating this sum is:
The sum of all integers from 12 to (n-1)2, plus n2
That first step is usually the hardest because it's the most "obvious". For example, we know that "a + b + c" is the same as "a + b", plus "c", but we have to take a leap of faith of sorts and state it that way to get it into a recursive form.
So, now we have to take care of the special base case, 0:
When n is 0, the sum is 0.
So let's let recurvMath(n) be the sum of all integers from 12 to n2. Then, the above directly translates to:
recurvMath(n) = recurvMath(n-1) + n2
recurvMath(0) = 0
And this is pretty easy to implement:
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
} else {
return recurvMath(n-1) + (n * n);
}
}
Note I've chosen to go with n * n instead of Math.pow(). This is because Math.pow() operates on double, not on int.
By the way, you may also want to protect yourself against a user entering negative numbers as input, which could get you stuck. You could use if (n <= 0) instead of if (n == 0), or check for a negative input and throw e.g. IllegalArgumentException, or even use Math.abs() appropriately and give it the ability to work with negative numbers.
Also, for completeness, let's take a look at the problem in your original code. Your problem line is:
recurvMath((int) ((int) n+Math.pow(n, 2)))
Let's trace through this in our head. One of your int casts is unnecessary but ignoring that, when n == 3 this is recurvMath(3 + Math.pow(3, 2)) which is recurvMath(12). Your number gets larger each time. You never hit your base cases of 1 or 0, and so you never terminate. Eventually you either get an integer overflow with incorrect results, or a stack overflow.
instead of saying:
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
i instead said:
return (int) ((Math.pow(n, 2)+recurvMath(n-1)));
Try this
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 1){
return 1;
}//end if
// More simplified solution
return recurvMath(n-1) + (int) Math.pow(n, 2); // Here is made changes
}//end method
}//end class

Does Java have an exponential operator?

Is there an exponential operator in Java?
For example, if a user is prompted to enter two numbers and they enter 3 and 2, the correct answer would be 9.
import java.util.Scanner;
public class Exponentiation {
public static double powerOf (double p) {
double pCubed;
pCubed = p*p;
return (pCubed);
}
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
double num = 2.0;
double cube;
System.out.print ("Please put two numbers: ");
num = in.nextInt();
cube = powerOf(num);
System.out.println (cube);
}
}
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9
The easiest way is to use Math library.
Use Math.pow(a, b) and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).
you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)
System.out.println(Math.pow(2, 3));
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}

Categories