gpt4 book ai didi

java - 函数建议的变量列表

转载 作者:行者123 更新时间:2023-12-02 13:20:55 25 4
gpt4 key购买 nike

我编写了一个简单的程序来反转列表。现在我试图反转一个字符串,因此我将其转换为字符数组并将其分配给变量 charz。但我的函数只接受字符串列表。

现在在 python 中,我可以有一个多个变量类型的列表,例如 a = [1,"hello",1.3] ,这不会成为问题,是否有相同的方法来制作这样的列表,以便我可以使用它在我的函数中吗?如何让它接受这个变量 charz 而不为这个特定的数据类型创建一个新函数。

package test_proj1;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class TestClass1
{
static Scanner reader = new Scanner(System.in);

public static void main (String[] args)
{
List<String> sent = new ArrayList<String>(Arrays.asList("Jake","you","are"));
System.out.println("Without reversal the inuilt list is "+sent);
sent = lisrev(sent);
System.out.println("After reversal the list is "+ sent);
System.out.println("\nNow then enter a word for me: ");
String word = reader.nextLine();
char[] charz = word.toCharArray();
// List<String> revword = lisrev(charz);
// I want the above line to work but it won't because my function
// lisrev will only accept a list of type String




}
public static List<String> lisrev (List<String> lis)
{
int lastindex = lis.size() - 1;
List<String> newlis = new ArrayList<String>();


while (lastindex != -1)
{
String elem = lis.get(lastindex);
newlis.add(elem);
lastindex -= 1;
}


return newlis;
}

}

最佳答案

char[] charz = word.toCharArray();
String wordReversed = "";
for (int i=charz.length-1; i>=0; i--){
wordReversed+= charz[i];
}
System.out.println(wordReversed);

结果将是例如:

Without reversal the inuilt list is [Jake, you, are]
After reversal the list is [are, you, Jake]

Now then enter a word for me:
Hello My name is Sam, How are you today?
?yadot uoy era woH ,maS si eman yM olleH

此外,如果您想反转用户的句子,您可以执行以下操作:

List<String> theWord = new ArrayList<String>();
String eachWord="";
for(int i=0; i<charz.length; i++){
eachWord+=charz[i]; // append the char to the String
if(charz[i]==' ' || i==charz.length-1){
if(!eachWord.replace(" ", "").equals("")){ // for the followed spaces
theWord.add(eachWord.replace(" ", "")); // add the word
}
eachWord = ""; // start new string
}
}
System.out.println(lisrev(theWord));

结果将是例如(注意空格)

Without reversal the inuilt list is [Jake, you, are]
After reversal the list is [are, you, Jake]
Now then enter a word for me:
Hello My name is Sam, How are you today
[?, today, you, are, How, Sam,, is, name, My, Hello]

关于java - 函数建议的变量列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43565238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com