我正在為學校做一份家庭作業,作業規定“輸入兩個單詞,并垂直打印一個單詞,水平打印一個單詞,以便它們相交”。一個例子:vertical: coffeehorizontal: suffering c osuffering f e e當我進入咖啡和痛苦時,我得到以下輸出:vertical: coffeehorizontal: suffering c osuffering f f e e我的代碼如下:public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.print("vertical: "); String vertical = kb.next().toLowerCase(); System.out.print("horizontal: "); String horizontal = kb.next().toLowerCase(); boolean indexed = true; int indexOf = 0; StringBuilder spaces = new StringBuilder(); while (indexed) { for (int i = 1; i <= vertical.length()-1; i++) { String found = vertical.substring(i - 1, i); spaces.append(" "); if (horizontal.contains(found)) { indexOf = i; indexed = false; break; } } } for (int i = 1; i <= vertical.length(); i++) { if (i == indexOf) { System.out.println(horizontal); } System.out.println(spaces + vertical.substring(i - 1, i)); } }
1 回答
紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
這里有一些提示。
使用indexOf查找交點。
水平字的索引是垂直字符縮進的距離。找到索引后,可以通過執行以下操作輕松獲得間距:
spaces = " ".substring(0,indexOf);
垂直單詞的索引是在什么點打印水平單詞而不是垂直字符。
請記住在沒有共同字符時處理特殊情況。
您不需要嵌套的 while 和 for 循環。只需要其中之一即可。
添加回答
舉報
0/150
提交
取消
