Here's the code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class MadLib
{
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib()
{
loadNouns();
loadVerbs();
loadAdjectives();
out.println(nouns);
}
public MadLib(String fileName)
{
//load stuff
loadNouns();
loadVerbs();
loadAdjectives();
try{
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e)
{
out.println("Houston we have a problem!");
}
}
public void loadNouns()
{
nouns = new ArrayList<String>();
try{
//nouns = new ArrayList<String>();
String nou = "";
Scanner chopper = new Scanner(new File ("nouns.dat"));
//chopper.nextLine();
while(chopper.hasNext()){
nou = chopper.next();
out.println(nou);
nouns.add(nou);
//chopper.nextLine();
}
//chopper.close();
out.println(nouns.size());
}
catch(Exception e)
{
out.println("Will");
}
}
public void loadVerbs()
{
verbs = new ArrayList<String>();
try{
Scanner chopper = new Scanner(new File("verbs.dat"));
while(chopper.hasNext()){
verbs.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e)
{
out.println("run");
}
}
public void loadAdjectives()
{
adjectives = new ArrayList<String>();
try{
Scanner chopper = new Scanner(new File("adjectives.dat"));
while(chopper.hasNext()){
adjectives.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e)
{
}
}
public String getRandomVerb()
{
String verb = "";
int num = 0;
num = (int)(Math.random()*(verbs.size()-1));
verb = verbs.get(num);
return verb;
}
public String getRandomNoun()
{
String noun = "";
int num = 0;
if(nouns == null){
loadNouns();
}
double rand = (Math.random());
num = (int)(rand * (nouns.size()-1));
out.println(num);
noun = nouns.get((int) num);
out.print(noun);
return noun;
}
public String getRandomAdjective()
{
String adj = "";
int num = 0;
num = (int)(Math.random()*(adjectives.size()-1));
adj = adjectives.get(num);
return adj;
}
public String toString()
{
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
and here's one of the .dat files (the other 2 are the exact same aside from the specific words they contain):
dog
pig
chicken
building
car
person
place
thing
truck
city
state
school
student
bird
turkey
lion
tiger
alligator
elephant
My issue is that I can't get any of my arrayLists to read in their appropriate .dat files and from my POV, my code seems like it should do that
UPDATE
current output aside from the absence of "Will" (I removed that line):
run
[ ]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at MadLib.getRandomNoun(MadLib.java:130)
at MadLib.toString(MadLib.java:147)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at Lab16d.main(Lab16d.java:18)
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public static void main(String args[]) {
MadLib a = new MadLib();
System.out.println(a.toString());
}
public MadLib() {
loadAllWords();
System.out.println(nouns);
}
public MadLib(String fileName) {
loadAllWords();
try {
Scanner file = new Scanner(new File(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadAllWords() {
loadNouns();
loadVerbs();
loadAdjectives();
}
public void loadNouns() {
nouns = loadFile("nouns.dat");
}
public void loadVerbs() {
verbs = loadFile("verbs.dat");
}
public void loadAdjectives() {
adjectives = loadFile("adjectives.dat");
}
public ArrayList<String> loadFile(String filename) {
ArrayList<String> words = new ArrayList<String>();
try {
Scanner chopper = new Scanner(new File(filename));
while (chopper.hasNext()) {
words.add(chopper.next());
// just calling nextLine will cause an exception at the end of the file unless you have an blank line there on purpose, so this makes sure it does
if (chopper.hasNext()) {
chopper.nextLine();
}
}
chopper.close();
} catch (Exception e) {
e.printStackTrace();
}
return words;
}
public String getRandomWord(ArrayList<String> words) {
Random rand = new Random();
int num = rand.nextInt(words.size());
String word = nouns.get(num);
System.out.println(word);
return word;
}
public String getRandomVerb() {
if (verbs == null) {
loadNouns();
}
return getRandomWord(verbs);
}
public String getRandomNoun() {
if (nouns == null) {
loadNouns();
}
return getRandomWord(nouns);
}
public String getRandomAdjective() {
if (adjectives == null) {
loadNouns();
}
return getRandomWord(adjectives);
}
public String toString() {
return "The " + getRandomNoun() + " " + getRandomVerb() + " after the " + getRandomAdjective() + " " + getRandomAdjective() + " " + getRandomNoun() + " while the " + getRandomNoun() + " " + getRandomVerb() + " the " + getRandomNoun();
}
}
Related
In the Fileoperator class I tried to make a couple methods to enable saving (from inputs from the screen to a text file) and loading (from exactly the same text file and print it out on screen). Since both of them are static methods, I can't quote them directly in my FileoperatorTest. How could I write the tests for them?
(I've already written some tests for Person.)
public class Fileoperator {
private ArrayList<Person> saveList;
private Scanner scanner;
int age;
String name;
int income;
int expenditure;
int willingnesstoInvest;
String exit;
public Fileoperator() {
saveList = new ArrayList<>();
scanner = new Scanner(System.in);
processOperations();
}
private void processOperations() {
while (true) {
Person personEntry = getPerson();
if (exit.equals("yes")) {
personEntry.updateMaster(age, name, income, expenditure, willingnesstoInvest);
personResult(personEntry);
break;
}
personEntry.updateMaster(age, name, income, expenditure, willingnesstoInvest);
personResult(personEntry);
System.out.println(personEntry.print());
}
for (Person p: saveList) {
System.out.println(p.print());
}
}
private Person getPerson() {
Person personEntry = new Person(0, "", 0, 0, 0);
System.out.println("Age: ");
age = scanner.nextInt();
scanner.nextLine();
System.out.println("Name: ");
name = scanner.nextLine();
System.out.println("Income: ");
income = scanner.nextInt();
System.out.println("Expenditure:");
expenditure = scanner.nextInt();
System.out.println("Willingness to invest: ");
willingnesstoInvest = scanner.nextInt();
scanner.nextLine();
System.out.println("done?(yes or no)");
exit = scanner.nextLine();
return personEntry;
}
private void personResult(Person p) {
saveList.add(p);
}
public static void mainhelper() {
try {
printload(load());
} catch (IOException e) {
e.printStackTrace();
}
Fileoperator fo = new Fileoperator();
try {
fo.save();
} catch (IOException e) {
e.printStackTrace();
}
}
public void save() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("output.txt"));;
PrintWriter writer = new PrintWriter("output.txt","UTF-8");
for (Person p: saveList) {
lines.add(p.getAge() + ", " + p.getName() + ", "
+ p.getIncome() + ", " + p.getExpenditure() + ", " + p.getwillingnesstoInvest());
}
for (String line : lines) {
ArrayList<String> partsOfLine = splitOnSpace(line);
System.out.println("Age: " + partsOfLine.get(0) + ", ");
System.out.println("Name: " + partsOfLine.get(1) + ", ");
System.out.println("Income " + partsOfLine.get(2) + ", ");
System.out.println("Expenditure " + partsOfLine.get(3) + ", ");
System.out.println("WillingnesstoInvest " + partsOfLine.get(4) + ", ");
writer.println(line);
}
writer.close(); //note -- if you miss this, the file will not be written at all.
}
public static ArrayList<String> splitOnSpace(String line) {
String[] splits = line.split(", ");
return new ArrayList<>(Arrays.asList(splits));
}
public static ArrayList<Person> load() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("output.txt"));
ArrayList<Person> loadList = new ArrayList();
for (String line : lines) {
if (line.equals("")) {
break;
} else {
Person fromline = fromline(line);
loadList.add(fromline);
}
}
return loadList;
}
public static void printload(ArrayList<Person> loadList) {
for (Person p: loadList) {
System.out.println(p.print());
}
}
private static Person fromline(String line) {
Person fromline = new Person(0, "", 0, 0, 0);
ArrayList<String> partsOfLine = splitOnSpace(line);
int age = Integer.parseInt(partsOfLine.get(0));
int income = Integer.parseInt(partsOfLine.get(2));
int expenditure = Integer.parseInt(partsOfLine.get(3));
int willingnesstoInvest = Integer.parseInt(partsOfLine.get(4));
fromline.updateMaster(age, partsOfLine.get(1), income, expenditure, willingnesstoInvest);
return fromline;
}
}
I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?
This is how my toString looks like:
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
Full code:
import java.util.*;
import java.io.*;
public class Codes {
public static void main(String[] args) {
List<Codes2> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] personData = fileRead.split(":");
String personName = personData[0];
String userNameGenerator = personData[1];
Codes2 personObj = new Codes2(personName, userNameGenerator);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++){
String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
for(int j = 0; j < regionSplit.length; j++){
newStrSet.add(regionSplit[j]);
}
}
for (String p: newStrSet) {
System.out.printf("%s -> ", p);
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.getPersonName());
}
}
System.out.println();
}
}
}
Java Class:
public class Codes2 implements Comparable<Codes2> {
private String personName;
private String userNameGenerator;
public Codes2(String personName, String userNameGenerator) {
this.personName = personName;
this.userNameGenerator = userNameGenerator;
}
public String getPersonName() {
return personName;
}
public String getUserNameGenerator() {
return userNameGenerator;
}
#Override
public int compareTo(Codes2 o) {
return getUserNameGenerator().compareTo(o.getUserNameGenerator());
}
public int compare(Object lOCR1, Object lOCR2) {
return ((Codes2)lOCR1).userNameGenerator
.compareTo(((Codes2)lOCR2).userNameGenerator);
}
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
}
Everything looks right in your code.
I think you should just call the method when you are trying to print it out:
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.toString());
}
}
This follows the fact that the class that prints out the object is not so closely coupled with the class that hold the data.
Try:
#Override
public String toString() {
return String.format("%s -> [%s]",this.userNameGenerator,this.personName);
}
I am trying to read from a text file of the type (Artist, Title, Genre, Recordcompany, Release year, Number of songs, Playtime):
The Beatles, Abbey Road, Rock, Apple Records, 1969, 17, 47.16
Sia, 1000 Forms of Fear, Pop, Intertia, 2014, 12, 48.41
Taylor Swift, Speak Now
I have created a CD class:
package q;
public class CD {
//
private String artist;
private String titel;
private String genre;
private String recordcompany;
private int year; //
private int songs; //
private double playtime; //
public CD() { //
}
public CD(String newArtist, String newTitel) {
artist = newArtist;
titel = newTitel;
}
public CD(String newArtist, String newTitel, String newGenre, String newRecordcompany, int newYear, int newSongs, double newPlaytime) {
artist = newArtist;
titel = newTitel;
genre = newGenre;
recordcompany = newRecordcompany;
year = newYear;
songs = newSongs;
playtime = newPlaytime;
}
public String getArtist() { //
return artist;
}
public String getTitel() {
return titel;
}
public String getGenre() {
return genre;
}
public String getRecordcompany() {
return recordcompany;
}
public int getYear() {
return year;
}
public int getsong() {
return songs;
}
public double getPlaytime() {
return playtime;
}
public void setArtist(String newArtist) { //
artist = newArtist;
}
public void setTitel(String newTitel) {
titel = newTitel;
}
public void setGenre(String newGenre) {
genre = newGenre;
}
public void setRecordcompany(String newRecordcompany) {
recordcompany = newRecordcompany;
}
public void setYear(int newYear) {
year = newYear;
}
public void setSongs(int newSongs) {
songs = newSongs;
}
public void setplaytime(double newPlaytime) {
playtime = newPlaytime;
}
#
Override public String toString() { //
return ("Artist " + artist + System.lineSeparator() + "Titel: " + titel + System.lineSeparator() + "Genre: " + genre + System.lineSeparator() + "Recordcompany: " + recordcompany + System.lineSeparator() + "Year: " + year + System.lineSeparator() + "Songs: " + songs + System.lineSeparator() + "Playtime: " + playtime + System.lineSeparator());
}
}
I am trying to read from the text file and then convert it into a arraylist. I know I have overcomplicated it by first conerting the text file to a string array and then converting it to an arraylist. I would like to use set and get methods when I create the array, if it is possible. I wonder if any of you have any tips for me for how I can make the code less complicated and include set and get methods if possible, thank you.
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
String year = "";
String songs = "";
String playtime = "";
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String tmp[] = line.split(",");
artist = tmp[0];
titel = tmp[1];
if (tmp.length > 2) {
genre = tmp[2];
recordcompany = tmp[3];
year = (tmp[4]);
songs = (tmp[5]);
playtime = (tmp[6]);
} else {
genre = "";
recordcompany = "";
year = "";
songs = "";
playtime = "";
}
List < String > unsorted = Arrays.asList(tmp);
for (String e: unsorted) {
System.out.println(e);
}
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
EDITED
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
int year = 0;
int songs = 0;
double playtime = 0.0;
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
System.out.println(cdsList);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Something like below.
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
cdsList.add(cd);
}
System.out.println(cdsList);
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
I've dug up the following code for serializing an ItemStack in bukkit (Minecraft). I've been able to serialize an item in hand with the following:
itemString = ItemStackUtils.deserialize(player.getInventory().getItemInHand());
I can't figure out how to utilize the deserial call however. What I am trying to do is to pull an item from the players hand, serialize it, stick it into a config file, then when the player runs another command... deserialize it and slap it into their inventory. I am fairly certain this class will meet my needs if I just can get the last part working.
public final class ItemStackUtils {
public static String getEnchants(ItemStack i){
List<String> e = new ArrayList<String>();
Map<Enchantment, Integer> en = i.getEnchantments();
for(Enchantment t : en.keySet()) {
e.add(t.getName() + ":" + en.get(t));
}
return StringUtils.join(e, ",");
}
public static String deserialize(ItemStack i){
String[] parts = new String[6];
parts[0] = i.getType().name();
parts[1] = Integer.toString(i.getAmount());
parts[2] = String.valueOf(i.getDurability());
parts[3] = i.getItemMeta().getDisplayName();
parts[4] = String.valueOf(i.getData().getData());
parts[5] = getEnchants(i);
return StringUtils.join(parts, ";");
}
public ItemStack deserial(String p){
String[] a = p.split(";");
ItemStack i = new ItemStack(Material.getMaterial(a[0]), Integer.parseInt(a[1]));
i.setDurability((short) Integer.parseInt(a[2]));
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(a[3]);
i.setItemMeta(meta);
MaterialData data = i.getData();
data.setData((byte) Integer.parseInt(a[4]));
i.setData(data);
if (a.length > 5) {
String[] parts = a[5].split(",");
for (String s : parts) {
String label = s.split(":")[0];
String amplifier = s.split(":")[1];
Enchantment type = Enchantment.getByName(label);
if (type == null)
continue;
int f;
try {
f = Integer.parseInt(amplifier);
} catch(Exception ex) {
continue;
}
i.addEnchantment(type, f);
}
}
return i;
}
}
here it saves & loads the whole NBT
package XXXXXXXXX
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData;
import net.minecraft.server.v1_8_R3.MojangsonParseException;
import net.minecraft.server.v1_8_R3.MojangsonParser;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
public class ItemSerialize {
public ItemSerialize() {
}
public static String serialize(ItemStack i) {
String[] parts = new String[7];
parts[0] = i.getType().name();
parts[1] = Integer.toString(i.getAmount());
parts[2] = String.valueOf(i.getDurability());
parts[3] = i.getItemMeta().getDisplayName();
parts[4] = String.valueOf(i.getData().getData());
parts[5] = getEnchants(i);
parts[6] = getNBT(i);
return StringUtils.join(parts, ";");
}
public static String getEnchants(ItemStack i) {
List<String> e = new ArrayList<String>();
Map<Enchantment, Integer> en = i.getEnchantments();
for (Enchantment t : en.keySet()) {
e.add(t.getName() + ":" + en.get(t));
}
return StringUtils.join(e, ",");
}
public static String getLore(ItemStack i) {
List<String> e = i.getItemMeta().getLore();
return StringUtils.join(e, ",");
}
public static String getNBT(ItemStack i) {
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
NBTTagCompound compound = nmsStack.hasTag() ? nmsStack.getTag() : new NBTTagCompound();
return compound.toString();
}
public static ItemStack setNBT(ItemStack i, String NBT) {
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
try {
NBTTagCompound compound = MojangsonParser.parse(NBT);
nmsStack.setTag(compound);
} catch (MojangsonParseException e1) {
e1.printStackTrace();
}
return CraftItemStack.asBukkitCopy(nmsStack);
}
#SuppressWarnings("deprecation")
public static ItemStack deserial(String p) {
String[] a = p.split(";");
ItemStack i = new ItemStack(Material.getMaterial(a[0]), Integer.parseInt(a[1]));
i.setDurability((short) Integer.parseInt(a[2]));
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(a[3]);
i.setItemMeta(meta);
MaterialData data = i.getData();
data.setData((byte) Integer.parseInt(a[4]));
i.setData(data);
if (!a[6].isEmpty()) {
i = setNBT(i, a[6]);
}
if (!a[5].isEmpty()) {
String[] parts = a[5].split(",");
for (String s : parts) {
String label = s.split(":")[0];
String amplifier = s.split(":")[1];
Enchantment type = Enchantment.getByName(label);
if (type == null)
continue;
int f;
try {
f = Integer.parseInt(amplifier);
} catch (Exception ex) {
continue;
}
i.addUnsafeEnchantment(type, f);
}
}
return i;
}
}
ItemStack rItem = ItemStackUtils.deserial(itemString);
I have the following textfile contains the information that will be added to the treemap.
1 apple
1 orange
3 pear
3 pineapple
4 dragonfruit
my code:
public class Treemap {
private List<String> fList = new ArrayList<String>();
private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();
public static void main(String[] args) {
Treemap tm = new Treemap();
String file = "";
if (args.length == 1) {
file = args[0];
try {
tm.Read(file);
} catch (IOException ex) {
System.out.println("Error");
}
} else {
System.out.println("Usage: java treemap 'Filename'");
System.exit(1);
}
}
public void Read(String file) throws IOException {
//Scanner in = null;
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
if (file_Array[0].equalsIgnoreCase("1")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(1);
} else if (file_Array[0].equalsIgnoreCase("3")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(3);
} else if (file_Array[0].equalsIgnoreCase("4")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(4);
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item) == false) {
tMap.put(item, fList);
fList.add(fruit);
System.out.println("Fruits added " + item);
} else {
System.out.println("not exist");
}
}
public void Display(int item) {
if (tMap.containsKey(item)) {
System.out.print("Number " + item + ":" + "\n");
System.out.print(fList);
System.out.print("\n");
} else {
System.out.print(item + " WAS NOT FOUND"+ "\n");
}
}
}
ideal output
Number 1:
[apple, orange]
Number 3:
[pear, pineapple]
Number 4:
[dragonfruit]
currently i only able to output this
Fruits added 1
Number 1:
[apple]
not exist
Number 1:
[apple]
Fruits added 3
Number 3:
[apple, pear]
not exist
Number 3:
[apple, pear]
Fruits added 4
Number 4:
[apple, pear, dragonfruit]
How should I display the item following by the list of fruit added to that number?
Try this code. Its working. By the way you should improve this code. The code is not optimised.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class Treemap {
private List<String> fList = new ArrayList<String>();
private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();
public static void main(String[] args) {
Treemap tm = new Treemap();
String file = "";
if (args.length == 1) {
file = args[0];
try {
tm.Read(file);
} catch (IOException ex) {
System.out.println("Error");
}
} else {
System.out.println("Usage: java treemap 'Filename'");
System.exit(1);
}
}
public void Read(String file) throws IOException {
//Scanner in = null;
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
if (file_Array[0].equalsIgnoreCase("1")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
// Display(1);
} else if (file_Array[0].equalsIgnoreCase("3")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
// Display(3);
} else if (file_Array[0].equalsIgnoreCase("4")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
// Display(4);
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
for(int i: tMap.keySet())
Display(i);
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item) == false) {
fList = new ArrayList<>();
fList.add(fruit);
tMap.put(item, fList);
// System.out.println("Fruits added " + item);
} else {
tMap.get(item).add(fruit);
// System.out.println("not exist");
}
}
public void Display(int item) {
if (tMap.containsKey(item)) {
System.out.print("Number " + item + ":" + "\n");
System.out.print(tMap.get(item));
System.out.print("\n");
} else {
System.out.print(item + " WAS NOT FOUND"+ "\n");
}
}
}
Here is your READ , ADD ad DISPLAY method,
public void Read(String file) throws IOException {
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
Add(Integer.parseInt(file_Array[0]),file_Array[1]);
}
Display(-1); // -1 for displaying all
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item)) {
fList = tMap.get(item);
} else {
fList = new ArrayList<String>();
}
fList.add(fruit);
tMap.put(item, fList);
}
public void Display(int key) {
if(key == -1){
for (Map.Entry<Integer, List<String>> entry : tMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}else{
System.out.println(key);
System.out.println(tMap.get(key));
}
}
You make unnecessary complicated your code. Try with simple code.
public class Treemap {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("file.txt"));
Map<Integer, List<String>> tMap = new TreeMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] values=line.split(" ");
List<String> fList;
Integer key=Integer.valueOf(values[0]);
if(tMap.containsKey(key)){//Key already inserted
fList=tMap.get(key); //Get existing List of key
fList.add(values[1]);
}
else{
fList = new ArrayList<String>();
fList.add(values[1]);
tMap.put(key, fList);
}
}
for (Map.Entry<Integer, List<String>> entry : tMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
Output:
1
[apple, orange]
3
[pear, pineapple]
4
[dragonfruit]
Change some code for the method Add(), which is incorrect in your code.
What if the Map contains the key?
Following code is modified based on your code, hope this can help you some.
public void Add(int item, String fruit) {
if (tMap.containsKey(item)==false) {
fList.clear();
fList.add(fruit);
tMap.put(item, fList);
System.out.println("Fruits added " + item);
} else {
tMap.get(item).add(fruit);
}
}