我试图从String list(Array)中只取出一个对应用户输入(数字)的值。如果用户输入数字4,结果应该是60.这是我试图完成的代码。错误是不兼容的int和字符串(当然),但除此之外,我确信我在其他地方也犯了错误。我希望数组在没有对象和类的情况下尽可能简单。
RSA_free()
答案 0 :(得分:0)
也许我误解了这个问题,但听起来你想要的只是:
if(inputNumber >= 0 && inputNumber < someArray.length) {
System.out.printf("The Number %d corresponds to String %s\n", inputNumber, someArray[inputNumber]);
} else {
// you don't really show how you want to handle this case...
}
目前还不清楚VALID_NUMBERS的目的是什么。
我的意思是你应该完全替换for循环:
import java.util.Scanner;
public class FindStringValue {
final String[] someArray = {"20", "30", "40", "50", "60", "70", "80", "90"};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number from 0-7 >> ");
int inputNumber = in.nextInt();
if(inputNumber >= 0 && inputNumber < someArray.length) {
System.out.printf("The Number %d corresponds to String %s\n", inputNumber, someArray[inputNumber]);
} else {
// you don't really show how you want to handle this case...
}
}
}
答案 1 :(得分:0)
您不需要检查数组并进行任何比较,因为您要删除元素索引。您可以通过以下代码段实现目标:
public static void main(String[] args) {
String[] someArray = {"20", "30", "40", "50", "60", "70", "80", "90"};
int inputNumber;
boolean foundIt = false;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number from 0-7 >> ");
inputNumber = in.nextInt();
in.close();
LinkedList<String> list = new LinkedList(Arrays.asList(someArray));
list.remove(inputNumber);
String []newArray = list.toArray(new String[list.size()]);
System.out.println("The Number " + inputNumber + " corresponds to String " + someArray[inputNumber]);
}
答案 2 :(得分:0)
我完全取消了数组,只需使用此处所示的List。
public static void main(String[] args){
List<String> numbers = Arrays.asList("20", "30", "40", "50", "60", "70", "80", "90");
int inputNumber;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number from 0-7 >> ");
inputNumber = in.nextInt();
in.close();
if(inputNumber < numbers.size()) //validity check of input value
{
System.out.println("The Number "+ inputNumber + " corresponds to String "+ numbers.get(inputNumber));
}
}