how to assign text in .txt file as a variable value? Java - java

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]));

Related

IndexOutOfBoundsException when trying to get String from ArrayList

So I'm trying to create a small hangman mini-game. Unfortunately, I keep receiving the same error. I've attempted to re-do the game twice, but still can't seem to get it right. I'm sure it is simply some logic error or something.
I'm still relatively new to Java, so any help would be appreciated.
I've split the program into three classes. One for the Hangman object, one for the array containing said objects, and one for using the array of those objects. The three parts below are a snippet from the game.
Class 1: Hangman
package hangman2;
import java.util.*;
import java.io.*;
public class Hangman {
private ArrayList<String> words = new ArrayList<>();
private int diff;
public Hangman(String fileName, int difficulty) {
diff = difficulty;
//easy = 0; medium = 1; hard = 2
try {
Scanner scanFile = new Scanner(new File(fileName));
while(scanFile.hasNext()) {
String line = scanFile.nextLine();
Scanner scanLine = new Scanner(line);
String tempWord = scanLine.next();
words.add(tempWord);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found\n" + e);
}
}
//Gets
public ArrayList<String> getWords() { return words; }
public int getDifficulty() { return diff; }
//Sets
public void addWord(String word) { words.add(word); }
}
Class 2: HangmanArray
package hangman2;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class HangmanArray {
private Hangman easyHangman;
private Hangman mediumHangman;
private Hangman hardHangman;
public HangmanArray() {
easyHangman = new Hangman("easy.txt", 0);
mediumHangman = new Hangman("medium.txt", 1);
hardHangman = new Hangman("hard.txt", 2);
}
public String getRandomWord() {
Hangman workingHangman = chooseDifficulty();
int max = workingHangman.getWords().size();
int randIndex = (int) (Math.random() * max);
return workingHangman.getWords().get(randIndex);
}
private Hangman chooseDifficulty() {
int chosenDifficulty = Integer.parseInt(JOptionPane.showInputDialog("Choose difficulty level\n"
+ "1: Novice\n2: Intermediate\n3: Expert"));
Hangman retHangman = null;
switch(chosenDifficulty) {
case 1: retHangman = easyHangman; break;
case 2: retHangman = mediumHangman; break;
case 3: retHangman = mediumHangman; break;
}
if (retHangman == null) {
System.out.println("Chosen difficulty not within range of [1;3]\nexiting");
System.exit(0);
}
return retHangman;
}
}
Class 3: HangmanUI
package hangman2;
public class HangmanUI {
public static void main(String[] args) {
HangmanArray hangmanArray = new HangmanArray();
System.out.println(hangmanArray.getRandomWord());
}
}
The error appears to be coming from line 25 of HangmanArray when difficulty 2 or 3 is selected:
return workingHangman.getWords().get(randIndex);
Any help is appreciated.
You should check whether max is 0 and, if so, return null or an empty string, then handle this special case.
I used Random.nextInt() instead of int randIndex = (int) (Math.random() * max);
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability
Keep in mind that the index of last element is size()-1
public String getRandomWord() {
Hangman workingHangman = chooseDifficulty();
int max = workingHangman.getWords().size();
if (max == 0) {
return "";
}
int randIndex = new Random().nextInt(max); // returns an integer between 0 and max-1
return workingHangman.getWords().get(randIndex);
}
You should also use try-with-resources to ensure that resources you're using are closed once you finisched with them.
public Hangman(String fileName, int difficulty) {
diff = difficulty;
//easy = 0; medium = 1; hard = 2
try (Scanner scanFile = new Scanner(new File(fileName))) {
while(scanFile.hasNext()) {
String line = scanFile.nextLine();
Scanner scanLine = new Scanner(line);
String tempWord = scanLine.next();
words.add(tempWord);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found\n" + e);
}
}
Lastly I suggest to use the debugger in order to know what you're putting into every Hangman.

reverse a stack and concatenate a popped stack

I'm trying to push any array list to a stack in reverse then concatenate a popped stacked. I getting the information from a file then storing it into an array List. Then i pushed the array List into a stack. now when i print the stack out its just printing the array List how can i pop the stack and concatenate it? here is my code so far
public static LinkedListStack myStack = new LinkedListStack();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
song.add(line = inFile.next());
}
for(int i = 0; i < song.size(); i++)
{
myStack.push1(song);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
if(!myStack.empty())
{
System.out.println(myStack.pop1());
} else
{
System.out.println("Sorry stack is empty");
}
}
output looks like this now :[Mary, had, a, little, lamb, Whose, fleece, was, white, as, snow, Everywhere, that, Mary, went, The, lamb, was, sure, to, go]
I'm trying to get it to look like this:
lamb little a had Mary
snow as white was fleece Whose
went Mary that Everywhere
go to sure was lamb The
i have made a custom class for the push and pop
{
private Node first;
/**
Constructs an empty stack.
*/
public LinkedListStack()
{
first = null;
}
/**
Adds an element to the top of the stack.
#param element the element to add
*/
public void push1(Object element)
{
Node newNode = new Node();
newNode.data = element;
newNode.next = first;
first = newNode;
}
/**
Removes the element from the top of the stack.
#return the removed element
*/
public Object pop1()
{
if (first == null) { throw new NoSuchElementException(); }
Object element = first.data;
first = first.next;
return element;
}
/**
Checks whether this stack is empty.
#return true if the stack is empty
*/
public boolean empty()
{
return first == null;
}
class Node
{
public Object data;
public Node next;
}
}
I fixed the problems in your code. Here is the working version along with some comments. This assumes the sentences in the file are separated by new lines and the words are separated by white spaces.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GeneralTest {
//You want the same ordering for sentences. This collection
//therefore should be a list (or a queue)
//I have not changed the name so you can see how it makes a
//difference
public static List<LinkedListStack> myStack = new ArrayList<>();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
//Here you need to use nextLine() instead of next()
song.add(inFile.nextLine());
}
//This loop is the main location your original code goes wrong
//You need to create a stack for each sentence and add it to the
//list. myStack will hold a list of stacks after this loop is done
for(int i = 0; i < song.size(); i++)
{
String songString = (String) song.get(i);
String[] sga = songString.split(" ");
LinkedListStack rowStack = new LinkedListStack();
for(int j=0; j < sga.length; j++) rowStack.push1(sga[j]);
myStack.add(rowStack);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
//To get all values in a collection you need to
//loop over it. A single if will not work
for(LinkedListStack rs : myStack)
{
//Each entry in the list is a LinkedListStack
//So you can pop them and print the results with
//appropriate separators
while(!rs.empty())
System.out.print(rs.pop1() + " ");
System.out.println();
}
}
}
Now, your code has many other problems. For example, you really should use generics when you create a collection class.
The main problem with your code is that to produce the output you have described, you will need a queue of stacks. I have implemented the concept using ArrayList to show the source of the problem. But if you want to learn data structures (or if this is a homework problem), then you should try implementing and using a queue as well.

