String in ArrayList Not Outputting - java

I have the following method which takes user input and applies an algorithm to it. However when I try to print the String process_name, stored in the fcfs ArrayList it comes out empty. But the burst_time and arrival_time fields in the same fcfs ArrayList get output to the console exactly as the user inputted the data. Not really sure what could be wrong.
public static void algorithm() {
ArrayList<Process> fcfs = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Process name,CPU Burst Time,Arrival time\n ");
while (!scan.next().equalsIgnoreCase("finish")) {
Process p = new Process();
String pn = "";
String bt = "";
String at = "";
pn = input.nextLine();
bt = input.nextLine();
at = input.nextLine();
System.out.println("Process name, CPU Burst Time, Arrival time\n ");
p.process_name = pn;
p.burstTime = Float.parseFloat(bt);
p.arrivalTime = Float.parseFloat(at);
fcfs.add(p);
}
{
Collections.sort(fcfs, new comp());
}
result(fcfs, fcfs.size(),false)
}
This is the Process class:
class Process {
String process_name;
float burstTime;
float arrivalTime;
float compTime = 0;
boolean status = false;
}

scan.next() function gets the next input string. That is why you get an empty line for process name because the name is already taken by the next function in the while condition. Either use hasNext() to check if there is a next line or get and put input to a string variable and compare it with the word 'finish'.
You can see the explanation in the documentation: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
Quoting from the documentation: "next : Finds and returns the next complete token from this scanner"

The problem is because of using next() instead of nextLine(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Replace
while (!scan.next().equalsIgnoreCase("finish"))
with
while (!scan.nextLine().equalsIgnoreCase("finish"))
Also, it's better to use do...while which guarantees to execute its body at least once i.e.
do {
Process p = new Process();
String pn = "";
String bt = "";
String at = "";
pn = input.nextLine();
bt = input.nextLine();
at = input.nextLine();
System.out.println("Process name, CPU Burst Time, Arrival time\n ");
p.process_name = pn;
p.burstTime = Float.parseFloat(bt);
p.arrivalTime = Float.parseFloat(at);
fcfs.add(p);
} while (!scan.nextLine().equalsIgnoreCase("finish"));

Related

How can I check if the character from a user- inputted string (first string) is present on the second string?

We have to write a program that inputs two String values. And this is the condition:
If the third character of the first string is present on the second string then do this code...
I tried using the .contains() method but there is an error. I also don't know how to apply loops because the output is being printed several times. What should I do?
The error says "The method contains (CharSequence) in the type String is not applicable for the arguments (char)"
System.out.println("Input String 1:");
Scanner sc1 = new Scanner(System.in);
String str1 = sc1.nextLine();
System.out.println("Input String 2:");
Scanner sc2 = new Scanner(System.in);
String str2 = sc2.nextLine();
char third = str1.charAt(2);
if (str2.contains(third)) {
str1 = str1.replaceAll("[AaEeIiOoUu]", "*");
str1.replaceAll("[AaEeIiOoUu]", "*");
System.out.println(str1.toUpperCase());
String first = "xyz";
String nthChar = Character.toString(first.charAt(2);
String second = "aaaaaaaz";
if(second.indexOf(nthChar) != -1){
// nth character from 'first' exists in 'second'
// do whatever
}

How do I read a position of a list of lines in text file

I am building a freight management system. I want to list out the intermediate ports available between the source and destination after the user has input the source port and destination port. But I don't know how to do that. I saved the port name and distance of each port in the text file where one line for each port. The location variable is used to calculate the distance between source and destination. I wanted to use the position variable to locate the ports in between the source and destination.
Newes;10;
Harrytown;25;
Truy;33;
East Port;47;
Athens;56;
Nasky;71;
private int location, location1, position, position1;
private String source, destination;
public void choosePort(){
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please enter the source.");
source = sc.nextLine();
System.out.println("Please enter the destination.");
destination = sc.nextLine();
try{
File f = new File("Port.txt");
Scanner file = new Scanner(f);
while(file.hasNextLine()){
String line = file.nextLine();
String[] split = line.split(";");
if(split[0].equals(source)){
location = Integer.parseInt(split[1]);
position = i;
}
else if(split[0].equals(destination)){
location1 = Integer.parseInt(split[1]);
position1 = i;
}
i++;
}
file.close();
}
catch(IOException e){
System.out.println(e);
}
If I understand your question correctly, you want ports displayed between source and destination. For example, if a user selects 'Newes" as a starting point and 'Trury' as a destination, you would like 'Harrytown' displayed as an intermediate. There are several ways you can do this. The easiest way, I believe is to use a second scanner to scan word for word, a delimiter, and a print statement inside that while loop.
while(file.hasNextLine())
{
String line = file.nextLine();
Scanner sff = new Scanner(line);
sff.useDelimiter(";"); // scanner will see ';' and skip over it
String temp1 = sff.next;
if ( source.equals(temp1))
{
System.out.println(file.nextLine());
}
After this, just complete out the code. write another file.nextLine() to see if it matches destination, if it does not, print out the line. When sff matches the destination, print out that final line then insert a break statement.
something quick like.
boolean isPrint = false;
while(file.hasNextLine()){
String line = file.nextLine();
String[] split = line.split(";");
if(split[0].equals(destination)){
isPrint = false;
}
if (isPrint) { System.out.println(split[1]);}
if(split[0].equals(source)){
print = true;
}
}

Java, File Reader, going into infinite loop

I wrote a program to read a file. It reads the file correctly. I tested using print statements. But after reading the last line in the file, the program doesn't stop. It goes into an infinite loop. I am guessing that my while loop keeps reading blank characters as the next line. I don't know how to fix it.
If I put a break in the else part, it just reads the first line and breaks out of the while loop. I am not sure why.
Please help me out.
Here is the code :
public static void InterpretMessageFromFile() throws FileNotFoundException{
File inputfile = new File("FilePath");
Scanner reader = new Scanner(inputfile);
try
{
while (reader.hasNextLine())
{
//if the type of order is add order to existing Order Book
if (reader.hasNext("A")){
reader.next();
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts);
//int ts = Integer.parseInt(retrieve_ts, 2); //for binary file
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id);
//int id = Integer.parseInt(retrieve_id ,2); // for binary file
String or_side = reader.next();
String retrieve_share = reader.next();
int share = Integer.parseInt(retrieve_share);
// int share = Integer.parseInt(retrieve_share, 2); //for binary file
String retrieve_price = reader.next();
int price = Integer.parseInt(retrieve_price);
//int price = Integer.parseInt(retrieve_price, 2); //for binary file
System.out.println("Add Order : Id is " + id );
AddOrderToExistingBook.AddNewOrder(id, ts, or_side, share, price);
}
//if it is cancel order
else if (reader.hasNext("X")){
reader.next();
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts);
//int ts = Integer.parseInt(retrieve_ts, 2); //for binary file
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id);
System.out.println("Cancel Order : Id is " + id + " time stamp is : " + ts );
//int id = Integer.parseInt(retrieve_id, 2); //for binary file
//String retrieve_share = reader.next();
// int share = Integer.parseInt(retrieve_share, 2); // need to add back later, removing it for testing purposes
CancelOrder.CancelPartOfOrder(id, ts);
}
//if it is delete order
else if (reader.hasNext("D")){
reader.next();
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts, 2);
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id, 2);
DeleteOrder.DeleteOrderFromBook(id, ts);
}
else{
// unexpected token.
// basically log as info and ignore.
}
}
}
finally
{
reader.close();
}
}
When handling file reading operations, it is always good to check couple of conditions -
1) Does the file has next line? 2) Is the next line not null.
while (reader.hasNextLine() && (line = reader.nextLine()) != null)
And then you can use this String line in your code.
In you code, although you are getting the next value by reader.next(), It does not advance the pointer. That is the reason the loop never exits.
Ref: Scanner
The last else block does not actually consume the line. Therefore if you've got any characters after the last line of real data in your input the program will always have a next line. Try consuming the file one line at a time and then using String.split() to get the individual tokens in each line. This guarantees that you will consume every line in the file.

