[英]Java Scanner and errors
嗨,我正在嘗試制作一個聲明一組字符串和一組整數的程序。 之后,我想根據我寫的號碼將它們都打印到控制台。
例如,如果我聲明了這樣的內容,
String a[] = a1 a2 a3 a4 a5
int b[] = 10 20 30 40 50
如果我在掃描儀中輸入1,我想打印出a1和10。
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class value {
private static Scanner sc;
public static void main(String args[]){
String a[] = {"a1","a2","a3","a4","a5"};
int b[] = {100, 220, 200, 230, 500};
sc = new Scanner(System.in);
System.out.println("type in a number");
String input = sc.nextLine();
int i = Integer.parseInt(input);
int j = i - 1;
System.out.println(a[j] + b[j]);
}
}
你能告訴我這是怎么回事嗎? 我真的是編程新手
該答案假設您的int[]
和String[]
數組已經被聲明。
首先,設置掃描儀並讀取輸入。
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
之后,嘗試將輸入從String解析為Integer,這將使您可以從數組中獲取數據。
int j = 0;
try {
j = Integer.parseInt(input);
catch (NumberFormatException e) {
System.out.println("NaN");
System.exit(-1);
}
現在您有一個電話號碼。 您現在要做的就是嘗試從陣列中獲取數據。
try {
System.out.println(a[j] + " " + b[j]);
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of range!");
System.exit(-1);
}
如果失敗,我們將捕獲Exception
的情況。 第一種情況是輸入不是數字。 第二個是數組的length
是否小於請求的索引。
您還必須確保遵循一個數組的第一個索引為0而不是1的標准 。
您的代碼示例:
import java.util.Scanner;
public class Value {
public static void main(String args[]){
String a[] = {"a1", "a2", "a3", "a4", "a5"};
int b[] = {100, 220, 200, 230, 500};
Scanner sc = new Scanner(System.in);
System.out.println("Type in a number.");
String input = sc.nextLine();
int i;
try {
i = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("NaN");
System.exit(-1); // Replace with whatever you want if it fails.
}
try {
System.out.println(a[i] + " " + b[i]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of range: " + i);
System.exit(-1); // Again, change to whatever you want.
}
}
}
你可以這樣嘗試
import java.util.Scanner;
public class Value {
public static void main(String args[]) {
String[] a = {"a1", "a2", "a3", "a4", "a5"};
int[] b = {100, 220, 200, 230, 500};
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
if (choice < 0 || choice > Math.min(a.length, b.length)) {
System.out.println("out of range...");
} else {
System.out.println(a[choice] + "\t" + b[choice]);
}
}
}
}
鍵入0時,它將打印出a1 100
,鍵入1,打印出a2 220
。
您的代碼中的問題是System.out.println(a[j] + b[j]);
在main()方法之外。 它應該在main()中,並在int j = i - 1;
之后刪除}
int j = i - 1;
(這是一個額外的括號)
在您的代碼中:
。 。 。
int i = Integer.parseInt(input);
int j = i - 1;
}
System.out.println(a[j] + b[j]);
}}
正確的代碼:
....
int i = Integer.parseInt(input);
int j = i - 1;
System.out.println(a[j] + b[j]);
}}
您也可以添加異常處理程序來處理類似“ ArrayIndexOutOfBoundException”的事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.