java conversion from double to int for certain numbers - java

import java.util.Scanner;
public class Test1C
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 50: ");
double quo;
int num = reader.nextInt();
for(double a = 1; a <= num; a++)
{
quo = (num / a);
System.out.println(quo);
}
}
}
This is the code I currently am making to evaluate the list of quotients based on what number was inputted. Now the only thing my brain keeps farting on about is how to convert the whole numbers that are currently decimals into integers. However, the doubles (ex: 1.333) that are printed by this code are fine as is. I just can't figure out how to convert the whole number decimals (ex: 12.0) into whole number integers. Can someone help me?

yes you can :
String s = "1.333";
double d = Double.parseDouble(s);
int i = (int) d;
or
String s="1.333";
int i= new Double(s).intValue();

you can do like that .
Double d = new Double(1.25);
int i = d.intValue();
System.out.println("The integer value is :"+ i);

There is no general way to detect whether a double is truly an integer and a comparison of double and double or int must, generally, be handled with much care, but for the range of numbers in your program (and the upper bound could be raised considerably), this will work as you want:
for(double a = 1; a <= num; a++) {
double quo = num/a;
int iquo = (int)quo;
if( iquo == quo ){
System.out.println(iquo);
} else {
System.out.println(quo);
}
}

Related

The question is around the "Gambling" zone with addition of math

after adding two int variables to (a) and (b),
I have to gamble (a) times values between 10 to 100 and
calculate which square root of these gambled numbers is the closest to (b).
For example a=3 and b=2
output:
Gambled 16,25,49.
The number 16 was chosen since it's square root (4) is the closest to b=2.
I am stuck in the part of calculation of the square root, and saving the closest value to b each time the loop runs, i'm not allowed to use arrays,
this is the third question of my first task and i'd appreciate any experienced ideas to be shared ^^.
(MyConsole is a replacement for the scan command)
int a = MyConsole.readInt("Enter value a:");
int b = MyConsole.readInt("Enter value b:");
for(int i = 0; i<a; a--){
int gambler = ((int)(Math.random() *91)+10);
double Root = Math.sqrt(gambler);
double Distance= Root-b;
{
System.out.println();
Here is how I found the minimum. You can also use arrays to store all the gambling values if you want for future use. I also used Scanner but you can use your MyConsole I'm just not familiar with it. I hope it helps. דש מישראל
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter value a:");
int a = scanner.nextInt();
System.out.println("Enter value b:");
int b = scanner.nextInt();
double min = 100;
for (int i = 0; i < a; i++) {
int gambler = ((int) (Math.random() * 91) + 10);
double root = Math.sqrt(gambler);
double distance = Math.abs(root - b);
if (min > distance)
min = distance;
}
System.out.println("minimum value is: " + min);
}

Java program to add up the reciprocals of the integers up to number n

I tried to do it but i'm getting 1.0 as answer every time i run it. I'm not being able to find out what's wrong please help me. Here are the codes:
import java.util.Scanner;
public class Number23 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n=0;
float sum = 0,r = 0;
System.out.print("Enter a number for n: ");
n = input.nextInt();
for(int x = 1; x <= n; x++)
{
r = (1/x);
sum = sum + r;
}
System.out.print("The sum is "+sum);
}
}
In order to produce a reciprocal that has a floating point value it is not enough to declare r a float: the expression you assign it needs to be float as well. You can do it by using the f suffix on the constant 1 which you divide by x:
r = (1f / x);
Without the suffix, your expression represents an integer division, which produces an integer result, and drops the fraction. In your case, the only time that you get a value other than zero is when x is equal to 1.
class reciprocal
{
public static void main ( int n)
{
float i,a,s=0;
for(i=1;i<=n;i++)
{
a= 1/i;
s+=a;
}
System.out.print( "sum is "+s);
}
}

Generate Natural Logarithm of 2 Customly

I know I could generate it using Math.log(2) but I when I try to make up my own program to generate a natural log of 2 it continuously print 1. This is my code:
import java.math.BigDecimal;
import java.util.Scanner;
public class Ques11 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
BigDecimal sum = new BigDecimal(1);
for(int i = 2; i <= n; i++) {
sum.add(new BigDecimal(1/n));
}
System.out.print(sum.setScale(10).toPlainString());
}
}
I have tried to use float, double and int and in the end used BigDecimal but I still got 1 as the result I don't know why.
P.S It actually throws InputMismatchException when big numbers are given i.e greater than 2000000000 or 2 Billion.
n is defined as an int and 1 is an int literal. When you divide two ints you use integer arithmetic, which would return only the whole part of the fraction - in your case, 0.
To rectify this, you should use doubles:
public class Ques11 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double d = scan.nextInt(); // Note we're assigning to a double
BigDecimal sum = new BigDecimal(1);
for(int i = 2; i <= d; i++) {
sum.add(new BigDecimal(1.0/d));
}
System.out.print(sum.setScale(10).toPlainString());
}
}

java binary to decimal

