- コンソールからの入力
Javaでは、Scannerクラスを使用してコンソールからの入力を処理することができます。Scannerクラスはjava.utilパッケージに含まれているため、使用する前にインポートする必要があります。
import java.util.Scanner;
Scannerクラスを使用してコンソールからの入力を処理する手順は以下の通りです:
Scannerオブジェクトを作成し、コンソールの入力ストリームを引数として渡します。
Scanner scanner = new Scanner(System.in);
Scannerオブジェクトのメソッドを使用してコンソールからの入力を読み取ります。
int num = scanner.nextInt();
Scannerオブジェクトを閉じます。
scanner.close();
1. 整数の入力と平均値の計算
以下は、ユーザーが入力した整数の平均値を計算して表示する例です。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("最初の整数を入力してください:");
int a = scanner.nextInt();
System.out.print("次の整数を入力してください:");
int b = scanner.nextInt();
System.out.print("最後の整数を入力してください:");
int c = scanner.nextInt();
int sum = a + b + c;
double average = (double) sum / 3;
System.out.println("3つの整数の平均値は:" + average);
scanner.close();
}
}
2. 浮動小数点数の入力と平均値の計算
以下は、ユーザーが入力した浮動小数点数の平均値を計算して表示する例です。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("最初の浮動小数点数を入力してください:");
double a = scanner.nextDouble();
System.out.print("次の浮動小数点数を入力してください:");
double b = scanner.nextDouble();
System.out.print("最後の浮動小数点数を入力してください:");
double c = scanner.nextDouble();
double sum = a + b + c;
double average = sum / 3;
System.out.println("3つの浮動小数点数の平均値は:" + average);
scanner.close();
}
}
3. 文字列の入力と表示
以下は、ユーザーが入力した文字列を表示する例です。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("文字列を入力してください:");
String str = scanner.nextLine();
System.out.println("入力された文字列は:" + str);
scanner.close();
}
}
4. その他のデータ型の入力
Scannerクラスには、nextByte(), nextShort(), nextLong(), nextFloat(), nextDouble()などのメソッドがあります。これらのメソッドも同様の方法で使用できます。
ファイルやネットワークからの入力
5. ファイルからの入力
以下は、ファイルからデータを読み込んで表示する例です。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
6. ネットワークからの入力
以下は、ネットワークからデータを読み込んで表示する例です。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://www.example.com");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
7. キーボードからの入力
以下は、キーボードからの入力を読み込んで表示する例です。
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("内容を入力してください:");
String line = reader.readLine();
System.out.println("入力された内容は:" + line);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 出力のフォーマット
System.out.println()やSystem.out.print()は出力のフォーマットを制御できませんが、System.out.printf()を使用することでフォーマット付きの出力を実現できます。
1. printf()メソッドの使用
public class Main {
public static void main(String[] args) {
int num = 10;
double pi = 3.14159;
String name = "山田";
System.out.printf("整数:%d,浮動小数点数:%f,文字列:%s\n", num, pi, name);
}
}
2. String.format()メソッドの使用
public class Main {
public static void main(String[] args) {
int num = 10;
double pi = 3.14159;
String name = "山田";
String result = String.format("整数:%d,浮動小数点数:%f,文字列:%s", num, pi, name);
System.out.println(result);
}
}
その他の出力形式:
int num = 10;
final double pi = 3.14159;
String name = "山田";
System.out.printf("%9.2f\n", pi); // 9.2 で9は長さ、2は小数点以下の桁数
System.out.printf("%+9.2f\n", pi); // + で正負符号を表示
System.out.printf("%-9.2f\n", pi); // - で左寄せ
System.out.printf("%+-9.2f\n", pi); // 正負符号を表示し左寄せ
出力のリダイレクト
2.5.3 出力のリダイレクト
Javaでは、System.setOut()メソッドを使用して出力を指定の出力ストリームにリダイレクトできます。
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("output.txt");
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("Hello, World!");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.5.4 入力のリダイレクト
Javaでは、System.setIn()メソッドを使用して入力を指定の入力ストリームにリダイレクトできます。
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("input.txt");
System.setIn(fis);
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println("入力された内容は:" + input);
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.5.5 パイプストリーム
Javaでは、PipedInputStreamとPipedOutputStreamクラスを使用してパイプストリームを実装できます。
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
Thread writerThread = new Thread(() -> {
try {
pos.write("Hello, World!".getBytes());
pos.close();
} catch (IOException e) {
e.printStackTrace();
}
});
Thread readerThread = new Thread(() -> {
try {
byte[] buffer = new byte[1024];
int length = pis.read(buffer);
String message = new String(buffer, 0, length);
System.out.println("読み取ったデータは:" + message);
pis.close();
} catch (IOException e) {
e.printStackTrace();
}
});
writerThread.start();
readerThread.start();
}
}
- 銀行口座残高の照会
3.1 要求分析
顧客の名前を入力して、その顧客の口座残高を出力します。
3.2 デザイン思路
BankQueryクラスを定義し、mainメソッドを含めます。mainメソッドでScannerクラスを使用してユーザーが入力した顧客名を取得します。- 顧客名に基づいて口座残高を照会し、結果を出力します。
3.3 コード実装
package cn.campsg.java.experiment;
import java.util.Scanner;
public class BankQuery {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("照会したい顧客の名前を入力してください:");
String name = scanner.nextLine();
float money = 8888f;
System.out.printf("尊敬的客户:%s\n您的余额为:%.1f\n", name, money);
}
}
この例では、Scannerクラスを使用してユーザーが入力した顧客名を取得し、System.out.printf()を使用してフォーマット付きで出力しています。
拡張ケース
import java.util.Scanner;
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public synchronized void deposit(double amount) {
balance += amount;
System.out.println("預金:" + amount);
System.out.println("現在の残高:" + balance);
}
public synchronized void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("引き出し:" + amount);
System.out.println("現在の残高:" + balance);
} else {
System.out.println("残高不足、引き出し不可:" + amount);
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("操作を選択してください:1.預金 2.引き出し 3.終了");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("預金額を入力してください:");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.println("引き出し額を入力してください:");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
System.exit(0);
break;
default:
}
}
}
}