Created
June 9, 2014 08:46
-
-
Save nshiba/45e3c44a1427149a35ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ex1; | |
import java.util.Scanner; | |
public class InputTriangle { | |
public static void main(String[] args) { | |
// TODO 自動生成されたメソッド・スタブ | |
System.out.println("何段にしますか?"); | |
InputTriangle tri = new InputTriangle(); | |
Scanner s = new Scanner(System.in); //文字入力の準備 | |
int high = s.nextInt(); //高さを代入 | |
while (true) { //何度でも実行 | |
System.out.println("1,2,3のどれかを入力してください"); | |
int i = s.nextInt(); //入力された数値を変数に代入 | |
if (i == 1) { //1だった場合 | |
tri.createTriangle1(high); | |
} | |
if (i == 2) { //2だった場合 | |
tri.createTriangle2(high); | |
} | |
if (i == 3) { //3だった場合 | |
tri.createTriangle3(high); | |
} | |
} | |
} | |
//1だった場合のときの三角形を作るメソッド | |
public void createTriangle1(int high) { | |
int num = high + 1; //*の表示するのは高さ+1、 | |
//頂点が右側なので初期値は最大値を代入 | |
for (int j = 0; j < high; j++) { //高さの分だけ繰り返し | |
num--; //右からなので初期値から1ずつ減らしていく | |
for (int k = 0; k < high + 1; k++) { //*を表示する分だけ繰り返し | |
if (k >= num) { //表示する範囲 | |
System.out.print("*"); | |
} else { | |
System.out.print(" "); | |
} | |
} | |
System.out.println(); | |
} | |
} | |
//2だった場合のときの三角形を作るメソッド | |
public void createTriangle2(int high) { | |
//前半は1の時と同じ処理 | |
int num = high + 1; | |
for (int j = 0; j < high; j++) { | |
num--; | |
for (int k = 0; k < high; k++) { | |
if (k >= num) { | |
System.out.print("*"); | |
} else { | |
System.out.print(" "); | |
} | |
} | |
//後半は3のときと同じ処理だが頂点が一つ下がる | |
for (int l = high; l > 0; l--) { | |
if (l >= num) { | |
System.out.print("*"); | |
} else { | |
System.out.print(""); | |
} | |
} | |
System.out.println(); | |
} | |
} | |
public void createTriangle3(int high) { | |
int num = 0; //頂点が左にあるので初期値は0 | |
for (int j = 0; j < high; j++) { //高さの分だけ繰り返し | |
num++; //左からなので0から1ずつ足していく | |
for (int k = 0; k < high + 1; k++) { //*を表示する分だけ繰り返し | |
if (k <= num - 1) { //表示する範囲 | |
System.out.print("*"); | |
} else { | |
System.out.print(" "); | |
} | |
} | |
System.out.println(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment