私は学校の宿題に取り組んでいます。課題には、「入力として2つの単語を取得し、1つを垂直に、もう1つを水平に印刷して、それらが交差するようにする」と記載されています。
この例:
vertical: coffee
horizontal: suffering
c
o
suffering
f
e
e
コーヒーと苦しみに入ると、出力として次のようになります。
vertical: coffee
horizontal: suffering
c
o
suffering
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));
}
}