I want to print out the nth string using the
Queue data type.
Ex.
$ java NthString 5
a b c d e f
< ctrl -d >
should give me:
b (the fifth string from the right)
This is what I have so far, but I do not know my next step:
public class NthString {
public static void main(String[] args) {
Queue<Integer> q = new Queue<Integer>();
while(!StdIn.isEmpty()){
q.enqueue(StdIn.readInt());
}
}
}
Thanks
public class NthString {
public static void main(String[] args) {
Integer n = Integer.parseInt(args[0]);
Queue<Integer> q = new Queue<Integer>();
while(!StdIn.isEmpty()){
q.enqueue(StdIn.readInt());
}
while(q.size() > n){
q.dequeue();
}
StdOut.println(q.peek().toString());
}
}
First of all you should know how these stuff work, so read my comments carefully. I have written a sample for you but it is not exactly what you need but with small changes you can reach the requirement.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class NthString {
public static void main(String[] args) {
// java NthString 5
// when you run this command 5 will come from args as first parameter
int nth = Integer.parseInt(args[0]);
// Since we get alfabetic from console input your queue must be type of String
Queue<String> q = new LinkedList<>();
// This is in place of your StdIn
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
try {
String s = "";
// '/' this is the exit String that is expected from user to give at last to stop reading furthermore
// in your case it is different, ctrl -d ?
while (!"/".equals((s = bufferRead.readLine()))) {
q.add(s);
}
} catch (IOException e) {
e.printStackTrace();
}
String polled = "";
int count = 1;
// now you have to poll from queue back and count to get the nth string
// since the queue is implemented as linkedlist in my case 5th element will output e instead of b
while ((polled = q.poll()) != null) {
if (count == nth) {
System.out.println(nth + " th string is " + polled);
}
count++;
}
}
}
Related
I am trying to write a function in Java that returns the next ascending sequence (run) from a txt file, let's say the return type of a function would be ArrayList.
My example file input.txt contains next values: 78123421. So in terms of runs that means the file has 4 runs: |78|1234|2|1|.
What am I trying to reach here is like when I would call this function from main() four times it should print something like
1.run: 78,
2.run: 1234,
3.run: 2,
4.run: 1
or just two calls should print
1.run: 78,
2.run: 1234
I have tryed to solve my problem using BufferedReader/FileReader and RandomAccessFile but no working solution so far, please help :/
So this is what I have so far. The main idea was to use RandomAccessFile and read from input as long as run condition is satisfied. But the reader reads one value more, that is why I use seek() to start reading at the right position when next function call happens. There must be a bug in the code, because it doesn't print all the runs or just an Exception fires.
import java.io.File;
import java.util.ArrayList;
import java.io.RandomAccessFile;
public class GetRunsFromFile
{
static long start = 0;
static long read_len = 0;
public static void main(String[] args) throws Exception
{
File in = new File("C:/Users/henrich/Desktop/Gimp.txt");
RandomAccessFile raf = new RandomAccessFile(in,"r");
ArrayList<Integer> current_run = new ArrayList<Integer>();
for(int i=1;i<=4;i++)
{
current_run = getNextRun(raf);
printArrayList(current_run);
}
raf.close();
}
private static ArrayList<Integer> getNextRun(RandomAccessFile raf) throws Exception
{
int v;
String line;
int val = Integer.MIN_VALUE;
ArrayList<Integer> run = new ArrayList<Integer>();
while((line=raf.readLine())!= null)
{
v = Integer.parseInt(line.trim());
if(v >= val)
{
read_len = raf.getFilePointer() - start;
start = raf.getFilePointer();
run.add(v);
val = v;
}
else
{
raf.seek(raf.getFilePointer() - read_len);
start = raf.getFilePointer();
return run;
}
}
return null;
}
private static void printArrayList(ArrayList<Integer> al)
{
for(int i=0; i<al.size(); i++)
{
System.out.print(al.get(i) + " ");
}
System.out.println();
System.out.println("------");
}
}
For more questions please let me know.
Note: It should work only for ascending runs and files of any length.
Thanks for the support.
There are several ways to do it.
solution 1
For instance call your function with an int and make it return an int refering to the number of the last printed char.
Run Exaple:
after the first run return 2 cause the length of print text is 2
after the second run return 6 cause the length of print text is 4 +2 from last loop... etc.
public int function(int startPoint){
// do stuff here
return lastIndexofPrintChar;
}
then call your function like this
loop{
int result=0;
result= function(x);
}
solution 2
You can also dublicate your file and remove every String you print.
private static void getNextRun()
{
try
{
BufferedReader br = new BufferedReader(new FileReader(new File("C:/Users/henrich/Desktop/Gimp.txt")));
br.skip(skip_lines);
int v;
String line;
int val = Integer.MIN_VALUE;
ArrayList<Integer> al = new ArrayList<Integer>();
while((line=br.readLine())!= null)
{
skip_lines += line.length()+2;
v = Integer.parseInt(line.trim());
if(v >= val)
{
al.add(v);
val = v;
}
else
{
skip_lines -= line.length() + 2;
printArrayList(al);
break;
}
}
br.close();
}
catch (Exception e){System.out.println("EOF");}
}
I wrote this code which takes a .txt file and scans it. Each line represents a separate process with its attributes. I need to be able to loop through each line of the .txt file and assign the different values to the process's fields.
Here's my process class:
public class Process {
private String name;
private int arrive_time= 0;
private int burst_time = 0;
private int remain_time = 0;
public Process (String name, int arr_time, int bur_time) {
this.arrive_time = arr_time;
this.burst_time = bur_time;
this.remain_time = burst_time;
this.name = name;
}
public int getArrTime() {return arrive_time;}
public int getBurTime() {return burst_time;}
public int getRemTime() {return remain_time;}
public String getName() {return name;}
public void decRemTime() {this.remain_time--;}
}
Here's my .txt file:
P1 0 8
P2 1 4
P3 2 9
P4 3 3
END 4 9999
p1 is supposed to be assigned to the name variable of the first process. 0 is the arrival time. and 8 is the burst time. Then we move onto the next line and do the same for a new process that we will be creating every time I move to a new line in the .txt
Here's my code for assigning things:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Test {
public static void main(String[] args) {
//Priority queue for storing the initialized processes
PriorityQueue<Process> prq = new PriorityQueue<Process>(5, new Comparator<Process> () {
#Override
public int compare(Process p1, Process p2) {
return p1.getArrTime() - p2.getArrTime();
}
});
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("C:\\Users\\Veni\\Desktop\\test\\test.txt\\"));
}
catch (FileNotFoundException fnfex) {
System.out.println(fnfex.getMessage() + "File not found");
System.exit(0);
}
try {
int localProcessIndex = 0;
/* Count number of lines in .txt and store number in localProcessIndex.
* Then declare exactly that many processes.
*
* Then move to the loop below and start reading each line's values
* and start initialising the processes with those values.
*
* Then move all the processes to the prq priority queue.
*/
while((line = br.readLine()) != null) {
//Process localProcessIndex = new Process(line.split);
//System.out.println(line);
}
}
catch(IOException ioex) {
System.out.println(ioex.getMessage() + "Error reading");
}
SPN spn = new SPN(prq);
spn.SPN_ALG();
}
}
Assuming that your file will always have that same structure, you could use the split(String regex) method to process your data:
while((line = br.readLine()) != null) {
try {
String[] params = line.split(" ");
prq.add(new Process(params[0], Integer.parseInt(params[1]), Integer.parseInt(params[2]))),
...
}
catch(Exception e) {
//Log
}
}
EDIT: What you need to do is to have a list of Process items. This will allow you to create the amount of processes you need and make them available at a later stage. I have modified the code above to provide this functionality.
For each line, split it by a space. Next use parseInt to get the numbers. Finally call the constructor with these values:
String line = "P1 0 8";
String params = line.split("\s");
Process process = new Process(params[0], Integer.parseInt(params[1]), Integer.parseInt(params[2]));
So I have an object which I import in another object
First object:
package test;
import java.util.*;
public class Eveniment {
int ziua;
String luna = new String();
public void setZiua(int param){
ziua = param;
}
public void setLuna(String param){
luna = param;
}
public int getZiua(){
return ziua;
}
public String getLuna(){
return luna;
}
}
Second object:
package test;
import test.*;
import java.util.*;
public class EventPlanner {
public static void main(String[] args){
ArrayList<Eveniment> myAr = new ArrayList();
Scanner sc = new Scanner(System.in);
System.out.println("Introduceti ziua urmata de luna evenimentului: ");
int zi = 0;
String luna;
zi = sc.nextInt();
luna = sc.nextLine();
Eveniment first = new Eveniment();
first.setZiua(zi);
first.setLuna(luna);
myAr.add(first);
while(luna!=null && zi!=0)
{
zi = sc.nextInt();
luna = sc.nextLine();
if(zi!=0)
{
Eveniment ev = new Eveniment();
ev.setZiua(zi);
ev.setLuna(luna);
myAr.add(ev);
}
}
String l = new String();
l = "Ianuarie";
System.out.println(myAr.size());*/
for(int i = 0; i < myAr.size(); i++){
if(myAr.get(i).getLuna().equals(l))
System.out.println(1);
else
System.out.println(0);
}
}
public static void afisare(ArrayList<Eveniment> myAr){
System.out.println("---------Array------------");
for(Eveniment i : myAr){
System.out.println(i.getLuna() +" "+i.getZiua());
}
}
}
The thing that bugs me is that inside the for I do a check if a current object has it's luna string equal to l string then I print out 1 else I print 0, but the algorithm prints out 0 even if the strings are equal, what am I doing wrong ?
I'm a newbie with Java so please don't judge too harshly.
Input given to the program:
1 Decembrie
2 Ianuarie
3 Februarie
4 Martie
0//to end the input
The program should write
`Decembrie` 0
`Ianuarie` 1
`Februarie` 0
`Martie` 0
because l is equal to Ianuarie.
this is because
l = "Ianuarie"
and
myAr.get(i).getLuna() =" Ianuarie"
^--->there are space before the Ianuarie
so you will never get 1
I'm not sure why this isn't working. I'm not sure if it's a problem with the printing, or if it's a problem with the methods themselves.
I am making a program that takes a collection of songs and filters or sorts it according to a given user input. The user should be able to input multiple commands to further narrow down the list.
My filterRank and filterYear methods work perfectly fine, but the other methods end up printing a seemingly random selection of songs that do not change regardless of what is inputted as the title or artist to be filtered by, which generally appears only after an extremely long waiting period and a long series of spaces.
Even after this amalgam of songs is printed, the program does not terminate, and periodically outputs a space in the console, as in a System.out.println() statement were being continuously run.
If I remove the code that configures the output file, which is a requirement for the project, the methods fail to print entirely. Regardless of either of these changes, filterRank and filterYear continue to work perfectly.
This problem also occurs with my sort methods. No matter what sort method I run, it still prints out the spaces and the random songs, or nothing at all.
Is there something I'm missing? I've tried printing out variables and strategically inserting System.out.println("test") in my program to determine what the program is, but it seems as though it's parsing the input correctly, and the methods are indeed being successfully run.
I've been otherwise unable to isolate the problem.
Can I get assistance in determining what I'm missing? Despite poring over my code for two hours, I just can't figure out what the logical error on my part is.
Here is the relevant code:
The main class:
public static void main(String[] args) throws FileNotFoundException, IOException{
//user greeting statements and instructions
//scanning file, ArrayList declaration
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
int n = 0;
SongCollection collection = new SongCollection(songs);
String inputType = input.nextLine();
String delims = "[ ]";
String[] tokens = inputType.split(delims);
for (int i = 0; i < tokens.length; i++) {
n = 0;
if (n == 0) {
if ((tokens[i]).contains("year:")) {
collection.filterYear(Range.parse(tokens[i]));
n = 1;
}// end of year loop
if ((tokens[i]).contains("rank:")) {
collection.filterRank(Range.parse(tokens[i]));
n = 1;
}// end of rank
if ((tokens[i]).contains("artist:")) {
collection.filterArtist(tokens[i]);
n = 1;
}// end of artist
if ((tokens[i]).contains("title:")) {
collection.filterTitle(tokens[i]);
n = 1;
}// end of title
if ((tokens[i]).contains("sort:")) {
if ((tokens[i]).contains("title")) {
collection.sortTitle();
n = 1;
}// end of sort title
if ((tokens[i]).contains("artist")) {
collection.sortArtist();
n = 1;
}// end of sort artist
if ((tokens[i]).contains("rank")) {
collection.sortRank();
n = 1;
}// end of sort rank
if ((tokens[i]).contains("year")) {
collection.sortYear();
n = 1;
}// end of sort year
}//end of sort
}// end of for loop
}// end of input.hasNextline loop
/*final PrintStream console = System.out; //saves original System.out
File outputFile = new File("output.txt"); //output file
PrintStream out = new PrintStream(new FileOutputStream(outputFile)); //new FileOutputStream
System.setOut(out); //changes where data will be printed
*/ System.out.println(collection.toString());
/*System.setOut(console); //changes output to print back to console
Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file
while ((outputFileScanner.hasNextLine())) { //while the file still has data
System.out.println(outputFileScanner.nextLine()); //print
}
outputFileScanner.close();
out.close();*/
}
}// end of main
}// end of class
The SongCollection Class, with all of its respective filter and sort methods:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class SongCollection {
ArrayList<Song> songs2;
ArrayList<Song> itemsToRemove = new ArrayList<Song>(); // second collection
// for items to
// remove
public SongCollection(ArrayList<Song> songs) { // constructor for SongCollection
System.out.println("Test");
this.songs2 = songs;
}
public void filterYear(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.year > (r.getMax()) || (song1.year) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void filterRank(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void filterArtist(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.artist).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void filterTitle(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.title).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void sortTitle() {
Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
}
public void sortRank() {
Collections.sort(songs2, SongComparator.byRank()); // now we have a sorted list
}
public void sortArtist() {
Collections.sort(songs2, SongComparator.byArtist()); // now we have a sorted list
}
public void sortYear() {
Collections.sort(songs2, SongComparator.byYear()); // now we have a sorted list
}
public String toString() {
String result = "";
for (int i = 0; i < songs2.size(); i++) {
result += " " + songs2.get(i);
}
return result;
}
}
SongComparator Class:
import java.util.Comparator;
public class SongComparator implements Comparator<Song> {
public enum Order{
YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
}
private Order sortingBy;
public SongComparator(Order sortingBy){
this.sortingBy = sortingBy;
}
public static SongComparator byTitle() {
return new SongComparator(SongComparator.Order.TITLE_SORT);
}
public static SongComparator byYear() {
return new SongComparator(SongComparator.Order.YEAR_SORT);
}
public static SongComparator byArtist() {
return new SongComparator(SongComparator.Order.ARTIST_SORT);
}
public static SongComparator byRank() {
return new SongComparator(SongComparator.Order.RANK_SORT);
}
#Override
public int compare(Song song1, Song song2) {
switch (sortingBy) {
case YEAR_SORT:
System.out.println("test");
return Integer.compare(song1.year, song2.year);
case RANK_SORT:
System.out.println("test");
return Integer.compare(song1.rank, song2.rank);
case ARTIST_SORT:
System.out.println("test");
return song1.artist.compareTo(song2.artist);
case TITLE_SORT:
System.out.println("test");
return song1.title.compareTo(song2.title);
}
throw new RuntimeException(
"Practically unreachable code, can't be thrown");
}
}
After you output the filtered collection, your program doesn't terminate because you are still in a while loop looking for the next user input line. This is basically what your program is doing:
while (input.hasNextLine()) {
// stuff happens here
System.out.println(collection.toString());
/*
* System.setOut(console); //changes output to print back to console Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file while ((outputFileScanner.hasNextLine()))
* { //while the file still has data System.out.println(outputFileScanner.nextLine()); //print } outputFileScanner.close(); out.close();
*/
}
I am trying to work out how to scan a text file of a conversation find how many positive words and negative words there are. The positive and negative words are contained within two separate text files which are used to 'scan' the conversation text file.
After it finds the number of positive and negative words I am trying to get it to tally each up and then tell me if there are more positive or negative words found.
I have the code below so far, it only gives me a count on the positive words. I am not looking at something like NLP at this stage just something on a much more basic level.
I think I have the second part looking for the negative words in the wrong location. And I think I need to use a boolean to tell me if there are more positive or negative words found, but I can't work out how to do it.
I am pretty stuck as I am new to Java, and programing in general.
Any help would be greatly appreciated.
package omgilisearch;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class SentimentTest {
public static void main(String[] args) throws Exception {
printAllCounts(
readWordFile("ConversationTest.txt", loadKeywords("PositiveWords.txt")));
}
public static void main1(String[] args) throws Exception {
printAllCounts(
readWordFile("ConversationTest.txt", loadKeywords("NegativeWords.txt")));
}
private static Map<String, Integer> readWordFile(
String fname, Set<String> keywords) throws FileNotFoundException
{
final Map<String, Integer> frequencyData = new TreeMap<String, Integer>();
for (Scanner wordFile = new Scanner(new FileReader(fname));
wordFile.hasNext();)
{
final String word = wordFile.next();
if (keywords.contains(word))
frequencyData.put(word, getCount(word, frequencyData) + 1);
}
return frequencyData;
}
private static void printAllCounts(Map<String, Integer> frequencyData) {
System.out.println("-----------------------------------------------");
System.out.println(" Occurrences Word");
for(Map.Entry<String, Integer> e : frequencyData.entrySet())
System.out.printf("%15d %s\n", e.getValue(), e.getKey());
System.out.println("-----------------------------------------------");
}
private static int getCount(String word, Map<String, Integer> frequencyData) {
return frequencyData.containsKey(word)? frequencyData.get(word) : 0;
}
private static Set<String> loadKeywords(String fname)
throws FileNotFoundException
{
final Set<String> result = new HashSet<String>();
for (Scanner s = new Scanner(new FileReader(fname)); s.hasNext();)
result.add(s.next());
return result;
}
}
You would have to have some array of so called "bad" words (wich are hard coded) and then iterate through the whole text file and compare every word in the array with the word you currently inspecting. If the word matches with one of the words in the array, then increase some variable that is holding the amount of badwords eg. badWords++;. I believe this approach should work.
package omgilisearch;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class SentimentTest {
public static void main(String[] args) throws Exception {
printAllCounts(
readWordFile("ConversationTest.txt"));
}
private static Map<String, Integer> readWordFile(String string) {
return null;
}
String[] goodWordsHolder = new String[3];{
goodWordsHolder[0] = "good"; goodWordsHolder[1] = "great";goodWordsHolder[2] = "excellent";
for(int iteration = 0; iteration < goodWordsHolder.length; iteration++) { String currentWordInText;
if(goodWordsHolder[iteration] == currentWordInText) { }// The word is a bad word } }
private static void printAllCounts(Map<String, Integer> frequencyData) {
System.out.println("-----------------------------------------------");
System.out.println(" Occurrences Word");
for(Map.Entry<String, Integer> e : frequencyData.entrySet())
System.out.printf("%15d %s\n", e.getValue(), e.getKey());
System.out.println("-----------------------------------------------");
}
}
package omgilisearch;
import java.io.*;
public class SentimentTest {
public static void main(String[] args) {
String[] lines = new String[0];
String path = "ConversationTest.txt";
BufferedReader br = null;
try {
File file = new File(path);
br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String line;
while( (line = br.readLine()) != null ) {
lines = add(line, lines);
}
br.close();
} catch(IOException e) {
System.out.println("read error: " + e.getMessage());
}
print(lines);
}
private static String[] add(String s, String[] array) {
String[] goodWordsHolder = new String[3];{
}goodWordsHolder[0] = "good"; goodWordsHolder[1] = "great";goodWordsHolder[2] = "excellent";
for(int iteration = 0; iteration < goodWordsHolder.length; iteration++) { String currentWordInText = null; if(goodWordsHolder[iteration] == currentWordInText) { }}
return goodWordsHolder; }
private static void print(String[] data) {
for(int i = 0; i < data.length; i++)
System.out.println(data[i]);
}
}
Arrays store multiple items of the same information type eg. String[] badWords;. I believe you should use this, since I'm sure you will have more than 1 bad word that you would like to find in the conversation text, if not, then simple use 1 String eg. String badWord;.
I'm not going to write out all the code that will make it work, I'll just give you an algorithm.
public class test {
// The process of picking out all the good and bad words
public static void main(String[] args) {
// Setting up all the needed variables
// Set up all the good words
String[] goodWordsHolder = new String[2];
goodWordsHolder[0] = "firstGoodWord";
goodWordsHolder[1] = "secondGoodWord";
// Set up all the bad words
String[] badWordsHolder = new String[2];
badWordsHolder[0] = "firstBadWord";
badWordsHolder[1] = "secondBadWord";
// Set up the counters
int amountOfGoodWords = 0;
int amountOfBadWords = 0;
int currentWordInText = 0;
// boolean that will exit the loop
boolean ConversationEnded = false;
while(!ConversationEnded) {
// Compare the currentWord from the conversation with the hard coded words
for(int iteration = 0; iteration < goodWordsHolder.length; iteration++) {
if(goodWordsHolder[iteration] == getWordInText(currentWordInText)) {
amountOfGoodWords++;
}
}
for(int iteration = 0; iteration < badWordsHolder.length; iteration++) {
if(badWordsHolder[iteration] == getWordInText(currentWordInText)) {
amountOfBadWords++;
}
}
// Increase the current word value so the next time we compare the next word in the conversation will be compared
currentWordInText++;
// Check that we haven't reached the end of the conversation
if(endOfTheConversationHasBeenReached()) {
// This will exit the while loop
ConversationEnded = true;
}
}
// Now print all the information to the console
System.out.println("Amount of good Words: " + amountOfGoodWords);
System.out.println("Amount of bad Words: " + amountOfBadWords);
if(amountOfGoodWords > amountOfBadWords) {
System.out.println("There are more good words than bad words.");
}
else {
System.out.println("There are more bad words than good words.");
}
}
// The method(s) you'll have to code out yourself. I suggest you read up on the web and so on to assist you with this.
private static String getWordInText(int currentWordInText) {
// TODO Auto-generated method stub
return null;
}
private static boolean endOfTheConversationHasBeenReached() {
// TODO Auto-generated method stub
return false;
}
}
Excuse me if there are any logical errors. The code hasn't been debugged yet. ;) Hopefully this will guide you into the right direction.