Parsing a String into a Map in Java - java

have a string like;
{uniqueKey=test20745,content={acostumbrado={tf=1,df=1},al={tf=1,df=6945},ante={tf=1,df=42},co={tf=1,df=9187},ello={tf=1,df=2},está={tf=2,df=21},falcao={tf=1,df=105},guardia={tf=1,df=2},http={tf=1,df=9893},nada={tf=1,df=24},no={tf=1,df=2493},osa={tf=1,df=429},para={tf=1,df=6382},partido={tf=1,df=50},pretorian={tf=1,df=1},que={tf=1,df=358},sebcfkeı={tf=1,df=1},su={tf=1,df=7368},t={tf=1,df=14423},tuvo={tf=1,df=3},un={tf=1,df=8511}}}
how to parse this string to a map(key, list) like below;
acostumbrado->tf=1,df=1
al ->tf=1,df=6945
ante ->tf=1,df=42
...
edit:
so what I have done up to now;
String delims = "[{},]";
HashMap<String, List<String>> valueMap = new HashMap<String, List<String>>();
for (int i = 0; i < text.size(); i++) {
String[] tokens = val.toString().split(delims);
ArrayList<String> tfAndDfValues = new ArrayList<String>();
tfAndDfValues.add(tokens[4].substring(3));
tfAndDfValues.add(tokens[5].substring(3));
if (valueMap.containsKey(removeLastChar(tokens[3]))) {
valueMap.get(removeLastChar(tokens[3])).addAll(tfAndDfValues);
} else {
valueMap.put(removeLastChar(tokens[3]), tfAndDfValues);
}
}

Have you thought about State pattern? See usage example:
public class StatePatternProgram {
public static void main(String[] args) {
String example = "{uniqueKey=test20745,content={acostumbrado={tf=1,df=1},al={tf=1,df=6945},ante={tf=1,df=42},co={tf=1,df=9187},ello={tf=1,df=2},está={tf=2,df=21},falcao={tf=1,df=105},guardia={tf=1,df=2},http={tf=1,df=9893},nada={tf=1,df=24},no={tf=1,df=2493},osa={tf=1,df=429},para={tf=1,df=6382},partido={tf=1,df=50},pretorian={tf=1,df=1},que={tf=1,df=358},sebcfkeı={tf=1,df=1},su={tf=1,df=7368},t={tf=1,df=14423},tuvo={tf=1,df=3},un={tf=1,df=8511}}}";
ParseContext context = new ParseContext();
Map<String, List<Integer>> map = context.parseContent(example);
System.out.println(map);
}
}
class ParseContext {
private Map<String, List<Integer>> contentMap;
private String currentKey;
private List<Integer> currentList;
private boolean continueParsing = true;
private ParseState state = new StartParseState();
public Map<String, List<Integer>> parseContent(String content) {
StringTokenizer tokenizer = new StringTokenizer(content, "{}=,", true);
while (continueParsing) {
state.parse(tokenizer);
}
return contentMap;
}
interface ParseState {
void parse(StringTokenizer tokenizer);
}
class StartParseState implements ParseState {
#Override
public void parse(StringTokenizer tokenizer) {
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (!"content".equals(token)) {
continue;
}
contentMap = new LinkedHashMap<String, List<Integer>>();
tokenizer.nextToken();
tokenizer.nextToken();
state = new KeyParseState();
break;
}
}
}
class KeyParseState implements ParseState {
#Override
public void parse(StringTokenizer tokenizer) {
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (",".equals(token)) {
token = tokenizer.nextToken();
}
if ("}".equals(token)) {
state = new EndParseState();
return;
}
currentKey = token;
tokenizer.nextToken();
state = new ListParseState();
}
}
}
class ListParseState implements ParseState {
#Override
public void parse(StringTokenizer tokenizer) {
currentList = new ArrayList<Integer>();
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if ("}".equals(token)) {
break;
}
if ("=".equals(token)) {
currentList.add(Integer.valueOf(tokenizer.nextToken()));
}
}
contentMap.put(currentKey, currentList);
state = new KeyParseState();
}
}
class EndParseState implements ParseState {
#Override
public void parse(StringTokenizer tokenizer) {
continueParsing = false;
}
}
}
This program prints:
{acostumbrado=[1, 1], al=[1, 6945], ante=[1, 42], co=[1, 9187], ello=[1, 2], está=[2, 21], falcao=[1, 105], guardia=[1, 2], http=[1, 9893], nada=[1, 24], no=[1, 2493], osa=[1, 429], para=[1, 6382], partido=[1, 50], pretorian=[1, 1], que=[1, 358], sebcfkeı=[1, 1], su=[1, 7368], t=[1, 14423], tuvo=[1, 3], un=[1, 8511]}

