I am trying to get java to 开发者_如何学JAVAdisplay 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
Hint: Convert the integer to a String
.
- Java int to String - Integer.toString(i) vs new Integer(i).toString()
You may also find the methods String.length
and String.charAt
useful.
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.
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
精彩评论