现在我有一个字符串 ArrayList。该数组填充了用户在控制台中输入的数据。我试图删除数组的第一个元素,然后使用其余的输入。输入的其余部分是指没有第一个元素的输入。我试图通过使用 nameofarray.remove(0);
来做到这一点但这似乎不起作用。感谢您对删除数组的第一个元素然后获取数组的其余部分的任何帮助,谢谢!
import java.util.ArrayList;
import java.util.Scanner;
class Driver {
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
String userInput;
char msb;
int convertedBinary;
String removedMSB;
ArrayList<String> binaryInput = new ArrayList<String>();
System.out.println("Press 1 to use the Binary Converter: Press 2 to use the Decimal Converter:");
int userChoice = k.nextInt();
if (userChoice == 1) {
System.out.println("Welcome to the Binary Converter!");
System.out.println("Please enter a 10 bit binary number");
// Adding the input to the ArrayList
userInput = k.next();
msb = userInput.charAt(0);
binaryInput.add(userInput);
if (msb == '0') {
convertedBinary = Integer.parseInt(userInput, 2);
System.out.println("Your number in decimal is " + convertedBinary);
} else if (msb == '1') {
// Attempting to remove first element from ArrayList
binaryInput.remove(0);
convertedBinary = Integer.parseInt(userInput, 2);
System.out.println("Your number in decimal is " + convertedBinary);
}
}
}
}
最佳答案
binaryInput.add(userInput);
BinaryInput 是字符串的 ArrayList。您将字符串 userInput 添加到 binaryInput,因此现在 binaryInput[0] 是字符串 userInput。
binaryInput.remove(0);
这一行将删除 binaryInput- 的第一个元素,即 userInput。我假设您只想删除 userInput 的第一个字符,而不是像您现在在代码中所做的那样删除整个字符串。
我建议改为这样做:
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
String userInput;
char msb;
int convertedBinary;
String removedMSB;
ArrayList<String> binaryInput = new ArrayList<String>();
System.out.println("Press 1 to use the Binary Converter: Press 2 to use the Decimal Converter:");
int userChoice = k.nextInt();
if (userChoice == 1) {
System.out.println("Welcome to the Binary Converter!");
System.out.println("Please enter a 10 bit binary number");
// Adding the input to the ArrayList
userInput = k.next();
String withoutFirstChar = userInput .substring(1);
msb = userInput.charAt(0);
if (msb == '0') {
convertedBinary = Integer.parseInt(userInput, 2);
System.out.println("Your number in decimal is " + convertedBinary);
} else if (msb == '1') {
convertedBinary = Integer.parseInt(withoutFirstChar , 2);
System.out.println("Your number in decimal is " + convertedBinary);
}
}
}
}
关于java - 从数组中删除第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40076594/