我几乎得到了它,除非我运行程序时它解析除了字符串Hello World的第一个字母以外的所有字符:" e l l o w o r d d。"继承我的代码;我错过了什么?
import java.util.Scanner;
public class encodeTesting {
public static void main(String []Args){
//Scanner scan = new Scanner (System.in);
String x = "Hello World "; //TEST STRING
//System.out.println(x.length()); //Console log test
char[] y = new char[x.length()]; // Array Y
//Defining Variables:
int i;
int z = 0;
int a = 1;
while(a<x.length()){ //should repeat as many times as needed to parse String X
//Parse Algorithm follows:
y[z] = x.charAt(x.length() - a);
System.out.println(y[z]);
z = z + 1;
a = a + 1;
}
}
答案 0 :(得分:2)
public static void main(String[] Args) {
String x = "Hello World ";
char[] y = new char[x.length()];
int i;
int z = 0;
int a = 1;
while (a <= x.length()) {
y[z] = x.charAt(x.length() - a);
System.out.println(y[z]);
z = z + 1;
a = a + 1;
}
}
您需要使用:
while (a <=x.length())
这样当x.charAt(x.length() - a);
评估x.charAt(0);
时获取字符串的第一个字符。
答案 1 :(得分:0)
你可以简单地做一个基本的for
循环。
public static void main(String[] Args){
String x = "Hello World ";
int length = x.length();
char[] y = new char[length];
for(int i = 0; i < length; i++){
y[i] = x.charAt(length - i - 1);
System.out.println(y[i]);
}
}
答案 2 :(得分:0)
如果你想为字符串中的每个字符做一些事情,可以这样做:
public static void main (String[] args){
String test = "Hello world";
for(char c: test.toCharArray()) {
//do your operations here
System.out.print(c);
}
}
//Output: Hello World
将for循环读为“对于测试中的每个字符”
通过它的外观你只想将你的字符串转换为字符数组,在这种情况下只需使用它:
String myStringVariable = "abc";
char[] stringAsArray = myStringVariable.toCharArray();
或者你甚至可以这样做:
char[] stringAsArray = "Hello world".toCharArray();