java.util.NoSuchElementException error, looked for possible reasons, still can't fix it

I am getting java.util.NoSuchElementException error. We get this error for the following reasons.
If we don't check if the file has next line before reading it,
then it throws exception after reading last line since it is trying
to read a line which doesn't exist.
Format of the file is messed up
I think that the format of the file I m using is correct and I am also checking for next line before reading it but I am still getting the error.
When I debug it using print statement, it prints all the line and throws java.util.NoSuchElementException error after reading last line.
Please help me out
Here is the code :
public static void InterpretMessageFromFile() throws FileNotFoundException{
File inputfile = new File("filepath");
Scanner reader = new Scanner(inputfile);
try {
while (reader.hasNextLine()) {
String MessageType = reader.next();
int IsAdd = MessageType.compareToIgnoreCase("A");
int IsCancel = MessageType.compareToIgnoreCase("X");
int IsDelete = MessageType.compareToIgnoreCase("D");
int IsExecute = MessageType.compareToIgnoreCase("E");
int IsReplace = MessageType.compareToIgnoreCase("U");
//if the type of order is add order to existing Order Book
if (IsAdd == 0) {
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts);
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id);
String or_side = reader.next();
String retrieve_share = reader.next();
int share = Integer.parseInt(retrieve_share);
String retrieve_price = reader.next();
int price = Integer.parseInt(retrieve_price);
System.out.println("Add Order : Id is " + id );
AddOrderToExistingBook.AddNewOrder(id, ts, or_side, share, price);
}
//if it is cancel order
if (IsCancel == 0){
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts);
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id);
System.out.println("Cancel Order : Id is " + id + " time stamp is : " + ts );
CancelOrder.CancelPartOfOrder(id, ts);
}
}
}
}
finally {
reader.close();
}
}
Exception (copied from comments):
Exception in thread "main" java.util.NoSuchElementException at
java.util.Scanner.throwFor(Scanner.java:907) at
java.util.Scanner.next(Scanner.java:1416) at
OrderBook.InterpretOrderBookUpdateMessage.InterpretMessageFromFile(InterpretOrde‌​rBookUpdateMessage.java:20)
at OrderBook.MainMethod.main(MainMethod.java:50)
you are trying to consume a token that is not there.
you do a number of next() calls without checking if there is next.
in your case, I suspect a newline at the end of your file gives you an empty line as input.
the scanner will see a new line, but as it doesn't contain tokens, calling "next()" will cause an error.
the same would happen if you have empty lines between blocks in your file.
one thing you can use is:
public boolean hasNext(String pattern)
instead of
next()
this will let you do a lookahead without consuming a token.
so instead of:
String MessageType = reader.next();
int IsAdd = MessageType.compareToIgnoreCase("A");
int IsCancel = MessageType.compareToIgnoreCase("X");
// .... left out other classes
//if the type of order is add order to existing Order Book
if (IsAdd == 0){
// .. do stuff
}
you can do something like:
if (reader.hasNext("A") {
reader.next(); // consume A
int ts = reader.nextInt(); // get id
// ... etcetera
} else if (reader.hasNext("X") {
}
I would also recommend you use nextInt() instead of nextString and then calling parseInt
One other thing: you can even make your code better to read by doing:
if (reader.hasNext("A") {
handleAddition(reader);
}
and then later on define a method that only handles this case.
your main method will look like:
try
{
while (reader.hasNextLine())
{
if (reader.hasNext("A")) {
handleAdd(reader);
} else if (reader.hasNext("X")) {
handleCancel(reader);
} else if (reader.hasNext("D")) {
handleDelete(reader);
} else if (reader.hasNext("E")) {
handleExecute(reader);
} else if (reader.hasNext("R")) {
handleReplace(reader);
} else {
// unexpected token. pretty sure this is the case that triggers your exeception.
// basically log as info and ignore.
reader.nextLine();
}
}
}
finally
{
reader.close();
}
Now your method is nice and short, and all the specific actions are taken in methods with their own name.
the only thing I'm not 100% about if it it's good practice to consume A, X, R, etc... inside the main loop, or the actual handler method. I prefer to consume inside the method personally.
hope it helps.

Is a scan line escaping?

I've been doing a small project for class, it runs perfectly without problems but when pitted against the class's auto testers it gives back 2 No line found errors. Asking the course's staff they say it's probably because I'm trying to scan a line when none exist, but I tried printing all my scans and didn't discover anything like that.
That's all the scans I have in my code:
Scanner sc = new Scanner(System.in);
String sentence;
int choice;
System.out.println("Please enter a sentence:");
sentence = sc.nextLine();
printMenu(); // calls a function to print the menu.
// gets the require action
System.out.println("Choose option to execute:");
choice = sc.nextInt();
sc.nextLine();
(I tried with and without the last sc.nextLine)
static void replaceStr(String str)
{
String oldWord, newWord;
Scanner in = new Scanner(System.in);
// get the strings
System.out.println("String to replace: ");
oldWord = in.nextLine();
System.out.println("New String: ");
newWord = in.nextLine();
// replace
str = str.replace(oldWord, newWord);
System.out.println("The result is: " + str);
in.close();
}
static void removeNextChars(String str)
{
Scanner in = new Scanner(System.in);
String remStr; // to store the string to replace
String tmpStr = ""; //the string we are going to change.
int i; // to store the location of indexStr
// gets the index
System.out.println("Enter a string: ");
remStr = in.nextLine();
i=str.indexOf(remStr);
in.close(); // bye bye
if (i < 0)
{
System.out.println("The result is: "+str);
return;
}
// Build the new string without the unwanted chars.
/* code that builds new string */
str = tmpStr;
System.out.println("The result is: "+str);
}
Any idea how a line can leak here?
Here is the problem. You are using in.close(); at multiple places(last statement in replaceStr method and around the middle in removeNextChars method). When you close the scnaner using close() method, it closes your InputStream (System.in) as well. That InputStream can't be reopened with-in your program.
public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**
Any read attempts after the scanner close will result into exception NoSuchElementException.
Please close your scanner only once, when your program is done.
EDIT: Scanner Closing/usage:
In yout main function:
Scanner sc = new Scanner(System.in);
....
.....
replaceStr(Scanner sc, String str);
.....
....
removeNextChars(Scanner sc ,String str);
....
....
//In the end
sc.close();
static void replaceStr(Scanner in, String str){
//All the code without scanner instantiation and closing
...
}
static void removeNextChars(Scanner in, String str){
//All the code without scanner instantiation and closing
...
}
You should be all good.

Categories