How To Use AND Statements With Java [duplicate] - java

This question already has answers here:
How to concatenate int values in java?
(22 answers)
Closed 3 years ago.
I am writing some code that gives me a random string of numbers, they need to list under on integer but each number needs to be under a different math.random. For Instance, if two separate number are listed like 5 and 7, I don't want it to print 12, I would like it to print 57. But i don't want to use the System.out.println(Number1+Number2); way.
I have tried using the "&" Sign multiple ways but none seem to work.
int Number1 = 1 + (int)(Math.random() * ((5) + 1));
int Number2 = 1 + (int)(Math.random() * ((5) + 1));
int Number3 = 1 + (int)(Math.random() * ((5) + 1));
int finalcode=Number1&Number2&Number3;
System.out.println("Promo Code Genorator:");
System.out.println(" ");
System.out.println("Your Promo Code Is: "+finalcode);
Instead, what happens is it picks the lowest number from there and prints them. Any Ideas?

It is suggested to use String if you want to combine a variety of numbers together.
You can write it like this:
int Number1 = 1 + (int)(Math.random() * ((5) + 1));
int Number2 = 1 + (int)(Math.random() * ((5) + 1));
int Number3 = 1 + (int)(Math.random() * ((5) + 1));
String finalcode = String.valueOf(Number1) + String.valueOf(Number2) + String.valueOf(Number3);
System.out.println("Promo Code Genorator:");
System.out.println(" ");
System.out.println("Your Promo Code Is: "+finalcode);
If you really need your final code to be a integer, you can use
int finalcode = Integer.parseInt(String.valueOf(Number1) + String.valueOf(Number2) + String.valueOf(Number3));
in which Integer.parseInt(String string) takes in a string and return a integer.
FYI, if you want to convert it to long instead of integer, use Long.parseLong(String string).
Hope this helps!

This seems like a nice problem to solve using streams and functional programming.
import java.util.stream.Stream;
import java.util.stream.Collectors;
public class LazyNumbersTest {
public static void main(String[] args) {
int result = Integer.parseInt(
Stream.generate(() -> (int)(Math.random() * ((5) + 1)))
.peek(System.out::println)
.limit(3)
.map(Object::toString)
.collect(Collectors.joining(""))
);
System.out.println("Promo Code Generator:");
System.out.println(" ");
System.out.println("Your Promo Code Is: " + result);
}
}
It's an infinite stream of random numbers, from which we pluck the first 3 and convert them to string, then join them together and convert to an integer.
If you want more or less numbers in the calculation, just change the number in limit. It's a shame I couldn't include the parseInt in the stream of fluent operations (without making it really ugly).

Related

How to make two random generated integers divisible by each other in java?

I am a newbie and trying to write a java code in my android studio project to generate two random integers up to 100(included) and what I am actually trying to do is to check if the first random integer is bigger than the second random integer and I also want to check if the first rand.num. is divisible by the second rand.num.
So far, I am able to generate two rand. nums in OnCreate method by using Math.random():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Objects.requireNonNull(getSupportActionBar()).hide();
setContentView(R.layout.activity_division);
randomFirstNum = (int) (Math.random() * 100 + 1);
randomSecondNum = (int) (Math.random() * 100 + 1);
and I am trying to write two functions.
The first function is to generate a question string depending on the rand. integer numbers. i.e.
private void generateQuestion(int randomFirstNum, int randomSecondNum) {
String firstNum = String.valueOf(randomFirstNum);
String secondNum = String.valueOf(randomSecondNum);
String question = null;
if(randomFirstNum % randomSecondNum == 0 && randomFirstNum > randomSecondNum){
question = firstNum + " ÷ " + secondNum + " = ?";
} else if(randomSecondNum % randomFirstNum == 0 && randomSecondNum > randomFirstNum){
question = secondNum + " ÷ " + firstNum + " = ?";
}
textViewQuestion.setText(question);
}
And the next function is to find the result of the division question. i.e.
private int findResult(int randomFirstNum, int randomSecondNum) {
if (randomFirstNum > randomSecondNum && randomFirstNum % randomSecondNum == 0){
return randomFirstNum / randomSecondNum;
} else if {(randomSecondNum > randomFirstNum && randomSecondNum % randomFirstNum == 0)
return randomSecondNum / randomFirstNum;
}
}
I know the code is not right and there are missing parts, I am just stucked here. But I hope I was able to explain my issue a bit. I want to be able to generate a question where the first rand.integer will be either bigger than the second rand.integer or equal to the second rand.integer on the secreen ( i.e "20 ÷ 2 = ?" or "21 ÷ 7 = ?" or 11 ÷ 11 = ? - There might be a chance that two rand. integers are gonna be the same numbers :)
I am just stucked at the point of what to do if the both integers are odds (i.e. "17 ÷ 11 = ?" I don't want to end up with these kind of questions :)
I would appreciate a lot if someone can shad some light on my question and hopefully provide a clear answer for me! :) Thank you so much for sticking around and spend your time to read my question.
First number can be generated without any constraints, but to cater first number must be divisible by second number and first number >= second number requirement, you have a constraint that second number must be the divisor of first number as it will fulfil both requirements.
So you can generate first number from 1 to 100 and whatever that number is, find out its divisors and pick a random divisor from the divisors list.
private static void generateQuestion() {
int first = (int) (Math.random() * 100 + 1);
List<Integer> firstNumDivisors = getDivisors(first);
int divisorsRandIndex = (int) (Math.random() * firstNumDivisors.size());
int second = firstNumDivisors.get(divisorsRandIndex);
System.out.println(first + " " + second);
// Create your question from first and second numbers here
}
private static List<Integer> getDivisors(int number) {
List<Integer> divisors = new ArrayList<>();
for (int i=1;i<=number;i++)
if (number%i==0)
divisors.add(i);
return divisors;
}

