I'm trying to create a random sum generator that generators random sums!
The only problem with what I created is, it can generate sums that have a negative result as well. So I want it to only generate sums with positive outcomes.
Example:
7-10 = -3
My code:
number1 = (int)(Math.random()* LT) + 1;
number2 = (int)(Math.random()* LT) + 1;
operator = (int)(Math.random()* OP) + 1;
switch(operator) {
case 1:
operation = "+";
result = number1 + number2;
break;
case 2:
operation = "-";
result = number1 - number2;
break;
case 3:
operation = "*";
result = number1 * number2;
break;
case 4:
operation = "/";
result = number1 * number2;
break;
}
Since you will always be dealing with positive integers your only issue is checking for negative numbers in your subtraction case. I would also recommend switching to the Random class to generate random integers. One way to get around negative results is to flip the numbers you are subtracting.
boolean flip = false;
int num1, num2, op, result;
String operation;
Random r = new Random();
num1 = r.nextInt(8)+2;
num2 = r.nextInt(8)+2;
op = r.nextInt(4);
switch(op) {
case 0:
// Always be positive.
operation = "+";
result = num1+num2
break;
case 1:
// Could be negative if num2 is larger than num1. Simply flip the numbers.
flip = num1 < num2;
operation = "-";
result = flip ? num2-num1 : num1-num2;
break;
case 2:
// Always be positive.
operation = "*";
result = num1*num2;
break;
case 3:
// Always be positive.
operation = "/";
result = num1/num2;
break;
}
The simplest fix you can do is let the random operation complete. I assume you do multiple loops of {add,sub,mult,divide}. If the final result is negative, convert it back to positive.
But a more distributed random number generation can be done with the java runtime:
double d = java.lang.Math.random() * MAX_RANDOM_VALUE; // MAX_RANDOM_VALUE is a max value you define, like 100000
int result = (int)d;
You haven't mentioned anything about required distribution of outputs, but if it's really as simple as making sure you have no negative outputs, you could pass each output through Math.abs() before returning it...
As far as I understood you want to pick random number from the set of positive integers which can be written as a + b where a and b are integers. Since every positive integer between 1 and the maximum value of a+b, can be written like this, you just want to select a random positive integer.
int result = new Random().nextInt(maxPossibleSumValue);
Since random number generated would be in the range 0-1. You will get negative result only when you are subtracting two numbers and number2 is greater than number1. In this case you can simply swap number1 and number2 if number2 is greater than number1.
Related
How can I reorder numbers in a int number to get minimum value.
Ex:
I input a number: $71440 and I want my output is: $1447 (this is minimum value after reordering). I think I will spits the numbers in my input number first like this , after that I will reorder them. That is good algorithm?
Yes it is good if you
split by digit
sort digits
make number out of those digits
What you need is essentially a sorting of the digits of the number. So yes, your proposed method will work and it seems as a reasonable practice.
I think this does roughly what you want it to do. Assumes that the input is positive, I'm sure you can figure out how to modify it to work with negative numbers if you need that.
public static int leastValue(int input) {
String s = Integer.toString(input);
char[] c = s.toCharArray();
Arrays.sort(c);
s = new String(c);
return Integer.parseInt(s);
}
The basic idea is:
Turn value into a string
Put each character into an array
Sort the array of characters, in most character sets this will order the numbers from smallest to largest.
Turn it into a string again
Parse it into an int
For readability I think Diasiares answer is better. However a different approach would be something like this. It sorts a long with a "merge sort like" algorithm. To understand how it works please view the gif file from wikipedia
public static long sort(long num) {
long res;
if (num > 9) {
//split num into two parts(n1, n2)
int numberOfDigits = (int) Math.log10(num) + 1;
long n1 = num / (long) Math.pow(10, numberOfDigits / 2);
long n2 = num % (long) Math.pow(10, numberOfDigits / 2);
//sort each part
long s1 = sort(n1);
long s2 = sort(n2);
//merge them into one number
res = merge(s1, s2);
} else {
res = num;
}
return res;
}
/**
* merges two sorted long into on long e.g 149 and 345 will give 134459
*/
public static long merge(long num1, long num2) {
return (num1 == 0 || num2 == 0)
? num1 + num2
: num1 % 10 < num2 % 10
? num2 % 10 + merge(num1, num2 / 10) * 10
: num1 % 10 + merge(num1 / 10, num2) * 10;
}
Lets say you have:
int number1 = 5;
int number2 = 5;
char operator = '*';
How can I use the character for a calculation: number1 (operator) number2 = 5*5
Edit: It was my first time posting anything on this site and I am also an amateur, so I guess thats why I got downvoted 8x cus it was unclear but ty for the people who answered. Will be more thorough next time :)
You can use switch or a simple if condition for an example
if(operator == '*'){
int total = number1 * number2;
}else if(operator == '+'){
int total = number + number2;
}
Like this you can do the calculations
you can use switch case for your purpose.
if operator is char type than
int result=0;
switch(operator){
case '+':
result=number1+number2;
case '-':
result=number1-number2;
case '*':
result=number1*number2;
case '/':
result=number1/number2;
}
I have a Java program that generates 2 random numbers and asks a user for a mathematical operator and uses those 3 elements to ask the user an equation. I am trying to check if the answer the user inputs is correct and display either correct or incorrect.
RandomGenerator rand = new RandomGenerator();
x=rand.nextInt(-10,10);
y=rand.nextInt(-10,10);
op=readLine("Choose an operator (+, -, /, or *): ");
equ = x + op + y + "= ";
val = readInt(equ);
z = x + op + y
if(z == val) {
println("CORRECT!!");
}
if(z != val) {
println("Incorrect.");
}
The number of operators are limited so you may want to have Switch cases for each operator and calculate the values. for example
case '+':
value = a + b;
case '-':
String value = a + b;
I'm supposed to write a program for a Java Intro class that lists the prime numbers up to the number a user inputs. However, with the code I have, if the user inputs a prime number, my program won't list back that number, even though it's supposed to do so when it's prime. Could someone give me a hint as to why it's not working?
int userNum=kbd.nextInt();
if (userNum<2){
System.out.println("Not a valid number.");
System.exit(1);
}
System.out.println("The prime numbers up to your integer are:");
for (int num1 = 2; num1<userNum; num1++) {
boolean prime = true;
for (int num2 = 2; num2 < num1; num2++) {
if (num1 % num2 == 0) {
prime = false;
break;
}
}
// Prints the number if it's prime.
if (prime) {
System.out.print(num1 + " ");
}
}
For example, when I input "19," the program prints all prime numbers up to and including "17."
Thanks!
You need num1 to take the value userNum as the last value to check.
Therefore, you need to replace num1 < userNum with num1 <= userNum.
Your loop has a condition of num1 < userNum. This means that it allows all numbers below userNum. What you appear to want is all numbers below and including userNum, so you want num1 <= userNum.
The start of your loop would thus be this:
for (int num1 = 2; num1 <= userNum; num1++) {
Change this
num1<userNum
to
num1<=userNum
At the moment you stop before the two numbers are equal in your for loop.
Change the end condition of your for statement to num1<=userNum.
For some class homework I need to create a program that converts roman numerals to decimal form. I can convert just fine as long as there are no exception characters such as IV or IX. How do I check for these exceptions? My attempt was to translate both the current character and the next one into decimal, then to compare them and if the next one (going right to left) is smaller to then subtract it. The problem is that I get out of bounds errors from this.
My current code is this:
Scanner keyboard = new Scanner(System.in);
String roman;
int decimal = 0;
int number = 0;
System.out.print("Enter a Roman Numeral to convert to decimal form: ");
roman = keyboard.next();
roman = roman.toUpperCase();
for (int count = roman.length()-1; count >= 0; count--)
{
char numeral = roman.charAt(count);
switch (numeral){
case 'I':
decimal = 1;
break;
case 'V':
decimal = 5;
break;
case 'X':
decimal = 10;
break;
case 'L':
decimal = 50;
break;
case 'C':
decimal = 100;
break;
case 'D':
decimal = 500;
break;
case 'M':
decimal = 1000;
break;
default:
System.out.println("Error: Invalid character detected.");
break;
}
number = number + decimal;
}
System.out.println("The decimal equivalent is: " + number);
System.out.println("Later!");
I'm still a beginner and most of the information I see on this kind of problem uses advanced solutions that I simply don't understand. I know I need to compare the characters but I'm not sure how to do this in a way that won't eventually go out of bounds.
EDIT: Solved! After posting the question I was struck by insight and solved the problem myself. This code works but I would appreciate any insights into how to improve it!
Scanner keyboard = new Scanner(System.in);
String roman;
int decimal = 0;
int number = 0;
int last = 0;
System.out.println("This program converts Roman Numerals to decimal form.");
System.out.println("Note: Roman Numerals are I, V, X, L, C, D and M.");
System.out.println("All letters entered will be treated as capitalized.");
System.out.print("Enter a Roman Numeral to convert to decimal form: ");
roman = keyboard.next();
roman = roman.toUpperCase();
for (int count = roman.length()-1; count >= 0; count--)
{
char numeral = roman.charAt(count);
switch (numeral){
case 'I':
decimal = 1;
break;
case 'V':
decimal = 5;
break;
case 'X':
decimal = 10;
break;
case 'L':
decimal = 50;
break;
case 'C':
decimal = 100;
break;
case 'D':
decimal = 500;
break;
case 'M':
decimal = 1000;
break;
default:
System.out.println("Error: Invalid character detected.");
System.exit(0);
break;
}
if (decimal >= last){
number = number + decimal;
}
else {
number = number - decimal;
}
last = decimal;
}
System.out.println("The decimal equivalent is: " + number);
System.out.println("Later!");
Well, a decimal is ##.##, and an integer is ##, so you should probably change demical to num.
Set the number as you already do, and add a check after it for the exception character. But first ensure that it exists:
if(this character is not the first && the previous character is an exception)
adjust the number as necessary
This will avoid an out-of-bounds exceptions.