0

I've been getting problems with the Math.min more so when I try to do

System.out.println(Math.min(0700,1400));

it returns 448 instead of 0700 the minimum value. I know it works when the 0 isn't there, but due to user input I kinda need it to be formatted that way. Is there any way around this, maybe like a substitute method or a quick efficient way to get rid of the 0 before I put it in Math.min parameter. I could do an if statement that checks then parses a substring, but that seems to tedious and inefficient. Any ideas?

Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43
Nebulor
  • 23
  • 2
  • 1
    How does your user input produce `0700` unless you're specifically parsing it to base 8? – Jacob G. Oct 03 '20 at 04:03
  • 2
    Does this answer your question? [Why is 08 not a valid integer literal in Java?](https://stackoverflow.com/questions/7218760/why-is-08-not-a-valid-integer-literal-in-java) (0700 is valid, but it goes wrong for the same reason, nothing to do with `Math.min`) – harold Oct 03 '20 at 04:06
  • 0700 is Octal integer man – Rony Nguyen Oct 03 '20 at 04:08
  • Rather than substring you could take the user input and parse it, for example, `Integer.parseInt(input);`, will convert it to a valid integer `700`. – sorifiend Oct 03 '20 at 04:11
  • The whole point was to have the program read military time, but I didn't consider that military time and base 8 have a few things in common – Nebulor Oct 03 '20 at 04:15

1 Answers1

0

Call the following function on any of the inputs with leading 0s (given that they are strings), then convert the new string into an integer with Integer.parseInt and then proceed with your normal Math.min function on this final integer:

//This function takes in a string that is of the form of a integer with 
//leading zeros i.e. it would take in 0008000 and return the string 8000
public static String removeZeros(String str) {
    String regexpattern = "^0+(?!$)"; //regex pattern to find leading zeros
    str = str.replaceAll(regexpattern, ""); //remove leading zeros in string
    return str; //return string
}
Fried Noodles
  • 287
  • 2
  • 8