Home > Net >  Printing out 3 of numbers in java
Printing out 3 of numbers in java

Time:04-29

The output value is 100000 to 10 random natural numbers What should I do to print out only from the right end to the third? And if you print it out with multiple of ten, an error appears so, if we get a multiple of 10, i want to put out 010 something

for example, input -> 6545 output -> 545, input -> 27 output -> 027

and i'm using java. pls help me

CodePudding user response:

Assuming your inputs are actually ints:

System.out.printf("d",inputvalue00); 

should give the result you want:

  • "d" forces output with zero padding
  • inputvalue00 calculates the remainder of division by 1000 (modulo), which will chop off all digits to the left of the three last

CodePudding user response:

You can transform an Int to a String with String.valueOf(i). Then, you only have to take the 3 last characters of the string and adding 0. Because your "027" is a String, it isn't an Int

CodePudding user response:

    public static void main(String... args) {
  
    Random rand = new Random();
    int upperbound = 100000;
    int lowerbound = 10;
    int random_integer = rand.nextInt(upperbound - lowerbound)   lowerbound;

    String output = String.valueOf(random_integer);
    String finaloutput = output;
    if (output.length() <= 3) {

        for (int i = 0; i < 3 - output.length(); i  ) {
            finaloutput = "0"   finaloutput;
        }
    } else {
        finaloutput = output.substring(0, 3);
    }

    System.out.println(random_integer   "->"   finaloutput);

}
  •  Tags:  
  • java
  • Related