我做了一个简单的程序来反转列表。现在我试图反转一个字符串,所以我把它转换成一个字符数组并将其分配给一个变量charz.But我的函数只接受一个字符串列表。
现在在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;
}
}
答案 0 :(得分:1)
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]
答案 1 :(得分:0)
如果您希望列表包含多种不同的数据类型,请将列表声明为对象,例如:
List<Object> sent = new ArrayList<Object>(Arrays.asList("Jake","you","are", 20, "years", "old", "and", 70.3, "inches", "high"));
for (int i = 0; i < sent.size(); i++) {
System.out.println(sent.get(i).toString());
}
但是,如果你想将列表的元素分解为特定的数据类型变量,如String,int,double等,那么你需要转换为它,例如:
String name = (String) sent.get(0); //or use: sent.get(0).toString();
int age = (int) sent.get(3);
double height = (double) sent.get(7);
如果您希望列表中的double或integer类型为String,那么您可以执行以下任一操作:
对于整数,double,float等:
String age = sent.get(3).toString();
OR
String age = String.valueOf(sent.get(3));