Display 3 numerical values ​in java with greater, less and equal - java

I'm trying to show 3 different values in this code, the highest number, the lowest number and if all the numbers are the same the output should show that they are equal, So far I have only been able to show greater or equal values, but I don't know how to implement the display of the smaller value, does this structure help me to achieve it or should I use another type of structure?
import java.util.Scanner;
public class values
{
public static void main(String[] args)
{
int x, y, z;
Scanner s = new Scanner(System.in);
System.out.print("First Value:");
x = s.nextInt();
System.out.print("Second Value:");
y = s.nextInt();
System.out.print("Third Value:");
z = s.nextInt();
if (x == y && x == z)
{
System.out.println("All numbers are equal");
}
else if(y > z && y > x)
{
System.out.println("The highest value is: "+y);
}
else if(x > y && x > z)
{
System.out.println("The highest value is: "+x);
}
else
{
System.out.println("The highest value is: "+z);
}
}
}

It might be cumbersome to write all the conditions involving all three variables. I would proceed as follows:
Initialize separate variables to store the highest, and the lowest value separately. e.g. int highest = x; int lowest = x;
Compare the current highest and the current lowest with y and z respectively, change if necessary. e.g. highest = y > highest : y ? highest; lowest = y < lowest ? y : lowest;
After all comparisons are done, if the highest value is the same as the lowest, then all x, y and z are the same.

Try it like this for min and max.
int x = 10; int y = 20; int z = 30;
int min = Math.min(Math.min(x,y),z);
int max = Math.max(Math.max(x,y),z);
System.out.println("max = " + max);
System.out.println("min = " + min);
Prints
max = 30
min = 10
If you don't want to use the Math class methods, write your own and use them the same way. These use the ternary operator ?: which says that for expr ? a : b if the expression is true, return a, otherwise return b;
public static int max (int x, int y) {
return x > y ? x : y;
}
public static int min (int x, int y) {
return x < y ? x : y;
}
Finally, you could write methods to take an arbitrary number of arguments and return the appropriate one. These first check for a null array then check for an empty array.
public static int min(int ...v) {
Objects.requireNonNull(v);
if (v.length == 0) {
throw new IllegalArgumentException("No values supplied");
}
int min = v[0];
for(int i = 1; i < v.length; i++) {
min = min < v[i] ? min : v[i];
}
return min;
}
public static int max(int ...v) {
Objects.requireNonNull(v);
if (v.length == 0) {
throw new IllegalArgumentException("No values supplied");
}
int max = v[0];
for(int i = 1; i < v.length; i++) {
max = max > v[i] ? max : v[i];
}
return max;
}

if (x == y && x == z) {
System.out.println("All numbers are equal");
} else {
System.out.println("The highest value is: "+ IntStream.of(x, y, z).max().getAsInt());
System.out.println("The lowest value is: "+ IntStream.of(x, y, z).min().getAsInt());
}

Related

Java using loop, accept five integers, input from console and return the min & max