This solution is using regex group capturing:
private static final String SAMPLE = "{uniqueKey=test20745,content={acostumbrado={tf=1,df=1},al={tf=1,df=6945},ante={tf=1,df=42},co={tf=1,df=9187},ello={tf=1,df=2},está={tf=2,df=21},falcao={tf=1,df=105},guardia={tf=1,df=2},http={tf=1,df=9893},nada={tf=1,df=24},no={tf=1,df=2493},osa={tf=1,df=429},para={tf=1,df=6382},partido={tf=1,df=50},pretorian={tf=1,df=1},que={tf=1,df=358},sebcfkeı={tf=1,df=1},su={tf=1,df=7368},t={tf=1,df=14423},tuvo={tf=1,df=3},un={tf=1,df=8511}}}";
private static final String CONTENT = "(\\p{L}*)=\\{((tf=\\d*),(df=\\d*))\\}";
public static void main(String[] args) {
Pattern p = Pattern.compile(CONTENT);
Matcher m = p.matcher(SAMPLE);
Map<String, List<String>> result = new HashMap<String, List<String>>();
while (m.find()) {
String key = m.group(1);
List<String> values = new ArrayList<String>();
values.add(m.group(3));
values.add(m.group(4));
result.put(key, values);
}
System.out.println(result);
}

If your input pattern is unique all the time, try this
String delims = "[{},=]";
Map map = new HashMap() ;
String[] tokens = text.toString().split(delims);
for( int i=5;i<tokens.length - 7;i = i+ 7) {
map.put(tokens[i], tokens[i+2]+"->"+tokens[i+3]+","+tokens[i+4]+"->"+tokens[i+5]);
}
System.out.println(map);

Related

How push to store data in Redis for Custom Map?

