如何从最后扭转以第一一字符阵列的

时间:2019-01-31 19:58:02

标签: java

我想反转用户提供的任何字符串输入,例如,如果输入为“ qwerty”,则输出应为“ ytrewq”。

var lines;                                 // Added compared to basic code.
const readline = require('readline');
const rl = readline.createInterface({
  input:  process.stdin,
  output: process.stdout
});
rl.question("Which dices to keep [1,2,3,4,5] ?: ", (answer) => {
  lines.push(answer);                      // Added compared to basic code.
  console.log("Will keep dices: ", answer);
  rl.close();
});
console.log(lines);                        // Added compared to basic code.

请告诉我这段代码出了什么问题,因为当我在纸上做循环时,它是可行的! 并且请告诉我这是否是最好的方法。

2 个答案:

答案 0 :(得分:1)

下面是扭转用户输入字符串

更短的方式
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter a string: ");
    String input = scanner.nextLine();

    ArrayList<String> list = new ArrayList<>(Arrays.asList(input.split("")));

    Collections.reverse(list);

    for (String str : list) {
        System.out.print(str);
    }
}

答案 1 :(得分:0)

您可以就地进行:

for (i=0; i<test1.length/2; i++){
    char tmp = test1[i];
    test1[i] = test1[test1.length - i - 1];
    test1[test1.length - i - 1] = tmp;
}