Print largest number out of given digits - Java - java

First I would apologize if my question seems not clear.
I want output to be the largest possible number from user input. Example:
input: x = 0; y = 9; z = 5;
output: 950
I tried something like the below code.
import java.util.Scanner;
class LargestOfThreeNumbers{
public static void main(String args[]){
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if ( x > y && x > z )
System.out.println("First number is largest.");
else if ( y > x && y > z )
System.out.println("Second number is largest.");
else if ( z > x && z > y )
System.out.println("Third number is largest.");
}
}
The code above will print something like: The seconde number is largest. That is correct the way I define the conditional statements. But how do I get 950 as final result? I know some logic is required here but my brain doesn't seem to produce it.
Your help is appreciated.

You could do something like this to print the numbers in order:
// make an array of type integer
int[] arrayOfInt = new int[]{x,y,z};
// use the default sort to sort the array
Arrays.sort(arrayOfInt);
// loop backwards since it sorts in ascending order
for (int i = 2; i > -1; i--) {
System.out.print(arrayOfInt[i]);
}

A solution using java 8 IntStream:
int x = 0, y = 9, z = 5;
IntStream.of(x,y,z).boxed().sorted( (i1,i2) -> Integer.compare(i2, i1)).forEach( i -> System.out.print(i));

You can find the maximum with successive calls to Math.max(int, int) and the minimum with calls to Math.min(int, int). The first number is the max. The last is min. And the remaining term can be determined with addition of the three terms and then subtraction of the min and max (x + y + z - max - min). Like,
int max = Math.max(Math.max(x, y), z), min = Math.min(Math.min(x, y), z);
System.out.printf("%d%d%d%n", max, x + y + z - max - min, min);

Something like this would work
ArrayList<Integer> myList = new ArrayList<Integer>();
Scanner val = new Scanner(System.in);
int x = 0;
for (int i = 0; i < 3; i++) {
System.out.println("Enter a value");
x = val.nextInt();
myList.add(x);
}
myList.sort(null);
String answer = "";
for (int i = myList.size() - 1; i >= 0; i--) {
answer += myList.get(i).toString();
}
System.out.println(answer);
}

Related

How do I display the first five numbers on a single line and the second five numbers on another line?

I am currently trying to create a do-while loop, counting from 1 to 10, that displays the first five numbers on the first line and the next five numbers on another line.
But whenever I run my code, the 6th iteration and onward print on seperate lines each instead of the same line.
If anyone could help me understand the error that I made and how to corret it, I would appreciate it.
import java.text.DecimalFormat;
import java.util.Scanner;
public class Hello_World { // Declare Class
public static void main(String[] args) { // Main Method
Scanner key = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("##.##"); // Decimal_Format!
/*
* While Loop count from 1 to 10
*/
int x = 1; // Declare and Initialize variable 'X'
do
{
System.out.print(x + " ");
x++;
if (x > 5) {
System.out.println("");
continue;
}
}
while (x <= 10);
}
} // Braces delimit blocks of code!
You only want to print the newline when x is 6. Also, you could use printf to make this a bit cleaner. Something like,
int x = 1; // Declare and Initialize variable 'X'
do {
if (x == 6) {
System.out.println();
}
System.out.printf("%3d ", x);
x++;
} while (x <= 10);
Outputs
1 2 3 4 5
6 7 8 9 10
The error in your code is with your if-statement
By setting the if statement to be true if x > 5 it will trigger for 6 through 10 which is why you get your numbers above 5 all on a separate line. If you just set the new line to kick in when x == 6 it will only trigger a new line when x is 6 and in no other circumstance.
I prefer a two-loop solution. The outer loop increments through the entire range you want; the inner loop increments through a single line.
int limit = 10;
int perLine = 5;
for (int x = 1; x <= limit; x += perLine) {
for (int y = x; y < x + perLine && y <= limit; y++) {
System.out.printf("%3d", y);
}
System.out.println();
}
This solution works even if the 'limit' is not an exact multiple of 'perLine'.
I wrote this with a for-loop out of sheer habit, but you could convert it to do-while easily enough.
int limit = 10;
int perLine = 5;
int x = 1;
do {
int y = x;
do {
System.out.printf("%3d", y);
y++;
} while (y < x + perLine && y <= limit);
System.out.println();
x += perLine;
} while (x <= limit);
However, it's a lot more long-winded that way, so unless this is being done as an exercise in using do-while, I'd use a for-loop.

Why won't this program print?

The problem is to determine the number of hours required before the second method becomes more beneficial than the first. I've been looking at this all day and don't know why I can't get it to print.
public class BestMethod{
public static void main(String[] args){
double earnings1 = 10.00;
double earnings2 = 0.10;
double totalHours1 = 0;
double totalHours2 = 0;
double x = 0;
double y = 0;
for (int i = 1; i <= 10; i++)
{
totalHours1++;
x = totalHours1 * earnings1;
totalHours2++;
earnings2 *= 1;
y = (earnings2 * 1) * 2 + earnings2;
}
if (y > x){
System.out.println ("It will take the second method " + totalHours2 + " hours before it becomes more beneficial than the first method ");
}
}
}
Based on your code, the value of earnings1 and earnings2 are remaining the same.
After the first iteration (i = 1) how values are changing (use pen and paper)
totalHours1 = 1.0, totalHours2 = 1.0, x = 10.0 and y = 0.30000000000000004
After completing the loop (i = 10)
totalHours1 = 10.0, totalHours2 = 10.0, x = 100.0 and y = 0.30000000000000004
So, the value of y is less than the value of x and the condition is going to false.
So, (in case if you want to) print the value use this in your program if (y < x) or you have to change the mathematical (calculation) method.

How to speed up the efficiency of my code?

