Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

// in this program l want to return an integer in the form of 00007 not just 7 b

ID: 3623372 • Letter: #

Question

// in this program l want to return an integer in the form of 00007 not just 7 because this will produce errors when l use that number to do other calculations. How can this be done ? Basically l want corrected to return 00007 not 7 only.

import javax.swing.*;

public class test
{
public static void main ( String [] args )
{
int theInput = -1000007;
int absolute = getAbsolute(theInput);
System.out.println(absolute);
}

public static int getAbsolute (int theInput)
{
String convert = Integer.toString(theInput);
int length = convert.length();

int corrected =0;

if ( length >=5)
{
String correctedInput = convert.substring(length-5,length);
System.out.println(correctedInput);
corrected = Integer.parseInt(correctedInput);

}

return corrected;
}

}

Explanation / Answer

The only best way, I am aware of, to adding leading zeros to an integer is to convert the Integer to a String and add another String of zeros infront of the converted Integer. Whenever you wish to do any calculations with the number just convert it back to an integer.

Integers cannot be manipulated as much as Strings...

**********************************************

public static void main(String[] args) {

   int theInput = -1000007;

   int absolute = getAbsolute(theInput);

   String addZeros = "0000" + Integer.toString(absolute); //convert to a string and the zeros

   System.out.println(addZeros);

  }