I am trying to create a Java code using a loop that will accept five integers input from console and return the smallest and the largest. I am having a problem with the code coming together.Thank you
import java.util.*;
public class Highest_LowestofFiveIntegers {
public static void main(String[] args) {
System.out.print("Enter five integers separated by a
space i.e. 2 6 55 1 3 910: ");
int number = 0;
number = input.nextInt();
int max = 0;
int min = 0;
for (int x = 0; x<5; x++){
if (x == 0 || number > max){
max = number;
}
if (x == 0 || number < min){
min = number;
}
}
System.out.println("Highest value: " + max);
System.out.println("Lowest value: " + min);
}
}
Put number = input.nextInt(); in the for loop; not before it.
int max = 0, min = 0;
for (int x = 0; x < 5; x++) {
int number = input.nextInt();
if (x == 0 || number > max){
max = number;
}
if (x == 0 || number < min){
min = number;
}
}
System.out.println("Highest value: " + max);
System.out.println("Lowest value: " + min);

Loss of accuracy with floats

I am trying to compute a summation of float numbers. All small numbers output properly, when I use very large numbers as inputs, the output is always off by a few integers. For example, H = 5764801 W = 1679616, on paper, works out as 335923 30275911. In my program though, 335923 30275908 is printed instead. Here is the code:
public void printOutput(int H, int W) // The inputs
{
if(H == 1 && W == 1)
{
System.out.println(0 + " " + 1);
return;
}
List<Integer> pfw = primeFactors(W);
int y = 1;
while(H != (int) (Math.pow(Math.pow(W, 1f/y) + 1f, y))) y++;
final float N = findWholeNumber(pfw);
float height = 0;
for(int x = 1; x <= y + 1; x++)
{
height += (float) (W * Math.pow((N + 1f) / N, x-1f) + 1e-8); //Here is the summation
}
float cats = 1;
for(int x = 2; x <= y + 1; x++)
cats += (float) (Math.pow(N, x-1));
int notWorking = (int) (cats - W);
System.out.println(notWorking + " " + (int)height); //Outputs printing
}
private int findWholeNumber(List<Integer> factors)
{
List<Integer> common = new ArrayList<Integer>();
for(int i = 0; i < factors.size(); i++)
{
if(common.contains(factors.get(i))) continue;
common.add(factors.get(i));
}
int num = common.get(0);
for(int i = 1; i < common.size(); i++)
num *= common.get(i);
return num;
}
private List<Integer> primeFactors(int num)
{
List<Integer> pf = new ArrayList<Integer>();
if(num == 1)
{
pf.add(1);
return pf;
}
for(int j = 2; j <= num; j++)
while(num % j == 0) // is prime
{
pf.add(j);
num /= j;
}
return pf;
}
}
Floating point numbers have a limited precision as mantissa has a limited width.
You could try double for your case which precision is more (as its mantissa is wider), but it is also limited.
More information: https://en.wikipedia.org/wiki/IEEE_floating_point#IEEE_754-2008 and What is the maximum number in the mantissa part of a Java float?
If you need to have an unlimited precision, try BigDecimal. The count of significant digits there is only limited by the amount of your memory.
If you only need integer values, BigInteger is an option.
Study What Every Computer Scientist Should Know About Floating-Point Arithmetic, David Goldberg, 1991.
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Three consecutive numbers in a while loop

