亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

掛信計劃.

掛信計劃.

FFIVE 2023-07-19 15:50:54
這幾天在練習JAVA的問題,遇到了這樣的問題:I/p: I Am A Good BoyO/p:I A A G B  m   o o      o y      d這是我的代碼。System.out.print("Enter sentence: ");String s = sc.nextLine();s+=" ";String s1="";for(int i=0;i<s.length();i++){    char c = s.charAt(i);    if(c!=32)    {s1+=c;}    else    {        for(int j=0;j<s1.length();j++)        {System.out.println(s1.charAt(j));}        s1="";    }}問題是我無法進行此設計。我的輸出是每行中的每個字符。
查看完整描述

1 回答

?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

首先,您需要用空格作為分隔符來劃分字符串并將它們存儲在字符串數組中,您可以通過編寫自己的代碼將一個字符串劃分為多個字符串來完成此操作,或者您可以使用名為的內置函數split()


將字符串“拆分”為字符串數組后,只需迭代字符串數組,次數與最長字符串出現的次數相同,因為這是您要打印的最后一行(從共享輸出中可以理解),即,d來自 string Good,因此迭代字符串數組,直到打印最大/最長字符串中的最后一個字符,然后從那里退出。


您需要在迭代字符串數組時處理任何邊緣情況,例如沒有任何額外字符可供打印的字符串,但需要為下一個具有輸出順序字符的字符串打印空格。


以下是您可以參考的代碼段,但請記住在進一步閱讀之前嘗試上面解釋的邏輯,


import java.io.*;

import java.util.*;

public class MyClass {

    public static void main(String args[]) throws IOException{

        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        Scanner sc = new Scanner(System.in);

        String[] s = sc.nextLine().split(" ");

        // Split is a String function that uses regular function to split a string, 

        // apparently you can strings like a space given above, the regular expression 

        // for space is \\s or \\s+ for multiple spaces

        int max = 0;

        for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length

        int count = 0;

        while(count<max){ // iterate till the longest string exhausts

            for(int i=0;i<s.length;i++){

                if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character

                else System.out.print("  "); // Two spaces otherwise

            }

            System.out.println();count++;

        }

    }

}

編輯:我正在分享下面的字符串輸出This is a test Input


T i a t I 

h s   e n 

i     s p 

s     t u 

        t   


查看完整回答
反對 回復 2023-07-19
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號