我如何在扫描仪中输入一个字符串并将其转换为字符,然后该字符成为我的堆栈?
How can I input a string in a scanner and convert it into character and that character becomes my stack?
我是 java 的新手,我被代码困住了,因为我不知道我的角色如何变成我的堆栈
Stack<Character> charStack = new Stack<Character>();
Scanner scan = new Scanner(System.in);
System.out.print("Input a word: ");
String str = scan.nextLine();
char[] char1 = new char [str.length()];
for (int b = 0; b<char1.length; b++){
charStack.push(b);
System.out.println(charStack);
charStack.pop();
}
error: incompatible types: int cannot be converted to Character
charStack.push(b);
and the output should be:
['W','O','R','D']
['W','O','R']
['W','O']
['W']
您的代码有两个问题
而不是 char[] char1 = new char [str.length()];
将您的输入字符串转换为这样的字符数组 str.toCharArray()
然后不是将 index
整数压入字符栈,而是压入字符 charStack.push(charArray[i]);
public static void main(String[] args) {
Stack<Character> charStack = new Stack<Character>();
Scanner scan = new Scanner(System.in);
System.out.print("Input a word: ");
String str = scan.nextLine();
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
charStack.push(charArray[i]);
}
while (!charStack.empty()) {
System.out.println(charStack);
charStack.pop();
}
}
我是 java 的新手,我被代码困住了,因为我不知道我的角色如何变成我的堆栈
Stack<Character> charStack = new Stack<Character>();
Scanner scan = new Scanner(System.in);
System.out.print("Input a word: ");
String str = scan.nextLine();
char[] char1 = new char [str.length()];
for (int b = 0; b<char1.length; b++){
charStack.push(b);
System.out.println(charStack);
charStack.pop();
}
error: incompatible types: int cannot be converted to Character charStack.push(b);
and the output should be:
['W','O','R','D']
['W','O','R']
['W','O']
['W']
您的代码有两个问题
而不是 char[] char1 = new char [str.length()];
将您的输入字符串转换为这样的字符数组 str.toCharArray()
然后不是将 index
整数压入字符栈,而是压入字符 charStack.push(charArray[i]);
public static void main(String[] args) {
Stack<Character> charStack = new Stack<Character>();
Scanner scan = new Scanner(System.in);
System.out.print("Input a word: ");
String str = scan.nextLine();
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
charStack.push(charArray[i]);
}
while (!charStack.empty()) {
System.out.println(charStack);
charStack.pop();
}
}