I'm storing Data in Map and Fetching the Field values now instead of Map I want to store data in Redis. I'm new to Redis and using below code to store in Redis :
public class CachingRedis {
private static HashMap<String, UserFields> Cache;
private static JedisPool pool = null;
private static final String redisHost = "localhost";
private static final Integer redisPort = 6379;
static Jedis jedis = null;
static User u;
public CachingRedis() {
pool = new JedisPool(redisHost, redisPort);
this.Cache = new HashMap<String, UserFields>();
}
public static void main(String[] args) throws ExecutionException {
CachingRedis gt = new CachingRedis();
gt.addSets();
}
private void addSets() {
InputStream in = ClassLoader.class.getResourceAsStream("/users.csv");
u = new User(in);
String[] consideredUserFields = { "Area","FirstName","LastName","Contact","Level"};
List<String[]> users = p.getUsers();
jedis = pool.getResource();
int count1 = 0;
String token = null;
String fieldName = null;
String fieldVal = null;
for (int i = 0; i < users.size(); i++) {
UserFields uFields = new UserFields();
String tmpId = Integer.toString(p.getUserId(i));
String[] tmpFields = Users.get(i);
for (int j = 0; j < tmpFields.length; j++) {
fieldName = consideredUsersFields[j];
fieldVal = tmpFields[j];
if (Cache != null && Cache.containsKey(tmpId)) {
uFields = Cache.get(tmpId);
uFields.setFieldKeyValues(fieldName, fieldVal);
Cache.put(tmpId, uFields);
**jedis.hsetnx( tmpId,fieldName,fieldVal );**
} else {
uFields.setFieldKeyValues(fieldName, fieldVal);
Cache.put(tmpId, pFields);
**jedis.hsetnx( tmpId,fieldName,fieldVal );**
}
}
}
} }
I'm getting the following error
Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: WRONGTYPE Operation against a key holding the wrong kind of value
at redis.clients.jedis.Protocol.processError(Protocol.java:117)
at redis.clients.jedis.Protocol.process(Protocol.java:142)
at redis.clients.jedis.Protocol.read(Protocol.java:196)
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:288)
at redis.clients.jedis.Connection.getIntegerReply(Connection.java:213)
at redis.clients.jedis.Jedis.lpush(Jedis.java:814)
at net.cintell.CachingRedis.addSets(CachingRedis.java:85)
at net.cintell.CachingRedis.main(CachingRedis.java:48)
Can anyone tell where I am doing wrong? I want to store the csv file into redis and fetch respective fields?
public class CachingRedis {
private static HashMap<String, UserFields> Cache;
private static JedisPool pool = null;
private static final String redisHost = "localhost";
private static final Integer redisPort = 6379;
static Jedis jedis = null;
static User u;
public CachingRedis() {
pool = new JedisPool(redisHost, redisPort);
this.Cache = new HashMap<String, UserFields>();
}
public static void main(String[] args) throws ExecutionException {
CachingRedis gt = new CachingRedis();
gt.addSets();
}
private void addSets() {
InputStream in = ClassLoader.class.getResourceAsStream("/users.csv");
u = new User(in);
String[] consideredUserFields = { "Area","FirstName","LastName","Contact","Level"};
List<String[]> users = p.getUsers();
jedis = pool.getResource();
int count1 = 0;
String token = null;
String fieldName = null;
String fieldVal = null;
for (int i = 0; i < users.size(); i++) {
UserFields uFields = new UserFields();
String tmpId = Integer.toString(p.getUserId(i));
String[] tmpFields = Users.get(i);
for (int j = 0; j < tmpFields.length; j++) {
fieldName = consideredUsersFields[j];
fieldVal = tmpFields[j];
if (Cache != null && Cache.containsKey(tmpId)) {
uFields = Cache.get(tmpId);
uFields.setFieldKeyValues(fieldName, fieldVal);
Cache.put(tmpId, uFields);
} else {
uFields.setFieldKeyValues(fieldName, fieldVal);
Cache.put(tmpId, pFields);
}
}
}
Map<String, String> Properties = new HashMap<String, String>();
for (Map.Entry<String, PersonaFields> entry : Cache.entrySet()) {
Properties.put("Id", entry.getKey());
Properties.put("Area", entry.getValue()
//rest of the fields
jedis.hmset("Users"+ entry.getKey(), Properties);
}
} }
I have loaded entire cache map into redis by loading each key value into other map so that I can retrieve based on same key value
from redis

combine three generic arraylists in one

I have three List of the generic type. I want to combine them into one List and return from a function but I do not know how to convert it into one object. Here is my code.......
public class WrapUpCodes
{
public Map<Long, W_Code> codes= new HashMap<>();
public Map<Long, S_Services> services= new HashMap<>();
public Map<Long, S_Group> skills= new HashMap<>();
public WrapUpCodes(){}
public WrapUpCodes(String dnis, String skillgroup)
{
populateResultString( dnis, skillgroup);
}
public void populateResultString(String dnis, String skillgroup)
{
DBCPSource conn= new DBCPSource();
String[] Res = null;
try
{
Res = conn.GetwrapUpCodes(dnis, skillgroup);
}
catch (Exception e)
{
e.printStackTrace();
}
String code[] =Res[0].split(",");
long keyValue = 1;
for(int k=0; k<code.length; k++)
{
codes.put(keyValue, new W_Code (code[k]));
keyValue = keyValue+1;
}
String ser [] = Res[1].split(",");
keyValue=1;
for(int j=0; j<ser.length; j++)
{
services.put(keyValue, new S_Services(ser[j]));
keyValue= keyValue+1;
}
String SG [] = Res[2].split(",");
keyValue=1;
for(int j=0; j<SG.length; j++)
{
skills.put(keyValue, new S_Group(SG[j]));
keyValue= keyValue+1;
}
}
public List<List<String>> getAllCodes()
{
ArrayList<S_Group> SG= new ArrayList<S_Group>(skills.values());
ArrayList<W_Code> WC= new ArrayList<W_Code> (codes.values());
ArrayList<S_Services> SER= new ArrayList<S_Services> (services.values());
}
}
I am getting problem in this function.
public List<List<String>> getAllCodes()
{
ArrayList<S_Group> SG= new ArrayList<S_Group>(skills.values());
ArrayList<W_Code> WC= new ArrayList<W_Code> (codes.values());
ArrayList<S_Services> SER= new ArrayList<S_Services> (services.values());
}
}
I want to return all of three ArraLists. Can anyone please help me out to resolve this problem.
Return a data object:
public static class CodeData {
public final ArrayList<S_Group> groups = new ArrayList<>();
public final ArrayList<W_Code> codes = new ArrayList<>();
public final ArrayList<S_Services> services = new ArrayList<>();
}
public CodeData getAllCodes()
{
CodeData data = new CodeData();
data.groups.addAll(skills.values());
data.codes.addAll(codes.values());
data.services.addAll(services.values());
return data;
}

