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

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);
}

Related

My code doesn't calculate min and max numbers

I'm trying to write a code which will show the highest, lowest, the difference of them and the average of inputted 30 numbers.
But its not working and is showing the same result for both min and max numbers. Here is the code.
public class aa {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] daystemp = new int[30];
int i = 0;
int dayHot = 0;
int dayCold = 0;
while(i < daystemp.length){
daystemp[i] = input.nextInt();
i++;
}
int maxTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] > maxTemp) {
maxTemp = daystemp[i];
dayHot = i + 1;
i++;
}
}
System.out.println(maxTemp);
int minTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] < minTemp) {
minTemp = daystemp[i];
dayCold = i + 1;
i++;
}
}
System.out.println(minTemp);
int diff = maxTemp - minTemp;
System.out.println("The difference between them is"+diff);
double sum = 0;
while(i < daystemp.length) {
sum += daystemp[i];
i++;
}
double average = sum / daystemp.length;
System.out.println("Average was"+average);
}
}
After the first loop (the input loop), i value is daystemp.length (i.e. 30).
It's never reset to 0. So each while loop condition is false.
Add i=0 before the loops and do i++outside the ifblocks or your code will never end.
example:
i=0;
int maxTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] > maxTemp) {
maxTemp = daystemp[i];
dayHot = i + 1;
}
i++;
}
A few notes about this solution:
By declaring the cumulative total double, no casting is required.
Because Java knows you want to convert int to double automatically if you assign an int to a declared double. Similary the fact that you want to express a result as double is implied when dividing a double by an int, such as when the average is taken. That avoids a cast also. If you had two ints and you wanted to produce a double you'd need to cast one or more of them, or in cases like a print statement where the compiler can't deduce the optimal type for the parameter, you'd need to explicitly cast to covert an int value to a double.
Not sure what OS you're running this on. The ideal situation would be to make it work on all platforms without requiring people type a magic word to end input (because how tacky). The easiest way to end input is to use the OS-specific end of input (end of file) key combination, and for Linux it's CTRL/D, which is how I explained it in the prompt. On another OS with a different end of input sequence you could just change the prompt. The trickiest would be if it is supposed to be truly portable Java. In that case I'd personally investigate how I could figure out the OS and/or End of File character or key combination on the current OS and modify the prompt to indicate to end input with whatever that is. That would be a bit of and advanced assignment but a very cool result.
Example illustrates use of a named constant to determine the array and is used limit the amount of input (and could be used to limit loop count of for loops accessing the array).
By setting the min and max to very high and low values respectively (notice the LOW value assigned to max and HIGH value assigned to min, those ensure the first legit temp entered will set the min and max and things will go from there).
Temperature Maximum, Minimum, Average and Difference Calculator
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args) {
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temps for up to 1 month of days (end with CTRL/D):");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("High temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}

