【问题标题】:How to make an if statement to check for if a String is greater than 10 characters如何制作 if 语句来检查字符串是否大于 10 个字符
【发布时间】:2018-03-16 12:40:58
【问题描述】:

到目前为止,我已经能够弄清楚字符串中有多少个字符,但我似乎无法找出一个 if 语句来检查字符是否超过 10 个字符,以及它是否只显示前 10 个字符.

import java.text.*

public class StringPracticeCoding

{
 public static void main (String[] args)

   {
      //local constants

  //local variables

  //phrase input by the user
  String sentence = "I am somebody, I am worthy";


  /********************   Start main method  *****************/

  System.out.println("Length of String: " + sentence.length());

      System.out.println(sentence.substring(0,10));

是的,它必须是一个 if 语句

【问题讨论】:

  • 如何检查一个数是否大于 10?

标签: java string if-statement


【解决方案1】:

我不确定这个问题的目的。你已经完成了sentence.length() - 无论如何这里是测试它是否超过 10 个字符的代码:-

String sentence = "I am somebody, I am worthy";
if (sentence.length() > 10) {
    // Do stuff
} else {
    // Do different stuff
}

【讨论】:

  • 非常感谢,是的,我有点扼杀了标题,我知道如何显示最多 10 个我只是无法弄清楚 if
【解决方案2】:
public class TestProject {

    public static void main (String[] args)throws IOException {
        String sentence = "I am somebody, I am worthy";
        if(sentence.length() > 10){
            System.out.println("Greater then 10");
        } else {
            System.out.println("Less then 10");
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2017-03-09
    • 2015-05-29
    相关资源
    最近更新 更多