Java - Collection

I'm working on my first java project and I have a question. The question should be quiet simple (though the the code is not that short, but there's no reason to be intimidated :) ). I create a basic roleplaying-game and I have an abstract class "Character" that defines each character. Among its subclasses you can find Mage, who has a Spellbook (Map). Spellbook class offers methods like addToSpellbook, that works fine. In addition I have an Inventory class that has addToInventory method, which is quit identical to addToSpellbook.
My question is as follows - why can I use In the main method addToSpellbook and can't use AddToInventory?
I guess the reason is that Map doesn't have AddToInventory, so I should override put, but still, how can I use addToSpellbook ?
public class Game {
public static void main(String[] args) throws IOException {
CharacterCreator heroCreator = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc = new Scanner(System.in);
int scan = sc.nextInt();
String chosenClass = CharacterCreator.getCharacterClass(scan);
Character hero = CharacterCreator.createCharacter(chosenClass);
try {
hero.displayCharacter();
}catch (Exception e){
System.out.println("Problem displaying character data");
}
hero.getInventory().addToInventory("Long sword");
CharacterCreator heroCreator2 = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc2 = new Scanner(System.in);
int scan2 = sc.nextInt();
String chosenClass2 = CharacterCreator.getCharacterClass(scan2);
Character hero2 = CharacterCreator.createCharacter(chosenClass2);
try {
hero2.displayCharacter();
}catch (Exception e){
System.out.println("Wrong input");
}
if(hero instanceof Mage) {
((Mage)hero).getSpellBook().addToSpellBook("Magic Missiles");
((Mage)hero).getSpellBook().addToSpellBook("Fireball");
((Mage)hero).getSpellBook().addToSpellBook("Mage Armor");
((Mage)hero).getSpellBook().showSpellBook();
((Mage)hero).getSpellBook().getSpellFromSpellbook("Fireball").castSpell(hero, hero2);
((Mage)hero).getSpellBook().getSpellFromSpellbook("Magic Missiles").castSpell(hero, hero2);
((Mage)hero).getSpellBook().getSpellFromSpellbook("Mage Armor").castSpell(hero, hero);
}
}
}
abstract public class Character {
private Equipment equipment;
private Map<String, Integer> inventory;
protected Character(String name){
equipment = new Equipment();
inventory = new HashMap<String, Integer>();
}
protected Character(String name, int lvl){
equipment = new Equipment();
inventory = new HashMap<String, Integer>();
}
}
public Equipment getEquipment() { return equipment; }
public Map getInventory() { return inventory; }
}
public class Inventory {
private Map<String,Integer> inventory;
Inventory() {
inventory = new HashMap<String, Integer>();
}
public void addToInventory(String item) {
boolean found = false;
try {
for (Iterator<Map.Entry<String, Integer>> iter = inventory.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, Integer> newItem = iter.next();
if (newItem.getKey() == item) {
inventory.put(item, inventory.get(newItem) + 1);
break;
}
}
}catch (Exception e) {
System.out.println(item + " : adding failed");
}
if (!found) {
inventory.put(item,1);
}
}
public void showInventory() {
System.out.println("Show Inventory: ");
for (Map.Entry<String,Integer> entry: inventory.entrySet()) {
System.out.println( entry.getKey() + ", quantity: " + entry.getValue() );
}
System.out.println("");
}
}
public class Mage extends Character {
private SpellBook spellBook;
public Mage(String name) {
super(name);
SpellBook spellbook = new SpellBook();
}
protected Mage(String name, int lvl){
super(name, lvl);
spellBook = new SpellBook();
}
public SpellBook getSpellBook() { return spellBook; }
}
}
public class SpellBook {
private Map<String, Spell> spellBook;
SpellBook() {
spellBook = new HashMap<String, Spell>();
}
public Map getSpellBook() { return spellBook; }
public void addToSpellBook(String spellName) {
Spell newSpell = null;
try {
if (DamageSpell.getSpell(spellName) != null) {
newSpell = DamageSpell.getSpell(spellName);
} else if (ChangeStatSpell.getSpell(spellName) != null) {
newSpell = ChangeStatSpell.getSpell(spellName);
}
System.out.println(newSpell.getSpellName() + " has been added to the spellbook");
spellBook.put(newSpell.getSpellName(), newSpell);
} catch (Exception e){
System.out.println("Adding " + spellName +"to spellbook has failed");
}
}
public void showSpellBook() {
System.out.println("Show spellbook: ");
for (Iterator<String> iter = spellBook.keySet().iterator(); iter.hasNext(); ) {
String spell = iter.next();
System.out.println(spell);
}
System.out.println("");
}
public Spell getSpellFromSpellbook(String spellName) {
Spell spl = null;
//Spell splGet = spellBook.get(spellName); /* straight forward implementation*/
// System.out.println("The spell " + splGet.getSpellName() + " has been retrived from the spellbook by using get method");
try {
for (Iterator<Map.Entry<String, Spell>> iter = spellBook.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, Spell> spell = iter.next();
if (spell.getKey() == spellName) {
spl = spell.getValue();
}
}
}catch (Exception e) {
System.out.println(spellName + " : no such spell in spellbook");
}
return spl;
}
}
getInventory() returns a Map and Map doesn't have the addToInventory() method.
getInventory() should add an Inventory instance.

