![](/img/trans.png)
[英]One variable type two object on different conditions in android studio
[英]Can I search for values in two different type of arrays with just one type of variable?
我對 Java 很陌生,我被要求創建一個程序,用戶可以在其中輸入兩個值並將它們存儲在單獨的 arrays 中。 我要求用戶的兩個值是姓名和手機號碼,然后我必須允許用戶通過輸入姓名或手機號碼進行搜索並返回相應的姓名或手機號碼。 我可以輸入值並按數字在其中搜索,但是當我嘗試按名稱搜索時出現此錯誤:
Exception in thread "main" java.lang.NumberFormatException: For input string: "B"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
這是我的代碼:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int i, x = 2;
static String names[] = new String[x];
static int numbers[] = new int[x];
public static void main(String[] args) {
Input();
Compare();
}
public static void Input() {
System.out.println("Enter a name followed by the persons number");
while (i < x) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.nextInt();
i++;
}
}
public static void Compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
var temp = sc.next();
System.out.println("NAME\tNUMBER");
for (i = 0; i < numbers.length; i++)
if ((names[i].equals(temp)) || (numbers[i] == Integer.parseInt(temp.trim()))) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
}
謝謝: :)
查看您的問題陳述,您似乎不需要對數字進行任何額外的處理。 因此,即使您將數字存儲為字符串,在這種情況下也應該沒問題。 因此,在獲得用戶搜索條件后,您可以在 arrays 中進行簡單的字符串搜索。
希望這可以幫助:)
首先,Java中可以表示為int的最大數是2147483647(214-748-3647)。 這顯然無法容納足夠高的號碼來容納任何電話號碼。 為了解決這個問題並修復您的主要錯誤,我建議將數字存儲為字符串。 這是我的解決方案:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int x = 2;
static String names[] = new String[x];
static String numbers[] = new String[x];
public static void main(String[] args) {
input();
compare();
}
public static void input() {
System.out.println("Enter a name followed by the persons number");
for (int i = 0; i < x; i++) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.next();
i++;
}
}
public static void compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
String temp = sc.next();
System.out.println("NAME\tNUMBER");
for (int i = 0; i < numbers.length; i++) {
if ((names[i].equals(temp)) || numbers[i].equals(temp)) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
System.out.println("===END OF SEARCH====")
}
}
另請注意,我未定義您的變量 i。 據我所知,您沒有理由定義它。 希望這有幫助,祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.