这是文本文件,我想读取文本文件并将名称年龄和地址存储到对象中。我对该程序有疑问,对不熟悉java
name:name1 年龄:20岁 地址:kokrajhar
我希望结果如下: StudenInfo [name = name1,age = 20,address = kokrajhar]
StudentInfo.java
#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/vm_map.h>
static unsigned long long _previousTotalTicks = 0;
static unsigned long long _previousIdleTicks = 0;
// Returns 1.0f for "CPU fully pinned", 0.0f for "CPU idle", or somewhere in between
// You'll need to call this at regular intervals, since it measures the load between
// the previous call and the current one.
float GetCPULoad()
{
host_cpu_load_info_data_t cpuinfo;
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuinfo, &count) == KERN_SUCCESS)
{
unsigned long long totalTicks = 0;
for(int i=0; i<CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];
return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);
}
else return -1.0f;
}
float CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)
{
unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;
unsigned long long idleTicksSinceLastTime = idleTicks-_previousIdleTicks;
float ret = 1.0f-((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
_previousTotalTicks = totalTicks;
_previousIdleTicks = idleTicks;
return ret;
}
Test.java
public class StudenInfo{
private static String name;
private static Integer age;
private static String address;
public String getName() {
return name;
}
public static void setName(String name) {
StudenInfo.name = name;
}
public static Integer getAge() {
return age;
}
public static void setAge(Integer age) {
StudenInfo.age = age;
}
public static String getAddress() {
return address;
}
public static void setAddress(String address) {
StudenInfo.address = address;
}
@Override
public String toString() {
return "StudenInfo [name=" + name + ", age=" +age +", address=" + address +"]";
}
}
答案 0 :(得分:0)
首先,如前面的答案所说,你不应该使用静态变量,因为它会修改所有对象的值,你最终会得到相同的值。
第二,如果你总是指望你的信息被格式化,那么你应该使用正则表达式,因为你正在进行的分割只会导致更多的错误。
这是一个如何使用它的例子:
Pattern pattern = Pattern.compile("\\w*\\s:\\s\\w*"); // this will split on groups of information, like name : name1
List<String> studentInfo = new ArrayList();
Matcher matcher = pattern.matcher(test);
while (matcher.find()) {
studentInfo.add(matcher.group());
}
studentInfo.get(0).substring(studentInfo.get(0).trim().lastIndexOf(" ")); // this is the name
studentInfo.get(1).substring(studentInfo.get(1).trim().lastIndexOf(" ")); // this is the age
studentInfo.get(2).substring(studentInfo.get(2).trim().lastIndexOf(" ")); // this is the address