简体   繁体   English

如何在java中显示中间数字

[英]How to display the middle digit in java

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. 我试图让java显示1-4位整数的中间数字,并且如果该整数具有偶数个数字,我会得到它以显示没有中间数字。

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 . 提示:将整数转换为String

You may also find the methods String.length and String.charAt useful. 您可能还会发现String.lengthString.charAt方法很有用。

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 在这种情况下,我会责怪OP不清楚

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM