gpt4 book ai didi

Java 扫描器和错误

转载 作者:行者123 更新时间:2023-12-01 10:34:37 25 4
gpt4 key购买 nike

嗨,我正在尝试编写一个程序来声明一组字符串和一组整数。之后,我想根据我写入的数字将两者打印到控制台。

例如,如果我声明了类似的内容,

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();

之后,尝试将输入从字符串解析为整数,这将让您从数组中获取数据。

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);
}

我们捕获异常以防失败。第一种情况是输入不是数字。第二个是数组的长度是否小于请求的索引。

您还必须确保遵循以下标准:数组的第一个索引是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.
}
}
}

关于Java 扫描器和错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34847877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com