-
콘솔화면에 구구단 출력하기과제/7월 2023. 7. 3. 21:55
<과제>
참고:
Formatter (Java Platform SE 7 )
'e' '\u0065' Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied. The formatting of the magnitude m depends upon its value. If m is NaN or infinite, the literal strings "NaN" or "Infinity", resp
docs.oracle.com
1. String.format 메서드 사용하기
: String.format은 JAVA에서 문자열을 원하는 형식으로 포맷팅하여 반환하는 메서드입니다. 이 메서드는 C 언어의 printf와 유사한 기능을 제공하고 다음과 같은 형태로 사용됩니다.
String formattedString = String.format(format, args);
- format : 출력 형식을 지정하는 문자열입니다. 포맷 지정자를 사용하여 원하는 형태로 데이터를 변환합니다. %d, %f, %s, %c, %b 등이 일반적인 포맷 지정자입니다.
- args : 포맷 문자열에 들어갈 데이터를 나타내는 변수들로, format 문자열 내에서 포맷 지정자와 일치하는 순서대로 대체됩니다. 예를 들어, 다음은 String.format을 사용하여 정수, 실수, 문자열을 원하는 형식으로 포맷팅하는 예제입니다.
public class FormatExample { public static void main(String[] args) { int number = 42; double pi = 3.14159265359; String name = "John Doe"; String formatted1 = String.format("Number: %d", number); System.out.println(formatted1); // Number: 42 String formatted2 = String.format("Pi: %.2f", pi); System.out.println(formatted2); // Pi: 3.14 String formatted3 = String.format("Name: %s", name); System.out.println(formatted3); // Name: John Doe } }
%d (= Integer Formatting, 10진수)
%s (= String Formatting, 문자열)
%f (= Floating point Formatting, 실수형)
%t (= DateTime Formatting)
- y: 연, year
- M: 월, month
- d: 일, day of month
- H: 시, 24-hour
- h: 시, 12-hour
- M: 분, minute
- s: 초, second
잠깐!
Q. 왜 자바에서 'public static void main(String[] args)'를 가장 먼저 쓸까?
- public: main메서드는 다른 클래스에서도 접근할 수 있도록 public 접근 제어자를 사용합니다.
- static: main메서드는 객체의 생성 없이 호출되어야 하므로, static 키워드를 사용하여 클래스 레벨에서 실행 가능한 메서드로 지정합니다.
- void: main 메서드는 반환값이 없기 때문에 void를 반환 타입으로 지정합니다.
- main: 메서드 이름은 main입니다. 이 이름은 관례적으로 사용되며, 자바 가상 머신(JVM)이 프로그램 실행 시 이 메서드를 찾아서 실행합니다.
- String[] args: main 메서드의 매개변수로 문자열 배열 args를 받습니다. 이 배열은 프로그램 실행 시 커맨드 라인에서 인자(argument)를 전달할 때 사용됩니다.
public class MyClass { public void myMethod() { System.out.println("Hello, world!"); } public static void main(String[] args) { MyClass obj = new MyClass(); obj.myMethod(); // 객체를 생성한 뒤에야 메서드를 호출할 수 있음 } }
- 위의 예제에서 myMethod는 일반(non-static) 메서드이기 때문에 해당 클래스의 객체를 생성한 뒤에 메서드를 호출할 수 있습니다.
- 그러나 main 메서드는 프로그램을 시작하는 지점으로서, 프로그램 실행 시에 JVM이 해당 메서드를 호출하게 됩니다. 이때, 프로그램이 시작되는 시점에서 객체를 먼저 생성할 수 없으므로, main 메서드는 static 키워드로 선언하여 클래스 레벨에서 실행 가능한 메서드로 지정됩니다. 따라서 main 메서드가 클래스 레벨에서 실행 가능하게 되면 프로그램 실행 시 객체 생성 없이 직접 호출할 수 있게 됩니다.
- 따라서, public static void main(String[] args) 메서드는 자바 프로그램을 시작하는 진입점(entry point)이며, 프로그램 실행 시에는 자동으로 JVM이 이 메서드를 호출하여 프로그램을 실행합니다. 이러한 이유로 main 메서드를 가장 먼저 작성하는 것이 일반적인 관례이고, 필수적인 구조입니다.
%02d
%: 포맷 지정자를 시작하는 기호
0: 빈 자리를 0으로 채우는 옵션
2: 출력할 숫자의 자리수
d: 10진수 정수를 출력\t
\t는 특수 문자로서, 탭(tab) 문자를 나타냅니다. 탭 문자는 일정한 간격으로 텍스트를 수평으로 정렬할 때 사용되며, 주로 출력에서 각 항목을 구분할 때나 텍스트를 깔끔하게 정렬할 때 유용합니다.
예를 들어, 다음과 같은 코드를 실행하면 탭 문자를 사용하여 간단한 표 형태의 출력을 만들 수 있습니다:public class TabExample { public static void main(String[] args) { System.out.println("Name\tAge\tCity"); System.out.println("John\t25\tNew York"); System.out.println("Alice\t30\tLondon"); System.out.println("Bob\t22\tParis"); } }
Name Age City John 25 New York Alice 30 London Bob 22 Paris
public class Gugudan { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { int result = i * j; String formatted = String.format("%02d x %02d = %02d", i, j, result); System.out.println(formatted+"\t"); } System.out.println(); // 줄바꿈 } } }