Im having trouble converting binary to a decimal. We have to use a function for the conversion and do it by hand rather than use a predefined function. This is what I have so far, I know it is a mess but I am stuck on how to fix it. Thanks!
import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (!"-1".equals(inString)) {
int i;
int binaryLength;
binaryLength = inString.length();
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
System.out.println(decimal);
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
To use a function, as your assignment requires, you have to write the function outside the main method, and then include a statement that calls the function. So move this above the line that says public static void main:
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, each function or method (including main) has its own variables that it uses, called local variables; but the local variables that each function uses are its own separate copies. Thus, the above function won't be able to use the binaryLength or decimal variabes belonging to main. You'll need to declare them inside binaryToDecimal:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, this function won't be able to access main's inString, but the idea is that you've given the function the string you want to work with, which it refers to as binaryString. So change inString to binaryString in the function:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal = decimal + Math.pow(2,binaryString.length() - 1 - i);
}
return (int) decimal;
}
And also note that the binaryLength and decimal variables are totally unrelated to the variables of the same name in main. That means that when you assigned binaryLength in main, that has no effect on binaryLength in binaryToDecimal. You'll need to assign it in the function. Change int binaryLength; to
int binaryLength = binaryString.length();
Finally, in order to use the function, main will need to call it. Put this in the main function:
decimal = binaryToDecimal(inString);
When main executes that, it will call the function and tell it to work with inString. The function will call that binaryString, though. The function will return a result, and then main will assign that result to the variable decimal--that means the local variable decimal that belongs to main, since the above statement is inside main.
I don't know if this will make your whole program work. (It should, but I'm not sure.) But I'm just trying to explain the details of how to use functions.
The confusing part is with the Math.pow, and its complicated arguments, where off-by-one errors are easily made.
Yet, if we have a number at base 10, like
123
its value is
(((0*10)+1)*10+2)*10+3
This looks complex, but note the easy pattern: Starting out with 0, we go through the digits. As long as we have another dgit, we multiply the previous result by the base and add the digit value. That's all! No Math.pow, no complex index calculations.
Hence:
String s = "1010";
int value = 0;
int base = 2;
for (i=0; i < s.length(); s++) {
char c = s.charAt(i);
value = value * base;
value = value + c - '0';
}
When I cleaned up your code, it worked just fine -
public static int binaryToDecimal(String binaryString) {
int binaryLength = binaryString.length();
int decimal = 0;
for (int i = binaryLength - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1') {
decimal += Math.pow(2, binaryLength - 1 - i);
}
}
return decimal;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String inString = input.nextLine();
while (!"-1".equals(inString)) {
System.out.println(binaryToDecimal(inString));
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
Output
Enter a binary number:
01
1
Enter a binary number:
10
2
Enter a binary number:
-1
All set !
Here's the function after a little clean up.
public static int binaryToDecimal (String binaryString) {
int decimal = 0;
int base = 2;
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal += Math.pow(base,i);
}
return decimal;
}

Find the max of 3 numbers in Java with different data types

Say I have the following three constants:
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
I want to take the three of them and use Math.max() to find the max of the three but if I pass in more then two values then it gives me an error. For instance:
// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);
Please let me know what I'm doing wrong.
Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).
you can use this:
Collections.max(Arrays.asList(1,2,3,4));
or create a function
public static int max(Integer... vals) {
return Collections.max(Arrays.asList(vals));
}
If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.
https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])
NumberUtils.max(int[])
Math.max only takes two arguments, no more and no less.
Another different solution to the already posted answers would be using DoubleStream.of:
double max = DoubleStream.of(firstValue, secondValue, thirdValue)
.max()
.getAsDouble();
Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so
public static double max(double... n) {
int i = 0;
double max = n[i];
while (++i < n.length)
if (n[i] > max)
max = n[i];
return max;
}
In your example, max could be used like this
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String[] args) {
double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}
Java 8 way. Works for multiple parameters:
Stream.of(first, second, third).max(Integer::compareTo).get()
I have a very simple idea:
int smallest = Math.min(a, Math.min(b, Math.min(c, d)));
Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.
Regards,
Norbert
Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().
If you don't like that you can always create your own method for it...
public class test {
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String args[]) {
double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
}
public static Object multiMax(Object... values) {
Object returnValue = null;
for (Object value : values)
returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
: (value instanceof Double) ? (Double) value
: (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
: (returnValue instanceof Double) ? (Double) returnValue
: (Float) returnValue)) ? value : returnValue)
: value;
return returnValue;
}
}
This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.
It might also be throwing an error since there is no such thing as "MY_DOUBLE2".
int first = 3;
int mid = 4;
int last = 6;
//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));
You can do like this:
public static void main(String[] args) {
int x=2 , y=7, z=14;
int max1= Math.max(x,y);
System.out.println("Max value is: "+ Math.max(max1, z));
}
if you want to do a simple, it will be like this
// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;
public class MaximumFinder
{
// obtain three floating-point values and locate the maximum value
public static void main(String[] args)
{
// create Scanner for input from command window
Scanner input = new Scanner(System.in);
// prompt for and input three floating-point values
System.out.print(
"Enter three floating-point values separated by spaces: ");
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double
// determine the maximum value
double result = maximum(number1, number2, number3);
// display maximum value
System.out.println("Maximum is: " + result);
}
// returns the maximum of its three double parameters
public static double maximum(double x, double y, double z)
{
double maximumValue = x; // assume x is the largest to start
// determine whether y is greater than maximumValue
if (y > maximumValue)
maximumValue = y;
// determine whether z is greater than maximumValue
if (z > maximumValue)
maximumValue = z;
return maximumValue;
}
} // end class MaximumFinder
and the output will be something like this
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
References Java™ How To Program (Early Objects), Tenth Edition
Simple way without methods
int x = 1, y = 2, z = 3;
int biggest = x;
if (y > biggest) {
biggest = y;
}
if (z > biggest) {
biggest = z;
}
System.out.println(biggest);
// System.out.println(Math.max(Math.max(x,y),z));

Categories

Resources