Essentially I'm trying to create a program that counts up the sum of the digits of the number, but every time a number that is over 1000 pops up, the digits don't add up correctly. I can't use % or division or multiplication in this program which makes it really hard imo. Requirements are that if the user inputs any integer, n, then I will have to be able to compute the sum of that number.
I've already tried doing x>=1000, x>=10000, and so forth a multitude of times but I realized that there must be some sort of way to do it faster without having to do it manually.
import java.util.Scanner;
public class Bonus {
public static void main(String[] args) {
int x;
int y=0;
int u=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
x = s.nextInt();
int sum = 0;
{
while(x >= 100) {
x = x - 100;
y = y + 1;
}
while(x>=10) {
x = x - 10;
u = u + 1;
}
sum = y + u + x;
System.out.println("The sum of the digits in your number is" + " " + sum);
}
}
}
So if I type in 1,000 it displays 10. And if I type in 100,000 it displays 100. Any help is appreciated
Convert the number to a string, then iterate through each character in the string, adding its integer value to your sum.
int sum = 0;
x = s.nextInt();
for(char c : Integer.toString(x).toCharArray()) {
sum += Character.getNumericValue(c);
}

How to generate a right angle Fibonacci Series pyramid in Java?

I want to generate an output like this :-
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
However, i am trying in this way to achieve , but some piece of logic is missing which i am unable to decipher.
Here's what i am trying :-
import java.util.Scanner;
class Fibonacci
{
public static void main(String arr[])
{
System.out.println("Enter a no.");
Scanner input=new Scanner(System.in);
int num=input.nextInt();
int x=0,y=1;
for(int i=0;i<=num;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(j);
}
System.out.println("");
}
}
}
And it generates the output like this (consider num=6)
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
What logic is required to get the desired output ? Would be thankful if anyone can explain me this :)
Thanks in advance !!
You need to change logic of inner loop like this by adding two previous number to current number and swap them like this.
import java.util.Scanner;
class Fibonacci
{
public static void main(String arr[])
{
int x = 0, y = 0, c = 0;
System.out.println("Enter a no.");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
for (int count = 0; count < num; count++) {
System.out.print(0);
x = 0;
y = 1;
c = 0;
for (int i = 1; i <= count; i++) {
c = x + y;
y = x;
x = c;
System.out.print(" " + c);
}
System.out.println();
}
}
}
First two numbers 0 and 1 are given , no need to caculate .
Use a String to save previous line string .
Caculate next numbers , add it into your previous line string .
Here is an example :
int x = 0 , y = 1;
int num = 6;
System.out.println("0");
System.out.println("0 1");
String str = "0 1";
for(int i = 2 ; i < num ; i ++){
int amt = x + y ;
x = y;
y = amt;
str += " " + amt;
System.out.println(str);
}
In a Fibonacci series only the first two numbers are provided which are 0 and 1. The next number of the series are calculated by adding the last two numbers. The series is limited by the user by providing the number of integers it wants in the series.
Logic: The logic behind creating a Fibonacci series is to add the two integers and save them in a new variable z = x+y and then replace the first integer value by the second integer and second integer value by their sum to move one step ahead in the series x=y adn y=z.
In your problem you want the series to be printed in a right angled triangle so you need to save the series that is already printed in a string
int n = 10;
System.out.println("0\n");
System.out.println("0 1\n");
int x = 0, y=1;
int i=2, z=0;
String str = "0 1";
while(i!=10)
{
z = x+y;
str += " " + z;
x=y;
y=z;
i++;
System.out.println(str);
}
Hope this helps

calculating average of random integers in an array

I need to generate a specified number of random integers between any
two values specified by the user (example, 12 numbers all between 10 and 20), and then calculate the average of the numbers.
The problem is if I ask for it to generate 10 numbers, it will only generate 9 (shown in output.)
Also, if I enter a max range of 100 and min range of 90, the program will still generate #'s like 147, etc that are over the max range... did I mess up the random number generator? Can someone help?
Here is the code I have so far:
public class ArrayRandom
{
static Console c; // The output console
public static void main (String[] args)
{
c = new Console ();
DecimalFormat y = new DecimalFormat ("###.##");
c.println ("How many integers would you like to generate?");
int n = c.readInt ();
c.println ("What is the maximum value for these numbers?");
int max = c.readInt ();
c.println ("What is the minimum value for these numbers?");
int min = c.readInt ();
int numbers[] = new int [n];
int x;
double sum = 0;
double average = 0;
//n = number of random integers generated
for (x = 1 ; x <= n-1 ; x++)
{
numbers [x] = (int) (max * Math.random () + min);
}
for (x = 1 ; x <= n-1 ; x++)
{
sum += numbers [x];
average = sum / n-1);
}
c.println ("The sum of the numbers is: " + sum);
c.println ("The average of the numbers is: " + y.format(average));
c.println ("Here are all the numbers:");
for (x = 1 ; x <= n-1 ; x++)
{
c.println (numbers [x]); //print all numbers in array
}
} // main method
} // ArrayRandom class
Java arrays are zero based. Here you leave the first array element at its default value of 0. Replace
for (x = 1 ; x <= n-1 ; x++)
with
for (x = 0 ; x < n ; x++)
Edit: To answer question (from now deleted comment) of why this does not produce values between min and max
max * Math.random () + min
Math.random generates double values between 0.0 and 1.0. So for example, a min of 90 and max of 100 would generate numbers between and 90 and 190(!). To limit the values between the min and max you would need
min + Math.random() * (max - min)
^ |_________________________|
| |
90 value between 0 - 10
Java arrays start indexing at 0. Also your loop is exiting one index short. So, when n==6, your condition is then, "x <=5", and the loop exits. Try this:
for ( x = 0; x < n; x++ {
// stuff
}

Categories

Resources