Nathan Daniels - 1 year ago 88
Java Question

# Return first and last digits of an integer using while loop

I've been trying to write a program that uses a while loop to return the first and last digits entered.

Here's what I've got so far:

``````import java.util.Scanner;
public class FirstLastInt {
public static void main(String[]args)
{
int fdig, ldig, num;

Scanner in = new Scanner(System.in);

System.out.println("Enter an Integer.");
num = in.nextInt();

ldig = num%10;

while (num > 0)
{ fdig = num/10;
num = num/10;

System.out.println("The first digit is " + fdig + ", and the last digit is " + ldig + ".");
}
}
``````

num is the integer entered, fdig is to be the first digit, and ldig is to be the last digit.

I figured the last digit will always be num%10, and I realized so far using the while loop like it's written will return the first digit......Along with a bunch of other numbers I don't really need.

For example:

``````run:
Enter an Integer.
98884
The first digit is 9888, and the last digit is 4.
The first digit is 988, and the last digit is 4.
The first digit is 98, and the last digit is 4.
The first digit is 9, and the last digit is 4.
The first digit is 0, and the last digit is 4.
BUILD SUCCESSFUL (total time: 3 seconds)
``````

It looks like the loop runs before and after I get the digit I want. Is there anyway to specify which line I'd like printed? (In the example, it's "The first digit is 9, and the last digit is 4.")

If you want to keep using your own code to see how it can be achieved that way then change your while condition and take system print outside:

``````import java.util.Scanner;
public class FirstLastInt {
public static void main (String[] args) {
int ldig, num;

Scanner in = new Scanner(System.in);

System.out.println("Enter an Integer.");
num = in.nextInt();

ldig = num % 10;

// keep looping num until it is in the range of 0-9
while (num >= 10) {
num = num / 10;
}
//initialize fdig variable and set it equal to num, just to make things clearer
int fdig = num;

System.out.println("The first digit is " + fdig + ", and the last digit is " + ldig + ".");
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download