4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java入門】コンソール上、文字を出力方法。

Last updated at Posted at 2020-04-05

コンソール上、文字を出力方法とは?

System.out.print()
System.out.printf()
System.out.println()

print()?printf()?println()?何が違う?

  • print()
  • そのまま、文字を出力する。
例)
print("abc")
// 表示結果:abc

print("abc")
print("123")
// 表示結果:abc123
  • println()
  • 行の区切り文字列を書き込むことで、現在の行を終了させます。(改行を入れて出力する。)
例)
println("abc")
// 表示結果:abc

println("abc")
println("123")
// 表示結果:abc
           123
  • printf()
  • 書式付き文字列を、指定された書式文字列と引数を使用し、この出力ストリームに書き込む便利な方法です。
例)
---
System.out.printf(書式, 引数1, 引数2, 引数3…)
---
int a = 1;
int b = 1;
System.out.printf("%d + %d = %d", a, b, a+b)
// 表示結果:1 + 1 = 2

※ Format一覧表。

指定子 主な型 簡単な説明 記述例 出力例
% なし 書式指定子の開始 なし なし
d 整数 10進数で出力 printf("%d", 123) 123
o 整数 8進数で出力 printf("%o", 123) 173
x 整数 16進数で出力 printf("%x", 123) 7b
e 小数 指数で出力 printf("%e", 123.4f) 1.23E+02
f 小数 小数点数出力 printf("%f", 123.4f) 123.4
s 文字列 文字列を出力 printf("%s", “abc”) abc
c 文字 文字を出力 printf("%c", ‘a’) a
b 真偽値 真偽値を出力 printf("%b", true) true
  • 桁数・左詰・0埋め・改行 ・引数番号(※△=スペースの意味)
指定子 簡単な説明 記述例 出力例
最小桁数を指定 printf("[%5d]", 123) [△△123]
.数 文字列の最大幅を指定 printf([%.3s]", "abcde") [abc]
- 左詰 printf([%-5s]", "abc") [abc△△]
0 0埋め printf("[%05d]",123); [00123]
n 改行 printf("abc%ndef"); abc
def
  • 日付
指定子 簡単な説明 記述例 出力例
tY 年(4桁) printf("%tY", new Date()); 2018
ty 年(2桁) printf("%ty", new Date()); 18
tm 月(2桁) printf("%tm", new Date()); 01
td 日(2桁) printf("%td", new Date()); 05
te 日(1~2桁) printf("%te", new Date()); 5
tH 時(2桁)24時間制 printf("%tH", new Date()); 17
tl 時(1~2桁)12時間制 printf("%tl", new Date()); 5
tM 分(2桁) printf("%tM", new Date()); 04
tS 秒(2桁) printf("%tS", new Date()); 05
tF 日付 printf("%tF", new Date()); 2018-01-05
tT 時刻 printf("%tT", new Date()); 17:04:05

参考

printf

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?