Find the first and follow set of a given grammar in java

I have been given the problem to complete, and the algorithms to find the first and follow, but my problem is I cant quite find a data structure to implement to find these sets.
import java.util.Stack;
public class FirstFollowSet {
private final String[] term_tokens = { "begin", "end", ";", "if", "then", "else", "fi", "i", "=", "+", "-", "*",
"/", "(", ")", "const" };
private final static String[] non_term_tokens = { "Start", "Prog", "Block", "Body", "S", "E", "T", "F" };
private static RuleStack rules;
private Stack<String> firstSet;
private Stack<String> followSet;
private boolean is_terminal(String str) {
boolean test = false;
for (int i = 0; i < term_tokens.length; i++) {
if (str.equals(term_tokens[i]))
test = true;
}
return test;
}
private boolean is_non_term(String str){
for(int i = 0; i < non_term_tokens.length; i++)
{
if(str.equals(non_term_tokens[i]))
{
return true;
}
}
return false;
}
private class Rule{
String def, token;
public Rule()
{
def = "";
token = "";
}
public Rule(String d, String t)
{
def = d;
token = t;
}
public String getDef() {
return def;
}
public String getToken() {
return token;
}
public String toString()
{
String str = "";
str+= token + " " + def + '\n';
return str;
}
}
public class RuleStack{
Stack<Rule> rules;
public RuleStack(String grammar)
{
if(grammar.equals("G1"));
{
rules = new Stack();
Rule rule = new Rule("Prog", "Start");
rules.push(rule);
rule = new Rule("Block #", "Prog");
rules.push(rule);
rule = new Rule("begin Body end", "Block");
rules.push(rule);
rule = new Rule("begin S end", "Body");
rules.push(rule);
rule = new Rule("Body ; S", "Body");
rules.push(rule);
rule = new Rule("S", "Body");
rules.push(rule);
rule = new Rule("if E then S else S fi", "S");
rules.push(rule);
rule = new Rule("if E else S fi", "S");
rules.push(rule);
rule = new Rule("i = E", "S");
rules.push(rule);
rule = new Rule("Block", "S");
rules.push(rule);
rule = new Rule("E + T", "E");
rules.push(rule);
rule = new Rule("E * T", "E");
rules.push(rule);
rule = new Rule("T", "E");
rules.push(rule);
rule = new Rule("T * F", "T");
rules.push(rule);
rule = new Rule("T / F", "T");
rules.push(rule);
rule = new Rule("F", "T");
rules.push(rule);
rule = new Rule("const", "F");
rules.push(rule);
rule = new Rule("( E )", "F");
rules.push(rule);
}
}
}
public FirstFollowSet()
{
rules = new RuleStack("G1");
firstSet = new Stack();
followSet = new Stack();
}
public String FindFirstSet(String str, Stack<String> used)
{
if(used.contains(str))
{
return null;
}
String firstToken = "";
String win = "";
if(str.indexOf(" ") != -1)
firstToken = str.substring(0, str.indexOf(" "));
else
firstToken = str;
if(is_terminal(firstToken))
{
if(!(firstSet.contains(firstToken)))
win = firstToken;
if(win.equals("") != true)
firstSet.push(win);
}
else if(is_non_term(firstToken) && !(used.contains(firstToken)))
{
used.push(firstToken);
if(firstToken.equals("lambda"))
{
if(!(firstSet.contains(firstToken)))
win = firstToken;
}
else
{
RuleStack rules = new RuleStack("G1");
while(rules.rules.isEmpty() != true)
{
Rule winner = rules.rules.pop();
if(winner.token.equals(firstToken))
{
String test = FindFirstSet(winner.def, used);
if(!(test.equals("lambda")))
{
if(!(firstSet.contains(test)))
win = test;
}
}
}
}
}
return win;
}
public String findFollowSet(String str)
{
if(str.equals("S"))
{
followSet.push("$");
}
for(int i = 0; i < non_term_tokens.length; i++)
{
if(str.contains(non_term_tokens[i]))
{
int index = str.indexOf(non_term_tokens[i]);
Stack<String> used = new Stack();
FirstFollowSet test = new FirstFollowSet();
if(index > 0 && index < str.length()-1)
{
test.FindFirstSet(str, used);
while(test.firstSet.isEmpty() != true)
{
String token = firstSet.pop();
if(!(token.equals("lambda")))
test.followSet.push(token);
}
}
else if(index > 0 && index == str.length()-1)
{
}
}
}
}
public static void main(String[] args) {
FirstFollowSet test = new FirstFollowSet();
Stack<String> used = new Stack();
test.FindFirstSet("S", used);
while(test.firstSet.isEmpty() != true)
{
String str = test.firstSet.pop();
System.out.println(str);
}
}
}
This is the code I have so far, and the find first set works just fine, but the findfollowset method I'm not quite sure how to implement. The only idea I can seem to come up with is making a stack for each non-terminal symbol, apply the algorithm, and add each terminal symbol returned to the set it belongs to. This method just feel like its more work then necessary.
If anyone has ever solved this problem, or has seen a way to solve this problem I would just like to know what sort of data structure was used and how it the algorithm was implemented for said structure.
Thank you for taking the time to read this, and i appreciate any feedback given.
package modelo;
import java.util.ArrayList;
/**
*
* #author celeste
*/
public class Axioma {
public char getSimbolo() {
return simbolo;
}
public void setSimbolo(char simbolo) {
this.simbolo = simbolo;
}
public ArrayList<Character> getPrimeros() {
return primeros;
}
public void setPrimeros(ArrayList<Character> primeros) {
this.primeros = primeros;
}
public ArrayList<Character> getSiguientes() {
return siguientes;
}
public void setSiguientes(ArrayList<Character> siguientes) {
this.siguientes = siguientes;
}
public ArrayList<Character> getPredictivos() {
return predictivos;
}
public void setPredictivos(ArrayList<Character> predictivos) {
this.predictivos = predictivos;
}
public ArrayList<Character> getRegla() {
return regla;
}
public void setRegla(ArrayList<Character> regla) {
this.regla = regla;
}
private ArrayList<Character> primeros = new ArrayList<>();
private ArrayList<Character> siguientes = new ArrayList<>();
private ArrayList<Character> predictivos = new ArrayList<>();
private ArrayList<Character> regla = new ArrayList<>();
private char simbolo;
}