How can I use a formula in a for loop in java

I am a beginner java programmer, studying off basic youtube videos and overflow forums, and i came across a question on an textbook sheet that asked me to use a for loop program and print this table out as well as fill in each blank
Number Square Cube (n+1)/(2n-18)
______________________________________
1 # # #
2 # # #
3 # # #
4 # # #
5 # # #
I thought I should try it out to test myself. I came up with the following program that works perfectly for the Number, Square and Cube part of the table, but I don't understand how to generate the numbers using the given formula. The formula I initialized as a variable (double) doesn't print the actual results, and I honestly don't have a clue as to what to do. I'd rather a simple explanation than a complex one and simple changes to the code rather than complex. As I said I am a beginner, and many different methods may go right over my head. Thank you so much in advance (also an extra task asks that I print out the sums of each column. I don't know how to do that at all, and would like an explanation if possible, but wouldn't mind if I don't receive one)
int number;
int maxValue;
Scanner keyboard = new Scanner(System.in);
System.out.println("how many numbers do you want the max value to be");
maxValue = keyboard.nextInt();
System.out.println("Number\tSquare\tCube (n+1)/(2n-18)");
System.out.println("--------------------------------");
for (number = 1; number <= maxValue; number++) {
double formula = (number + 1) / (number * 2);
System.out.println(
number + "\t\t\t" + number * number + "\t\t\t" +
number * number * number + "\t\t\t" + formula);
}
Your formula should be:
double formula = (double)(number + 1) / (number * 2 - 18);
Two issues:
missing -18
the / is doing an integer division unless you cast at least one operand into a double
Oh! one more thing: when number==9, there is a division by zero. A double division gives you "Infinity" whereas an integer division throws an exception.
Your formula does not match the textbook. Try this:
System.out.println("Number\tSquare\tCube (n+1)/(2n-18)");
System.out.println("--------------------------------");
for (int number=1; number <= maxValue; number++) {
double square = Math.pow(number, 2);
double cube = Math.pow(number, 3);
double formula = (number + 1) / (number * 2 - 18);
System.out.println(number + "\t\t\t" + square + "\t\t\t" + cube + "\t\t\t" + formula);
}
Note: As pointed out by #MauricePerry an input of 9 would cause a divide by zero. Rather than try to catch this unchecked exception, I think you should control your input values so that this does not happen.
Your formula is not correct and you are missing few \t.
int number;
int maxValue;
Scanner keyboard = new Scanner(System.in);
System.out.println("how many numbers do you want the max value to be");
maxValue = keyboard.nextInt();
System.out.println("Number\t\tSquare\t\tCube \t\t(n+1)/(2n-18)");
System.out.println("-------------------------------------------------------");
for (number = 1; number <= maxValue; number++) {
double formula = (number + 1) / (number * 2 - 18);
System.out
.println(number + "\t\t" + number * number + "\t\t" + number * number * number + "\t\t" + formula);
}
I'm not sure which outputs are you getting, but it seems to me you're using integer division when trying to get the result of (n+1)/(2n-18).
Try using:
double decimalNumber = (double) number;
double formula = (decimalNumber + 1) / (decimalNumber * 2 - 18);

Trying to make a simple type math game for my 4 year old.

Trying to make a simple type math game for my 4 year old. Having issue with my first operation. I am trying to generate to random numbers then have number 1 and number 2 displayed for him to answer. Problem is println text - first number text - second number - text
Basic syntax i am trying to get to work:
int SIDES = 6;
int a = 1 + (int) (Math.random() * SIDES);
int b = 1 + (int) (Math.random() * SIDES);
System.out.println("What is " +a "+" +b "=");
That last line is not correct. Please help.
You are missing an addition operator for your String in println:
System.out.println("What is " + a "+" + b "=");
// ^ Missing '+' operator
So you should change it to this:
System.out.println("What is " + a + "+" + b "=");

Getting the same random number

I want to generate a random number to apply to some arrays in order to get different elements in each execution.
The arrays contain names of sport products (product,size,price,etc). By doing this, I want to make random products that would go into a String, but in each execution of the program, I get the same product.
Where is the problem?
Here is the code in the class generaProductos:
public void generaProductos() {
int num;
for (int i=0;i<3;i++){
num = (int) Math.random() * 3;
String cliente = tipoProducto[num] + " " + deporte[num] + " " +
destinatario[num] + " " + color[num] + " " + tallaRopaAdulto[num]
+ " " + preciosIVA[num];
System.out.println(cliente);
}
return;
}
And here is where I call generaProductos() method in main:
switch (opt){
case 1:
generaProductos alm = new generaProductos();
alm.generaProductos();
When I execute my code, I always receive this:
Botas Futbol Hombre Marron S 16.99
Botas Futbol Hombre Marron S 16.99
Botas Futbol Hombre Marron S 16.99
(In English it would be Football boots men brown size S 16.99)
You cast a floating point value between 0 and 1 (exclusive) to int, which results in 0, and then multiply 0 by 3, which is still 0.
change
(int) Math.random() * 3
to
(int) (Math.random() * 3)
num = (int) Math.random() * 3;
will always be 0, because of order of precedence.
Math.random() is always < 1 so casting it to int will give you 0, then you multiply, still getting 0.
You can use Math Library of java to generate Random Integers. If you use Math.random() then you will get random number only within 0.0 to 0.1
If you want to take random integers between large range of integers then you can use following function by providing two integer inputs i.e. Min & Max No.
public static int RandInt(int max, int min){
return ((int) (Math.random()*(max - min))) + min;
}

Printf formatting for decimal places [duplicate]

This question already has answers here:
Format Float to n decimal places
(11 answers)
Closed 9 years ago.
I have the following code and my output is working but I don't know how to use the printf to make this output (66.67%) instead of 66.66666666666667%, just for an example. Any help is appreciated!
public static void evenNumbers(Scanner input)
{
int numNums = 0;
int numEvens = 0;
int sum = 0;
while (input.hasNextInt())
{
int number = input.nextInt();
numNums++;
sum += number;
if (number % 2 == 0)
{
numEvens++;
}
}
System.out.println(numNums + " numbers, sum = " + sum);
System.out.println(numEvens + " evens " + (100.0* numEvens / numNums + "%"));
}
Thank you
You can use the printf modifier %.2f to get only two decimal places.
Use String.format and %.2f:
String.format("%d evens %.2f%%", numEvens, 100.0 * numEvens / numNums);
You can use Math.round on the answer before you print it:
System.out.println(numEvens + " evens " + Math.round((100.0* numEvens / numNums)*100)/100.0d + "%"));
Don't use printf here. Instead, use MessageFormat or DecimalFormat.getPercentInstance().
String format = "{numbers: {0, number, integer}," +
" sum: {1, number, integer}\n" +
"evens: {2, number, integer}," +
" {3, number, percent}"
String message = MessageFormat.format(format,
new Object[]{numNums, sum, numEvens, ((double) numEvens)/ numNums)});
System.out.println(message);

Categories

Resources