第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從java中的字符串指定類屬性

如何從java中的字符串指定類屬性

尚方寶劍之說 2021-10-27 10:57:00
所以我正在使用掃描儀讀取文件,它具有類似的格式:title, name, ageMr, Matthew, 20mr,  Paul, 30miss, Anne, 24 CSV^class person{String name, title;int age; public  crimeData(String csv){    String[]list = csv.split(",", -1);    name = list[0];    title = list[1];    age = list[2];}}控制臺程序    Scanner input = new Scanner(System.in);    System.out.println("Please select what data you want to load:");    String selection = input.next();    int temp = 0;    for(int i=0; i< header.length; i++){        if(header[i].equals(selection)){            temp = i;        break;      }    }temp 會給我們指定選項的索引,所以如果它是 2 我們將要訪問 age 屬性當(dāng)我的控制臺應(yīng)用程序運行時,我會提示他們(用戶)輸入他們想要的數(shù)據(jù)。所以他們可能會輸入“年齡”所以我不知道如何使用這個“年齡”字符串并用它訪問 person 對象。程序輸出的理想情況應(yīng)該是:20,30,24遍歷每個時代并打印我接受他們的輸入,String input = scanner.nextLine(); 然后我循環(huán)遍歷我的 person 對象數(shù)組以獲取輸入的索引。一旦我有了這個索引,我就想在索引處訪問 person 的屬性。因此,如果我的索引為 1,我想訪問屬性“名稱”。在 javascript 中,我可以用字符串說person['age']雖然 java 是一個完全不同的故事。我已經(jīng)研究了 java 的“反射 API”,盡管它是一個沉重的學(xué)習(xí)曲線。
查看完整描述

3 回答

?
絕地?zé)o雙

TA貢獻1946條經(jīng)驗 獲得超4個贊

雖然一般來說我不贊成使用Map用于保存對象的字段,但如果屬性的數(shù)量很大,甚至可能因 CSV 文件而異(例如,某些文件有一個人就讀的大學(xué),另一個沒有),那么使用 aMap來保存屬性可能是合適的。


在這種情況下,可以定義一個簡單的Person類:


public class Person {

  Map<String, String> props = new HashMap<>();


  public void addProperty(String propertyName, String value) {

    // could add error checking to ensure propertyName not null/emtpy

    props.put(propertyName, value);

  }


  /**

   * returns the value of the property; may return null

  */

  public String getProperty(String propertyName) {

    return props.get(propertyName);

  }

}

如果知道將始終加載某些屬性/屬性,則getName()可以添加諸如此類的訪問器:


public String getName() {

  return props.get("name");

}


public int getAge() {

  String age = props.get("age");

  // or throw exception if missing

  return (age != null ? Integer.parseInt(age) : -1);

}

盡管請注意,對于大多數(shù)數(shù)據(jù)集,我希望 name 不是單個條目,因為通常會有姓氏、名字等。 盡管如此,有限數(shù)量的常見預(yù)期值的模式是相同的。此外,您可以進行調(diào)整,以便您可以直接獲取某些知名字段的整數(shù)值。


然后,在解析文件時,保留具有屬性定義的標(biāo)題行。然后,對于隨后讀取的每一行,創(chuàng)建一個新Person對象,然后按順序添加屬性。


List<Person> allPersons = new ArrayList<>();


while ( (line = READ_NEXT_LINE) ) {

  // NOTE: this is not a safe way to handle CSV files; should really

  //   use a CSV reader as fields could have embedded commas

  attrs[] = line.split(",");

  Person p = new Person();

  for (int i = 0; i < titleRow.length; ++i) {

    p.addProperty(titleRow[i], attrs[i]);

  }


  allPersons.add(p);

}

然后你可以得到一個特定Person的Person myPerson = allPersons.get(index_of_person),和你使用的方式非常相似Javascript,你可以做String val = myPerson.getProperty("age")。


如果您需要按給定的屬性進行搜索,則可以allPersons根據(jù)給定的屬性對等價性進行流/循環(huán)和檢查。


// find all people of a given age

List<Person> peopleAge20 = allPersons.stream()

            .filter(p -> p.getAge() == 20)

            .collect(Collectors.toList());

    System.out.println(peopleAge20);        


    // summary statics (average age) for all people

    IntSummaryStatistics stats = 

            allPersons.stream().mapToInt(p -> p.getAge()).summaryStatistics();

    System.out.printf("Average age: %f\n", stats.getAverage());

請注意,這種方法確實打破了 a 的想法Javabean,但這可能是也可能不是問題,具體取決于您的要求。


查看完整回答
反對 回復(fù) 2021-10-27
  • 3 回答
  • 0 關(guān)注
  • 287 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號