Return Multiple Values from a Single Method [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 5 years ago.
I had a question in my exam. At first it was pretty easy. Let me explain the question:
Make the User Specify how many integers wants to put (Array)
Numbers should be between -1500 to 1500
(Tricky): Create a method that calculates the percentage of the numbers put, what percentage were 0, positive, negative.
(All this should be in ONE method, no return to string, string buffer, the return result should be a double value)
I think I did it right, but when I tested it in real time, the problem that I run is that it returns the values 0.0, 0.0, 0.0 ... Or it returns the correct percentage only if the values fall within the same condition (eg. all zero).
Here is my code: (I hope you can make sense out of it). I'm just curious, I don't know how to solve it. I have also tried it with a static method, I run into the same problem.
import java.util.Scanner;
public class nPNZ {
public int [] number;
public nPNZ (int [] n){
number = n;
}
public double [] allCalcs(){
int countPos = 0; int countNeg = 0; int countZero = 0;
for (int i = 0; i < number.length; i++) {
if (number[i] == 0) {
countZero++;
}else if (number[i] > 0){
countPos++;
}else{
countNeg++;
}
}
//0 = 0 ; 1 = positive ; 2 = negative
double total [] = new double [3];
total[0] = (countZero/number.length)*100;
total[1] = (countPos/number.length)*100;
total[2] = (countNeg/number.length)*100;
return total;
}
public static void main (String args[]){
//min 20 number, -1500 to 1500
Scanner input = new Scanner (System.in);
final int MIN_SIZE = 5;
int size = 0;
while(size < MIN_SIZE){
System.out.println("Specify the size of the array: ");
size = input.nextInt();
while(size<MIN_SIZE){
System.out.println("Size should be greater than: " + MIN_SIZE);
size = input.nextInt();
}
}
input.nextLine();
int num [] = new int [size];
for (int i = 0; i < num.length; i++) {
System.out.println("Write number " + (i+1) + " : ");
num[i] = input.nextInt();
while(num[i] < -1500 || num[i] > 1500) {
System.out.println("The number should within the range of -1500 and 1500");
num[i] = input.nextInt();
}
}
nPNZ n = new nPNZ (num);
System.out.println("Percentage of zero numbers is: " + n.allCalcs()[0] );
System.out.println("Percentage of positive numbers is: " + n.allCalcs()[1] );
System.out.println("Percentage of negative numbers is: " + n.allCalcs()[2]);
}
}
I can see one problem in your code.
double total [] = new double [3];
total[0] = (countZero/number.length)*100;
total[1] = (countPos/number.length)*100;
total[2] = (countNeg/number.length)*100;
return total;
Here, countZero, countPos and countNeg are all integers and number.length is also integer. So, when you divide an integer by another integer, you will get an integer.
Since, countZero, countPos and countNeg are all less than number.length, you will get zero value in the total array.
Example:
System.out.println(2/3); // prints 0
System.out.println(2.0/3); // prints 0.6666666666666666
System.out.println((double)2/3); // prints 0.6666666666666666
There are several alternatives to solve your problem. One of them is, simply multiply the integer by 1.0 while dividing it by another integer.
You can do something like this.
public double [] allCalcs(){
// your code goes here
double total [] = new double [3];
total[0] = (countZero * 1.0 / number.length) * 100;
total[1] = (countPos * 1.0 / number.length) * 100;
total[2] = (countNeg * 1.0 / number.length) * 100;
return total;
}
OR, you can declare the variables (countZero, countPos and countNeg) as double.

Calculating factorial, where did I go wrong?

This was part of my assignment and was asked to calculate factorial of 5 and 7.
I finished it as below:
import java.util.Scanner;
public class Factorial {
public static void main(String [] args)
{
System.out.println("Please enter a number: ");
Scanner input=new Scanner(System.in);
int number=input.nextInt();
int i,fact=1;
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
}
It worked for 5 and 7 (resulting 120 and 5040).
But my professor came over and test it with 20 and 987654321, result returns -2102132736 and 0.
Why is that?
P.S. I thought for the case of 987654321, the result would crush the application or return error since it would be huge.
This code can solve your problem . It is taken from here
class BigFactorial
{
static void factorial(int n)
{
int res[] = new int[300];
// Initialize result
res[0] = 1;
int res_size = 1;
// Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n
for (int x=2; x<=n; x++)
res_size = multiply(x, res, res_size);
System.out.println("Factorial of given number is: ");
for (int i=res_size-1; i>=0; i--)
System.out.print(res[i]);
}
// This function multiplies x with the number represented by res[].
// res_size is size of res[] or number of digits in the number represented
// by res[]. This function uses simple school mathematics for multiplication.
// This function may value of res_size and returns the new value of res_size
static int multiply(int x, int res[], int res_size)
{
int carry = 0; // Initialize carry
// One by one multiply n with individual digits of res[]
for (int i=0; i<res_size; i++)
{
int prod = res[i] * x + carry;
res[i] = prod % 10; // Store last digit of 'prod' in res[]
carry = prod/10; // Put rest in carry
}
// Put carry in res and increase result size
while (carry!=0)
{
res[res_size] = carry%10;
carry = carry/10;
res_size++;
}
return res_size;
}
// Driver program
public static void main(String []args)
{
factorial(100);
}
}
Because 5040! is a very larger number (even long overflows). Use a BigInteger like
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= number; i++) { // <-- x * 1 = x
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println("Factorial of " + number + " is: " + fact);
This is because of the fact that the container that you have taken for storing and printing your result does not have the capacity to hold such big integer (I mean factorial of 20). So, you need a bigger container. As others already suggested, you can use BIGINTEGER.

java conversion from double to int for certain numbers

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);
}
}

Java multiple input

UPDATED
How can you by using this method (Collatz conjecture) to find the number with the highest number of operations between, say 4 and 230.
Any guidance appreciated.
public static void main(String[] args) {
System.out.print("Enter a low integer ");
Scanner input = new Scanner(System.in);
int low = input.nextInt();
System.out.print("Enter a high integer ");
int number = input.nextInt();
maxendurance(number);
}
public static int maxendurance(int number) {
int count = 0;
System.out.print("The number " + number);
// need to loop this i suppose in relative to user input
while (number != 1) {
number = (number & 1) != 0 ? number * 3 + 1 : number >> 1;
count++;
}
System.out.println(" has endurance: " + count);
return number;
}
You will have to loop through all the numbers between low and high. Look into for-loops:
for(int number = low; number <= high; number++)
{
// do something with number
}
Somehow you will need to execute a for every number within the loop (hint: pass it in as a parameter). Then keep track of the number with the highest count.
Oh, and please name your methods more clearly than a and b - nobody will understand what they do without going through the code.
First of all, move the input out of method a:
public static void main(String[] args) {
System.out.print("Enter an integer to be checked: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
a(number);
b();
}
public static int a(int number) {
int count = 0;
System.out.print("The number " + number);
[...]
Then you can use a simple for loop to iterate between low and high:
int bestNumber = -1;
int bestScore = -1;
for (int i = low; i <= high; i++) {
int score = a(i);
if (score < bestScore) {
bestNumber = i;
bestScore = score;
}
}
The result can then be found in bestNumber.
I am going to suggest a more advanced approach, in case relevant and incase anyone comes upon this. If you are concerned about time efficiency, Memoization or Dynamic Programming can help you, especially inverse dragon recursion.
I'll give you a hint. If you need more, just comment.
Take 3 for example. One transformation T has T(3)=10. If prior you had found it takes v transformations to take 10 to 1 and you stored (10,v) in a map, then instantly you know that it takes (v+1) steps to get 3 to 1.

Categories

Resources