Write a program that reads integers from the user until he enters -1, and print “Consecutive ” if there are three consecutive numbers otherwise print “None Consecutive”; that is in the number list you read are in an order such that there is some integer k that the numbers values are k, k+1, and k+2.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = x + 1;
int z = x + 2;
boolean areConsecutive = false;
while (x != -1) {
if (x == y) {
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
x = scan.nextInt();
}
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
Can anyone please tell me what's wrong with this code?
Get the next integer before checking with y, then check for z. if one of these fails update y and z and check again.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = x + 1;
int z = x + 2;
boolean areConsecutive = false;
while (x != -1) {
x = scan.nextInt();
if (x == y) {
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
y = x + 1;
z = x + 2;
}
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
You need to increment y and z by 1 before scaning new x.
This is what you are looking for:
Scanner scan = new Scanner(System.in);
System.out.println("enter");
int x = scan.nextInt();
boolean areConsecutive = false;
while (x != -1) {
int y = x + 1;
System.out.println("enter");
x = scan.nextInt();
if (x == y) {
System.out.println("enter");
int z = x + 1;
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
}
if (areConsecutive)
System.out.println("Consecutive");
else
System.out.println("None Consecutive");
You're close but you're not maintaining the history of the numbers correctly.
First, to clarify, the specification calls for you to enter an arbitrary quantity of arbitrary numbers from the user and simply check if any three of them are consecutive. Hence the first line below would have a consecutive sequence (the 1 2 3 bit starting at the third number) but the second would not:
9 9 1 2 3 9
3 1 4 1 5 9
One way to do this is simply maintain the minimal information to detect a consecutive sequence. To do that, you need to keep a copy of only the last three numbers entered. The pseudo-code (easily transformable into any procedural language) for such a beast would be:
# Get first number, ensure no chance of consecutive
# sequence until at least three are entered.
num3 = getint()
num2 = num3
num1 = num3
consecutive = false
# Loop until -1 entered.
while num3 != -1:
# Check for consecutive sequence.
if (num1 + 1 == num2) and (num2 + 1 == num3):
consecutive = true
# Shift numbers "left".
num1 = num2
num2 = num3
num3 = getint()
if consecutive:
print "Consecutive"
else
print "None Consecutive"
This is what you are looking for:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
boolean areConsecutive = false;
while ((x != -1)&&(y != -1)&&(z != -1)){
if ((z == y + 1)&&(y == x + 1)
areConsecutive = true;
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
I would do it this way, we have to check if three numbers are consecutive no matter the order they were entered by user:
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[] numbers = new int[3];
for( int i = 0; i < numbers.length; ++i)
numbers[i] = scan.nextInt();
Arrays.sort(numbers);
boolean areConsecutive = true;
for( int i = 0; i < numbers.length - 1; ++i)
if(numbers[i+1] - numbers[i] != 1)
areConsecutive = false;
if(areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}

Placing floats from an arrayList into equal width bins to create a histogram

This code will currently take in an array list and create 10 equal width bins from the floats contained; it will then print the bin ranges. What I am having trouble with is figuring out how to index through the ArrayList and print a star in the correct bin according to the float found.
I'm not asking for code; rather a push in the right direction.
public static String getHist( String Tag, ArrayList <Float> x)
{
Float max = getMaximum(x);
Float min = getMinimum(x);
Float interval = (max - min) / 10f;
// System.out.print("Interval:" + interval);
Float base = min;
//System.out.println(Tag);
//Loops through for 10 iterations
for(Float i = base ; i <= (max - interval); i+= interval)
{
//System.out.print("Interval:" + i + "\n");
//prints out the bin range
System.out.print(i + " - " + (base += interval) + " | ");
//Loop through ArrayList and if a number found belongs within a bin place it
// within that appropiate bin
//Logic not correct?
for(Float index = i; index <= base; index++)
{
for(Float n : x)
{
System.out.print("*");
}
}
System.out.println();
}
return Tag;
}
for(Float n : x)
{
if (i.compareTo(n) <= 0 && base.compareTo(n) > 0)
System.out.print("*");
else if (i == max && n == max)
{
System.out.print("*");
}
}

Binary multiplication - Peasant algorithm

I tried Binary multiplication technique on decimal numbers.
Algorithm:
To multiply two decimal numbers x and y, write them next to each
other, as in the example below. Then repeat the following: divide the first number by 2,
rounding down the result (that is, dropping the :5 if the number was odd), and double the
second number. Keep going till the first number gets down to 1. Then strike out all the rows
in which the first number is even, and add up whatever remains in the second column.
11 13
5 26
2 52
1 104
........
143 (answer)
Code:
class Multiply
{
static int temp;
static int sum;
public static void main(String[] args)
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int ans = multiply(x , y);
System.out.println(ans);
}
public static int multiply(int x, int y)
{
if(x==1)
{
System.out.println(x+" : "+y);
return y;
}
temp = multiply(x/2, y*2);
if(x%2==0)
{
System.out.println(x+" : "+y);
return temp;
}
else
{
System.out.println(x+" : "+y);
sum = sum+temp;
return sum;
}
}
}
Something is wrong with the recursion i think but i couldn't find what it is!!
When having recursion do not use variables outside the recursive method. It is too confusing. I mean that the recursive method should be self-contained. Here is a working version of your program:
public class Main {
public static void main(String[] args) {
int x = 11;
int y = 13;
int ans = multiply(x, y);
System.out.println(ans);
}
public static int multiply(int x, int y) {
if (x == 1) {
return y;
}
int temp = multiply(x / 2, y * 2);
if (x % 2 != 0) {
temp += y;
}
return temp;
}
}
Your recursion should be like this -
public class Multiply {
static int temp = 0;
static int sum = 0;
public static void main(String[] args) {
int x = Integer.parseInt("11");
int y = Integer.parseInt("9");
int ans = multiply(x, y);
System.out.println(ans);
}
public static int multiply(int x, int y) {
if (x == 1) {
System.out.println(x + " : " + y);
return sum + y;
}
if (x % 2 == 0) {
System.out.println(x + " : " + y);
} else {
System.out.println(x + " : " + y);
sum = sum + y;
}
return multiply(x / 2, y * 2);
}
}
I couldn't resist to post it in a single line
public static int multiply(int x, int y) {
return ((x & 1) > 0 ? y : 0) + ((x & ~1) > 0 ? multiply(x >> 1, y << 1) : 0);
}
I couldn't resist to add an iterative solution: fast, simple and valid
also for negative arguments:
int product(int x, int y) {
boolean positive = x >= 0;
int p = 0;
while (x != 0) {
if (x % 2 != 0) p += y;
x /= 2;
y *= 2;
}
return positive ? p : -p;
}
Here is simple Java implementation which does multiplication without multiplication operator.
public static int multiply(int a, int b) {
int p = 0;
// If a is odd number.
if ((a & 1) > 0) {
p = b;
} //else use the default value in the p.
// If 'a' contains any number larger than one
// than continue recursion.
if (a > 1)
p = p + multiply(a >> 1, b << 1);
return p;
}
public static int multiply(int x, int y) {
if (y == 0 || x == 0) {
return 0;
}
if (x == 1) {
return y;
} else {
return multiply(x >> 1, y << 1);
}
}

Categories

Resources