tags:

views:

77

answers:

3

Hi, I am trying to get java to display the middle digit of a 1-4 digit integer, and if the integer has an even number of digits i would get it to display that there is no middle digit.

I can get the program to take get the integer from the user but am pretty clueless as how to get it to pick out the middle digit or differentiate between different lengths of integer.

thanks

A: 

This sounds like it might be homework, so I will stay away from giving an exact answer. This is much more about how to display characters than it is about integers. Think about how you might do this if the questions was to display the middle letter of a word.

unholysampler
+1  A: 

Hint: Convert the integer to a String.

You may also find the methods String.length and String.charAt useful.

Mark Byers
A: 

Something like this?

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);

        System.out.print("Enter an integer: ");
        while (!s.hasNextInt()) {
            s.next();
            System.out.println("Please enter an integer.");
        }

        String intStr = "" + s.nextInt();
        int len = intStr.length();

        if (len % 2 == 0)
            System.out.println("Integer has even number of digits.");
        else
            System.out.println("Middle digit: " + intStr.charAt(len / 2));
    }
}

Uhm, I realized I might just have done someones homework... :-/ I usually try to avoid it. I'll blame the OP for not being clear in this case

aioobe