简体   繁体   English

如果一个单词有5个字母,则每行打印一个单词,如果没有,则仅打印该单词?

[英]if a word has 5 letters print the word with one letter per line if not then just print the word?

import java.util.Scanner;

public class SeperateLetters 
{

    public static void main(String[] args)
    {
        Scanner scan= new Scanner(System.in);
        System.out.println("Enter a word:");
        String w= scan.nextLine();
        for(int i=0; i<w.length();i++)
            System.out.println(w.charAt(i));    
    }
}

This is what I have so far and I can't figure how to make it so that if the word is 5 letters or longer to print it one letter per line and if not to just print the word. 这就是我到目前为止所掌握的,我无法弄清楚如何制作该单词,如果单词是5个字母或更长,则每行打印一个字母,而不是仅打印单词。 So far it'll just print any word with one letter per line. 到目前为止,它将仅打印每行一个字母的任何单词。

You are very close. 你很亲密 The only thing missing is an if-else conditional statement, to check whether the word has a length of five. 唯一缺少的是if-else条件语句,以检查单词的长度是否为5。 Without this check, you will always print the string one character per line, regardless of its length. 如果不进行此检查,则无论长度如何,您始终将每行打印一个字符。

import java.util.Scanner;

public class SeperateLetters {

    public static void main(String[] args) {
        Scanner scan= new Scanner(System.in);
        System.out.println("Enter a word:");
        String w = scan.nextLine();
        if (w.length() >= 5) {     // print one char per line if length is 5
            for (int i = 0; i < w.length(); i++)
                System.out.println(w.charAt(i));
        } else {
            System.out.println(w); // otherwise, print the whole string
        }
    }
}

使用if-else语句检查是否w.length() == 5

public class SeperateLetters { 公共类SeperateLetters {

public static void main(String[] args)
{
    Scanner scan= new Scanner(System.in);
    System.out.println("Enter a word:");
    String w= scan.nextLine();

    if( w.length() > 5) 
    {    
        for(int i=0; i<w.length();i++) 
        {
            System.out.println(w.charAt(i));
        }    
    }
}

} }

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

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