我想制作一个Java程序来接受用户输入的一部分并将其存储起来,以便以后使用。我的输入看起来像这样:
Mary market 8 theatre 80 end
John books 45 end
第一个字段表示该人的姓名,然后按照他们给钱的原因名称跟随一系列费用。单词end表示每个人输入的结尾。
我的问题是如何区分人民的名字和他们的支出,以便可以输出每个人的支出平均数?
这确实取决于您是否严格同意输入数据将始终与示例中的格式相同,然后您可以简单地使用字符串.split(" ")
并读取每一行的所有数字。
示例:
// or any other input, eg: List, BufferedReader, etc
String[] lines = new String[] {
"Mary market 8 theatre 80 end",
"John books 45 end"
};
for (String line : lines) {
String[] raw = line.split(" ");
String name = raw[0];
for (int i = 1; i < raw.length; i += 2) {
if (raw[i].equals("end")) break;
String expenseName = raw[i];
int cost = Integer.parseInt(raw[i+1]);
...
}
}
但是如果没有,那么使用RegExp
并找到每一行中的所有数字可能更好。
示例:
// or any other input, eg: List, BufferedReader, etc
String[] lines = new String[] {
"Mary market 8 theatre 80 end",
"John books 45 end"
};
Pattern p = Pattern.compile("\\d+");
for (String line : lines) {
Matcher m = p.matcher(line);
while(m.find()) {
int cost = Integer.parseInt(m.group());
...
}
}
万一用户按照您的指示输入输入:使用split()
字符串方法主班
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//Get Input
String input = s.nextLine();
//Split using Whitespace Regex (Or any regex if you want)
String[] InputArray = input.split(" ");
//Object to get person info later
PersonExpense person = new PersonExpense(InputArray[0]);
//Loop throw the array to get data
for (int i = 1; i < InputArray.length ; i = i+2) {
if (InputArray[i].toLowerCase().equals("end"))
break;
else{
person.addExpenses(new Pair<>(InputArray[i],Integer.valueOf(InputArray[i+1])));
}
}
}
}
PersonExpense类别
public class PersonExpense {
private String PersonName;
//ArrayList of pairs to save the name and cost of the expense
private ArrayList<Pair <String,Integer> > expenses = new ArrayList <Pair <String,Integer> > ();
public PersonExpense(String personName) {
PersonName = personName;
}
public void addExpenses(Pair<String, Integer> expense) {
this.expenses.add(expense);
}
public ArrayList<Pair<String, Integer>> getExpenses() {
return expenses;
}
public void setExpenses(ArrayList<Pair<String, Integer>> expenses) {
this.expenses = expenses;
}
public String getPersonName() {
return PersonName;
}
public void setPersonName(String personName) {
PersonName = personName;
}
}