Adding integers to arraylist "scores"

I have a text file with about 5000 names or so, each separated by line.
I am have already accomplished adding all the names to an ArrayList "names", but
i am not able to add anything to my arrayList scores.
I don't know where I'm going wrong, especially in the addScores method, nothing gets outputted at all.
If anymore information is required, please ask.
And thanks for the help..
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class ScoringNames {
BufferedReader x = null;
String location = "xxxxx\\names.txt";
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> scores = new ArrayList<Integer>();
public void readFile(){ //Opens file, and prints every line.
try{
x = new BufferedReader(new FileReader(location));
} catch(FileNotFoundException e) {
e.printStackTrace();
}
try{
String name = x.readLine();
while(name != null){
//System.out.println(name);
names.add(name);
name = x.readLine();
}
} catch(IOException e) {
e.printStackTrace();
}
}
public int nameScore(String name){
this.readFile(); //Open file and read, so that values are added to <names>
this.sortNames();
int score = 0;
char[] tempName = name.toCharArray();
for (char i : tempName){
score += alphValue(i);
}
return score;
}
public void addScores(){
for(String x : names){
scores.add(nameScore(x));
}
}
public void printScores(){
for(int counter: scores)
System.out.println(counter);
}
public static void main(String[] args) {
ScoringNames abc = new ScoringNames();
abc.readFile();
abc.addScores();
abc.printScores();
}
}
The error i get is:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at ScoringNames.addScores(ScoringNames.java:148)
at ScoringNames.main(ScoringNames.java:163)
You are modifying the List names while accessing it from the For loop of addScores() method.
When you call nameScore(String str) method, Then you don't need to read the file again as all data has been read already and stored in the names list. You need to do just evaluation of the String and return the score.
public int nameScore(String name){
int score = 0;
char[] tempName = name.toCharArray();
for (char i : tempName){
score += alphValue(i);
}
return score;
}
Change method nameScore - remove two top lines.
this.readFile(); // Open file and read, so that values are added to
// <names>
this.sortNames();
There are not unnecessary and the readFile() is the reason of the error.
The reason of the error is that you try to change this.names value in for each loop (for (String x : names)) and that is forbidden in Java.
public int nameScore(String name) {
int score = 0;
char[] tempName = name.toCharArray();
for (char i : tempName) {
score += alphValue(i);
}
return score;
}

Get next run from a text file

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");}
}

print out nth string using Queue

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++;
}
}
}

Categories