I need help with how to find and display the state information the user chose to the screen. I have five files which i have put into arrays. The five arrays contain information of a state(State Name, state capital,state nickname, State flower, state population.)
My program should allow the user of the program to enter a state name, and should display the information about that state (nickname, capital, flower, and population) to the screen.
Each input file contains the information in alphabetical order by state name. So line 1 of the state name file is Alabama, line 1 of the capital file is Montgomery (the capital of Alabama), line 1 of the flower file is the state flower for Alabama, line 1 of the nickname file is the nickname of Alabama, and line 1 of the population file is the population o``f Alabama. Line 2 of each file is info for Alaska, line 3 is for Arizona, etc.
This is my code so far.
public static void main(String[] args) throws FileNotFoundException {
String capital, stateFlowers, stateNickName, statesNames;
int statePopulation;
Scanner keyboard = new Scanner (System.in);
String userStateChoise;
File capitals = new File("capitals.txt");
File flores = new File("flowers.txt");
File nickName = new File("nicknames.txt");
File populacion = new File("population.txt");
File state_Name = new File("stateNames.txt");
System.out.println("Enter a State Name");
userStateChoise = keyboard.nextLine();
if (!capitals.exists()) {
System.out.println("The capitals input file was not found");
System.exit(0);
}
if (!flores.exists()) {
System.out.println("The flores input file was not found");
System.exit(0);
}
if (!nickName.exists()) {
System.out.println("The nickName input file was not found");
System.exit(0);
}
if (!populacion.exists()) {
System.out.println("The populacion input file was not found");
System.exit(0);
}
if (!state_Name.exists()) {
System.out.println("The stateName input file was not found");
System.exit(0);
}
Scanner inputFile = new Scanner(capitals);
Scanner flower = new Scanner(flores);
Scanner nickNames = new Scanner(nickName);
Scanner populations = new Scanner(populacion);
Scanner names = new Scanner(state_Name);
// ArrayList myCapitals = new ArrayList();
// ArrayList<String> stateNames = new ArrayList();
while (inputFile.hasNext() && flower.hasNext() && nickNames.hasNext()
&& populations.hasNext() && names.hasNext())
{
// reading all states from the input file
//reading all cities from the input file
capital = inputFile.nextLine();
stateFlowers = flower.nextLine();
stateNickName = nickNames.nextLine();
statePopulation = populations.nextInt();
statesNames = names.nextLine();
String[] stateCapitalArray = {capital};
String[] stateflowersArray = {stateFlowers};
String[] stateNickNameArray = {stateNickName};
int [] statePopulationArray = {statePopulation};
String[] stateNamesArray = {statesNames};
// I used for loops to go through each item in the array and to display it to the screen
for (int index = 0; index < stateNamesArray.length; index++)
{
System.out.println("State name : " +stateNamesArray[index]);
}
for (int index = 0; index < stateflowersArray.length; index++)
{
System.out.println("State flower : " + stateflowersArray[index]);
}
for (int index = 0; index < stateCapitalArray.length; index++)
{
System.out.println("The capital : " + stateCapitalArray[index]);
}
for (int index = 0; index < stateNickNameArray.length; index++)
{
System.out.println("State nickName : " + stateNickNameArray[index]);
}
for (int index = 0; index < statePopulationArray.length; index++)
{
System.out.println("State pupoluation : " + statePopulationArray[index]);
System.out.println("\n\n\n");
}
}
inputFile.close();
flower.close();
nickNames.close();
// populations.close();
}
}
Besides the awkward method of collecting and storing the information and getting user input, the most glaring error I see is how you're building your array. Every time you read a new line you're reinitializing each array with one thing instead of adding each thing to each array.
You'll end up with arrays of the last item from every file. The arrays should be created and initialized outside of the while loop and each item added to them as you read them.
Related
Write a program that shall calculate the vocabulary richness of a text in a file and the frequency of the most common word. The vocabulary richness is the number of words in the text divided by the number of distinct words. The frequency of a word is the number of times the word is mentioned in the text divided by the total number of words in the text.
Define and implement class WordCounter with two private fields String word and int count, constructor WordCounter(String word), and public methods String getName(), int getCount(), and void addToCounter().
Define and implement class Corpus (as in text corpus) with one private field ArrayList<WordCounter> words, constructor Corpus(BufferedReader infile), and public methods double getVocabularyRichness() and String getMostFrequentWord().
Implement a test program (as the public static void main method in Corpus) that reads all files in a specific folder, creates a Corpus object from each (previously opened) file, and saves the requested statistics into another file stats.csv. You can either create a new Corpus object for each file or define an ArrayList<Corpus> of the corpora.
Each line of the CSV file must consist of three fields separated by commas (but no spaces!): the file name, the vocabulary richness, and the most frequently used word. Run your program on all Shakespeare's plays. Submit the CSV file together with the Java file.
I wrote what I think is the correct implementation of the HW problem because it works properly for some of the text files, however only the words.get(i).getName() (I tested with words.get(i).getCount()) method will print a blank space for some of the files. I have tried everything, and can't seem to figure it out. Can you please give me a hint or some guidance as to how to fix this issue?
public class Corpus {
private ArrayList<WordCounter> words = new ArrayList <WordCounter>() ;
Corpus(BufferedReader infile){
String ln;
try {
while((ln = infile.readLine()) != null) {
for (String word : ln.toLowerCase().split("([,.\\s]+)")) {
int reference = 0;
for(int i = 0; i < words.size(); i++) {
if (word.equals(words.get(i).getName())) {
reference++;
words.get(i).addToCounter();
} }
if (reference==0) { words.add(new WordCounter(word)); }
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public double getVocabularyRichness() {
int word_count=0;
for(int i = 0; i < words.size(); i++) {
word_count=word_count+words.get(i).getCount();
}
return (double)word_count/(double)words.size();
}
public String getMostFrequentWord() {
String winner = "*AN ERROR OCCURRED*";
int max_count = 0;
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() > max_count){
max_count = words.get(i).getCount();
}
}
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() == max_count){
winner = words.get(i).getName();
}
}
//winner="Test " + String.valueOf(words.get(i).getName());;
//return String.valueOf(max_count);
return winner;
}
public static void main(String [] args) throws Exception{
BufferedWriter writer = null;
File folder_location = new File("/Users/joaquindelaguardia/Desktop/Shakespeare");
File[] file_array = folder_location.listFiles();
for(File iteration_file: file_array) {
FileReader current_file = new FileReader(iteration_file);
BufferedReader infile = new BufferedReader(current_file);
Corpus obj1 = new Corpus(infile);
String file_name = iteration_file.getName();
String frequent_word = obj1.getMostFrequentWord();
String vocabulary_richness = String.valueOf(obj1.getVocabularyRichness());
System.out.println(file_name);
System.out.println(frequent_word);
System.out.println(vocabulary_richness);
System.out.println("-----------------------------");
//FileWriter file_writer = new FileWriter("/Users/joaquindelaguardia/Desktop/stats.csv");
//writer = new BufferedWriter(file_writer);
//String output = file_name+", "+frequent_word+", "+vocabulary_richness + "\n";
//writer.append(output);
}
//writer.close();
}
}
public class WordCounter {
private String word;
private int count=1;
WordCounter(String word){
this.word=word;
}
public String getName() {
return word;
}
public int getCount() {
return count;
}
public void addToCounter() {
count++;
}
}
Im testing the information by printing before appending to file, and as you can see with the small fragment of the output included below, for some cases it prints the most common word (and) while in the second case it doesn't print anything.
shakespeare-lovers-62.txt
and
2.2409948542024014
shakespeare-julius-26.txt
6.413205537806177
So I am creating a card game that requires different cards, so I created a card class in which I declared the string value names and other integer values that are the powers eg. Intelligence
public static class hero{
static String name;
static int strength;
static int intellect;
static int flight;
static int tech;
}
So I created an array of instances of these classes.
Their names are read from a text file and assigned to the name value.
Q1) I am having trouble with reading through the file and assigning the string to the name value of each instance of the class.
This is what I've done so far
public static void readLines(File f)throws IOException{
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
fr.close();
}
static File f = new File("C:/Users/jeff/Desktop/test/names.txt");
try{
readLines(f);
} catch (IOException e){
e.printStackTrace();
}
Q2)The part I am also having trouble with is the part where I need to create a loop to randomly assign values to each power of each instance of a class.
Here's what I've done so far
{
hero [] cards = new hero[cardNumber];
for(int i=4;i<cardNumber;i++){ cards[i]=new hero();}
Random rand = new Random();
for(int i=0; i<cards.length; ++i)
{
cards[i].strength = rand.nextInt(25) + 1;
cards[i].intellect = rand.nextInt(25) + 1;
cards[i].flight = rand.nextInt(25) + 1;
cards[i].tech = rand.nextInt(25) + 1;
}
But when I print out the values all the instances have the same value for their powers.
Eg Card 12 Intelligence = 6
And Card 14 Intelligence = 6
Can anyone please help me with these issues, and any guidance will be highly appreciated
Thank you
i have a piece of code thats makes a image search on flickr and returns the URL of the first image with that name. certain words i search on flickr doesn't have any matching images so because there are no images to get i get an ArrayOutOfBoundsException [0]. is there a way that i can make the program skip that particular words and keep on searching with next words?
this is my code so far:
PImage[] images;
int imageIndex;
XML xml;
String tag = "rutte";
String tag_mode = "all";
String words[];
void setup() {
size(50, 50);
String lines[] = loadStrings("text.txt");
words = split(lines[0], " ");
for (int k = 0; k<words.length; k++) {
String query = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=MY API KEY&tags="+ words[k] + "&sort=relevance&tag_mode="+ tag_mode +"format=rest";
xml = loadXML(query);
XML[] children = xml.getChildren("photos");
if(children.length > 0){
XML[] childPhoto = children[0].getChildren("photo");
for (int i = 0; i < 1; i++) {
String id = childPhoto[i].getString("id"); // this line generates the error :(
String title = childPhoto[i].getString("title");
String user = childPhoto[i].getString("owner");
String url = "https://www.flickr.com/photos/"+user+"/"+id;
println(url);
println("=====================");
}
}
}
textAlign(CENTER, CENTER);
smooth();
}
void draw() {
}
Just use the length field of your array. Something like this:
XML[] children = xml.getChildren("photos");
if(children.length > 0){
XML[] childPhoto = children[0].getChildren("photo");
if(childPhoto.length > 0){
String id = childPhoto[0].getString("id");
//rest of your code
}
You can find more info in the Processing reference.
In fact, you're already doing this with your words array!
so that later i can parse the array and if the line contains 3 doubles store it into an array of object type? ill later have to store the lines with 3 doubles into another array.
here's an example of my code so far
public static void readFile(){
Scanner scnr = null;
File info = new File("info.txt");
try {
scnr = new Scanner(info);
} catch (FileNotFoundException e) {
System.out.println("file not found");
e.printStackTrace();
}
int counterLines = 0;
String nextLine = "";
while(scnr.hasNextLine()){
nextLine = scnr.nextLine();
counterLines ++;
}
System.out.println(counterLines);
String[] infoArray = new String[counterLines];
for(int i = 0; i < counterLines; i++){
infoArray[i] = scnr.nextLine();
System.out.println(infoArray[i]);
You can probably spilt the text of the file into individual words using String.split() which gives you a String array.
This question already has answers here:
how to read all cell value using Apache POI?
(2 answers)
Closed 7 years ago.
I had created my script to validate my actual result and expected result , .
As there is too many link to validated script will get too much of coding m so i need to convert this into Data Driven Case ,.
Where Webdriver will get URL , xpath ,expected value from excel .
But dont know how to proceed , .
A demo code is much appreciated
Here is my current script :
public void test() throws Exception
{
String home_logo_url="158321";
String enough_talk_promo="1057406";
System.out.println("Check for home_logo_url");
driver.get(baseUrl);
String SiteWindow = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[#id='logo']/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String script = "return rlSerial;";
String value = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(value,home_logo_url);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
System.out.println("Check for enough_talk_promo");
driver.get(baseUrl + "/category/tournaments/");
driver.findElement(By.xpath("//*[#id='content']/div/div[4]/aside/div/div/p[1]/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String sr_enough_talk_promo = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(sr_enough_talk_promo,enough_talk_promo);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
}
How to iterated to each rows and get my test case run !!!
It is much helpful , if some one can convert my existing code to work on excel sheet .
Thanks
i was working on a project in Spring that read from an excel (.xls) and this was my code if can help
private List<String> extraire (String fileName) throws IOException {
List<String> liste = new ArrayList();
FileInputStream fis = new FileInputStream(new File(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator < Row > rowIterator = null;
rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
int i = 0;
row = (HSSFRow) rowIterator.next();
Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext()) {
Cell cell = cellIterator.next();
i++;
/**
* For verifying if a line is empty
*/
if (i % 29 == 0 || i == 1) {
while ( cellIterator.hasNext() && cell.getCellType() == Cell.CELL_TYPE_BLANK) {
cell = cellIterator.next();
}
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
String cellule = String.valueOf(cell.getNumericCellValue());
liste.add(cellule);
break;
case Cell.CELL_TYPE_STRING:
liste.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellule = " ";
liste.add(cellule);
break;
}
}
}
fis.close();
return liste;
}
in my controller :
List<String> liste = new ArrayList();
liste = extraire(modelnom);
for (int m=0, i=29;i<liste.size();i=i+29) {
if(i % 29 == 0) {
// i=i+29 : begin from the second line first coll
// m is line
m++;
}
String matricule = (String)liste.get(29*m).toString().trim();
float mat = Float.parseFloat(matricul); // From String to float
employe.setMatricule((int)mat); //reading mat as an int
// ... your Code
}