Java Random Print - java

I generate a random number between 0-99 using this :
int num2= (int)(Math.random() * ((99) + 1));
When the number is below 10 I want it to print with a 0num2
So if the number is 9 it would be 09.
How can I get it to print this?

You can use the format() method:
System.out.format("%02d%n", num2);
%02d prints the argument as a number with width 2, padded with 0's
%n gives you a newline

System.out.println((num2 < 10 ? "0" : "") + num2);
One liner :-)

String str;
if (num2 < 10) str = "0" + num2;
else str = "" + num2;
System.out.println("Value is: " + str);

Have a look at PrintStream.format, which will allow you to print using specified widths and padding characters.
System.out is a PrintStream, so you can use System.out.format in place of println.
Your case is pretty simple, look over the syntax for the format string:
System.out.format("%02d", num2);
Here 2 is the minimum width, and the 0 specifies that the result be padded with zeros, if the width of the result is less than 2.

You can use the approach of removing an extra digit instead.
System.out.println(("" + (int)(Math.random()*100 + 100)).substring(1));
or to use the String format.
String s = String.format("%02d", (int)(Math.random()*100));
or
System.out.printf("%02d", (int)(Math.random()*100));
I would generally use the last option as it allows you to combine other strings and print them.

Related

Printf in Java with variable spaces before the output

With printf I can decide how many space characters should be before the variable i that I want to print. In the example below, it is 10. Is it possible to have there a variable instead of the number 10? So that the spaces characters depend on the value of a variable?
System.out.printf("%10d" , i);
The format string is still a string, so assuming a width variable System.out.printf("%" + width + "d", x); does the trick.
So for example
var width = 10; var x = 123;
System.out.printf("%" + width + "d", x);
prints 123 (7 leading spaces + 3 digits = 10), while
var width = 3; var x = 123;
System.out.printf("%" + width + "d", x);
prints 123
Define a lambda to create the desired width and then call that prior to printing the value.
Function<Integer, String> format = width-> "%%%dd\n".formatted(width);
int x = 4567;
System.out.printf(format.apply(10),x);
System.out.printf(format.apply(5),x);
// or create it once for multiple printf calls.
String form = format.apply(3);
System.out.printf(form, 2);
System.out.printf(form, 4);
prints
4567
4567
2
4
%%%dd - the first % escapes the second so on the last %d formats the width value.
then that format string is returned and used to format the supplied argument in the printf statement

How would I add two int that are in the same array to each other and convert them into an int. In the Luhn Algorithm

I am trying to add two parts of an array together to go into an int value. I am using Luhn algorithm to figure out of a credit card is a valid credit card. We are only using 6 digit credit card's just to make sure no one enter's a real credit card number. The part I am confused on is when I go to split a number that is above 10 and add it together. Example if the algorithm was to give me 12 I would need to separate it into 1 and 2 and then add them together to equal 3. I believe I am splitting it currently in the code but when I go to add them together I get some number that makes no since. here is a section of the code with some notes about it.
I have printed out numbers in certain places to show myself what is going on in certain places. I have also added in some comments that say that either the number that is printed out is what is expected, and some comments for when there isn't something I expected
int[] cardNumber = new int[]{ 1,2,3,4,5,5};
int doubleVariablesum = 0;
int singleVariablesum = 0;
int totalSum = 0;
int cutOffVar = 0;
String temp2;
for (int i = cardNumber.length - 1; i >= 0;) {
int tempSum = 0;
int temp = cardNumber[i];
temp = temp * 2;
System.out.println("This is the temp at temp * 2: " + temp);
temp2 = Integer.toString(temp);
if (temp2.length() == 1) {
System.out.println("Temp2 char 0: "+ temp2.charAt(0));
// this prints out the correct number
// Example: if there number should be 4 it will print 4
tempSum = temp2.charAt(0);
System.out.println("This is tempSum == 1: " + tempSum);
// when this goes to add temp2.charAt(0) which should be 4 it prints out //something like 56
} else {
System.out.println("TEMP2 char 0 and char 1: " + temp2.charAt(0) + " " + temp2.charAt(1));
// this prints out the correct number successfully spited
tempSum = temp2.charAt(0) + temp2.charAt(1);
System.out.println("This is tempSum != 1: " + tempSum);
// but here it when I try to add them together it is giving me something
// like 97 which doesn't make since for the numbers I am giving it
}
doubleVariablesum = tempSum + doubleVariablesum;
System.out.println("This is the Double variable: " + doubleVariablesum);
System.out.println();
i = i - 2;
}
Since you are converting the number to a string to split the integer, and then trying to add them back together. You're essentially adding the two characters numerical values together which is giving you that odd number. You would need to convert it back to an integer, which you can do by using
Integer.parseInt(String.valueOf(temp2.charAt(0)))
When adding char symbols '0' and '1' their ASCII values are added - not numbers 0 and 1.
It is possible to use method Character::getNumericValue or just subtract '0' when converting digit symbol to int.
However, it is also possible to calculate sum of digits in a 2-digit number without any conversion to String and char manipulation like this:
int sum2digits = sum / 10 + sum % 10; // sum / 10 always returns 1 if sum is a total of 2 digits
Seems like charAt() type casts into integer value, but the ascii one. Hence for the characters '0' and '1', the numbers 48 and 49 are returned resulting in a sum of 97. To fix this, you could just assign temp2 to (temp / 10) + (temp % 10). Which actually splits a two digit integer and adds their sum.
You need to be aware of the following when dealing with char and String
Assigning the result of charAt(index) to an int will assign the ASCII value and not the actual integer value. To get the actual value you need to String.valueOf(temp2.charAt(0)).
The result of concatenating chars is the sum of the ASCII values.
eg if char c = '1'; System.out.println(c + c); will print "98" not "11".
However System.out.println("" + c + c); will print "11". Note the "" will force String concatenation.

