通过字符串参数的Java构造函数
你好,我的问题是通过字符串参数的Java构造函数,java,string,list,constructor,Java,String,List,Constructor,你好,我的问题是 DepositoBancario(String s){ String[]v = s.split("[ :]"); Integer n= v.length; if(n!=2) throw new IllegalArgumentException("Error"+s); banco= new String(v[0]); interes= new List(v[1]); } 这个构造函数是为了
DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= new String(v[0]);
interes= new List(v[1]);
}
这个构造函数是为了能够通过一个文件构建和对象,我想转换列表中的元素v[1](interest)
谢谢你们的帮助
新字符串(“”)的字符串,只需设置banco=v[0]
v[1]
中是什么我相信您有一个或多个元素
(interest)
,您希望将它们转换为元素列表。你可以用这样的东西
import java.util.ArrayList;
import java.util.List;
public class DepositoBancario {
String banco;
List<String> interes;
public DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= v[0];
if(v[1] != null){
interes = new ArrayList<String>();
}
for(int i=1;i<n;i++)
interes.add(v[i]);
}
}
import java.util.ArrayList;
导入java.util.List;
公共类存款银行{
字符串银行;
列出利息;
公共存款银行(字符串s){
字符串[]v=s.split(“[:]”);
整数n=v.长度;
如果(n!=2)抛出新的IllegalArgumentException(“错误”+s);
banco=v[0];
如果(v[1]!=null){
利息=新的ArrayList();
}
对于(inti=1;i首先,除非您使用列表的一些自定义实现,否则代码不会编译。
从你的问题中我能理解的应该是
import java.util.List;
import java.util.ArrayList;
public class DepositoBancario {
private String banco;
private List<String> interes;
DepositoBancario(String s) {
String[]v = s.split("[ :]"); // split input string by colon or space
if(v.length != 2) { // check if there are just two fields
throw new IllegalArgumentException("Invalid syntax, two fields expected: " + s);
}
banco = v[0];
interes = new ArrayList<String>();
interes.add(v[1]);
}
}
import java.util.List;
导入java.util.ArrayList;
公共类存款银行{
私人字符串银行;
私人名单权益;
存托银行(字符串s){
字符串[]v=s.split(“[:]”;//按冒号或空格拆分输入字符串
如果(v.length!=2){//检查是否只有两个字段
抛出新的IllegalArgumentException(“无效语法,需要两个字段:”+s);
}
banco=v[0];
利息=新的ArrayList();
利息增加(v[1]);
}
}
能否显示banco和Interest中包含的内容。请提供更多信息,我们将尝试帮助private String banco;private List Interest;