error cannot find symbol and class discrete Attribute

import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class FileReader
{
public static final String PATH_TO_DATA_FILE = "playtennis.data";
public static ArrayList<Record> buildRecords() {
BufferedReader reader = null;
DataInputStream dis = null;
ArrayList<Record> records = new ArrayList<Record>();
try {
File f = new File(PATH_TO_DATA_FILE);
FileInputStream fis = new FileInputStream(f);
reader = new BufferedReader(new InputStreamReader(fis));;
// read the first record of the file
String line;
Record r = null;
ArrayLAist<DiscreteAttribute> attributes;
while ((line = reader.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ",");
attributes = new ArrayList<DiscreteAttribute>();
r = new Record();
if(Hw1.NUM_ATTRS != st.countTokens()) {
throw new Exception("Unknown number of attributes!");
}
#SuppressWarnings("unused")
String day = st.nextToken();
String outlook = st.nextToken();
String temperature = st.nextToken();
String humidity = st.nextToken();
String wind = st.nextToken();
String playTennis = st.nextToken();
if(outlook.equalsIgnoreCase("overcast")) {
attributes.add(new DiscreteAttribute("Outlook", DiscreteAttribute.Overcast));
}
else if(outlook.equalsIgnoreCase("sunny")) {
attributes.add(new DiscreteAttribute("Outlook", DiscreteAttribute.Sunny));
}
else if(outlook.equalsIgnoreCase("rain")) {
attributes.add(new DiscreteAttribute("Outlook", DiscreteAttribute.Rain));
}
if(temperature.equalsIgnoreCase("hot")) {
attributes.add(new DiscreteAttribute("Temperature", DiscreteAttribute.Hot));
}
else if(temperature.equalsIgnoreCase("mild")) {
attributes.add(new DiscreteAttribute("Temperature", DiscreteAttribute.Mild));
}
else if(temperature.equalsIgnoreCase("cool")) {
attributes.add(new DiscreteAttribute("Temperature", DiscreteAttribute.Cool));
}
if(humidity.equalsIgnoreCase("high")) {
attributes.add(new DiscreteAttribute("Humidity", DiscreteAttribute.High));
}
else if(humidity.equalsIgnoreCase("normal")) {
attributes.add(new DiscreteAttribute("Humidity", DiscreteAttribute.Normal));
}
if(wind.equalsIgnoreCase("weak")) {
attributes.add(new DiscreteAttribute("Wind", DiscreteAttribute.Weak));
}
else if(wind.equalsIgnoreCase("strong")) {
attributes.add(new DiscreteAttribute("Wind", DiscreteAttribute.Strong));
}
if(playTennis.equalsIgnoreCase("no")) {
attributes.add(new DiscreteAttribute("PlayTennis", DiscreteAttribute.PlayNo));
}
else if(playTennis.equalsIgnoreCase("yes")) {
attributes.add(new DiscreteAttribute("PlayTennis", DiscreteAttribute.PlayYes));
}
r.setAttributes(attributes);
records.add(r);
}
}
}
I haven given file name as FileReader
I'm getting errors on cannot file symbol
Cannot find symbol symbol:class discrete Attribute, location:class classifier.FileReader
Cannot find the symbol symbol:variable discrete Attribute location:class classifier.FileReader
Here DiscreteAttribute class. You need add that class your project.
public class DiscreteAttribute extends Attribute { public static final int Sunny = 0; public static final int Overcast = 1; public static final int Rain = 2; public static final int Hot = 0; public static final int Mild = 1; public static final int Cool = 2; public static final int High = 0; public static final int Normal = 1; public static final int Weak = 0; public static final int Strong = 1; public static final int PlayNo = 0; public static final int PlayYes = 1; enum PlayTennis { No, Yes } enum Wind { Weak, Strong } enum Humidity { High, Normal } enum Temp { Hot, Mild, Cool } enum Outlook { Sunny, Overcast, Rain } public DiscreteAttribute(String name, double value) { super(name, value); } public DiscreteAttribute(String name, String value) { super(name, value); } }

Categories

Resources