From given integer value, how to print first two digit and then last two digit values in java

int a=1256;
int b=34;
Now i want to print as below.
System.out.println(**First two digit from (a)** +b+ **and last two digit from (a)**);
help me out of this!
You might want to use Integer.toString(value) and than print the substring.
Something like that:
Integer a = new Integer(1256);
String aStr = a.toString();
System.out.println(aStr.substring(0,2));
The first digit of an int can be given with a while loop : divide by 10 until you're under 10, or use the String version which is easier to use
1st digit : String.valueOf(number).charAt(0)
last digit : number%10
Then concatenate them all, the ""+ is to avoid mathematic sum between them
System.out.println("" + String.valueOf(a).charAt(0) + b + (a%10)) ;
Since we need first 2 digits we should divide it by 100.
For the last 2 digits, apply mod 100 on the given number to get remainder which is the last 2 digits.
public class Main
{
public static void main(String[] args) {
int a=1256;
int b=34;
System.out.println(a/100+"" +b+ ""+a%100); // Output: 123456
System.out.println(a/100+" " +b+ " "+a%100); // Output: 12 34 56
}
}
The first System.out.println is without spaces and the second System.out.println is with spaces.

How To Use AND Statements With Java [duplicate]

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).

Why do i get this output in this simple java code?

Why do i get 10 2030 as the output? I can't figure out why it doesn' t output it as 10 50?
public class Testing1 {
public static void main(String args[]) {
int num1 = 10, num2 = 20, num3 = 30;
System.out.println(num1 + " " + num2 + num3);
This is because Java evaluates expressions with a 'precedence'. In this case, it starts at the left, and it works to the right, because the operations are all + they all have the same precedence so the left-to-right order is used. In the first 'addition', you add a number and a String. Java assumes the '+' is meant to do String concatenation, and you get the result "10 ". You then add that to 20, and get the (String concatenation) result "10 20". Finally you add the 30, again adding to a String, so you get the result"10 2030"`.
Note, if you change the order of your operations to:
System.out.println(num1+num2+" "+num3);
the num1+num2 will be treated as numbers, and will do numeric addition, giving the final result: "30 30"
To get the correct value you can change the evaluation order by making a sub-expression by using parenthesis (...) (which have a higher operator precedence than '+', and get the result with:
System.out.println(num1 + " " + (num2 + num3));
The num2 + num3 is evaluated first as a numeric expression, and only then is it incorporated as part of the string expression.
look up operator precedence and how + works when different types of operands
In java '+' operator operates differently for different operands.
For Integers operands it operates as integer addition
For strings it operates as concatenation.
Evaluation of java expression is based on precedence rule.In your case there is only '+' operator so evaluation is from left to right.
For integer and string operands java '+' operator performs string concatenation.
So num1 + " " + num2 + num3 execution is as
(integer + String) + int + int
(String + int)+ int
String + int
Your desired out put can be achieved by forcing the precedence for (num2 + num3) using parenthesis.

Categories

Resources