gpt4 book ai didi

java - 如果一个单词有偶数个字母,则打印该单词每行两个字母?

转载 作者:行者123 更新时间:2023-12-03 05:33:37 26 4
gpt4 key购买 nike

import java.util.Scanner;

public class TwoAtATime {

public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word with an even amount of letters:");
String w = scan.nextLine();
if(w.length() % 2 == 0) {
for(int i= 0; i<w.length(); i++) {
System.out.println(w.charAt(i));
}
} else {
System.out.println("You didnt follow directions");
}
}
}

这是我到目前为止的代码,我不知道如何让它每行打印两个而不是一个,有什么帮助吗?

最佳答案

这是一种方法:

if (w.length() % 2 == 0) {
for(int i = 0; i < w.length(); i+=2) {
System.out.print(w.charAt(i));
System.out.println(w.charAt(i+1));
}
}

或者你可以使用String::substring来实现。

if (w.length() % 2 == 0) {
for(int i = 0; i < w.length(); i+=2)
System.out.println(w.substring(i,i+2));
}

关于java - 如果一个单词有偶数个字母,则打印该单词每行两个字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25677166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com