I have been trying to get my try/catch set up to work but it doesn't seem to run either the try section or the catch section and just returns the default value of the variable.
I had it working before and cant remember what it was that i changed because I haven't touched it for a while
i can include the data file if requested
Any ideas?
package firsttry;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class csv{
public double speed(int tool , int block){
double blockbreak = 0;
//Define file variable thing
//runs through file
try {
String filename = "data.csv";
File file = new File(filename);
Scanner inputStream = new Scanner(file);
//runs through each line as long as there is something next
while (inputStream.hasNext()){
String data = inputStream.next();//gets a whole line
String[] values = data.split(",");
if (values[1].equals(block)){
blockbreak = Double.parseDouble(values[tool + 2]);
System.out.println(blockbreak);
blockbreak = 4;
}
}
}catch (Exception e) {
System.out.println("ERROR");
blockbreak = 4;
}
return blockbreak;
}
public String name(int block){
String filename = "data.csv";
File file = new File(filename);
//runs through file
try {
Scanner inputStream = new Scanner(file);
//runs through each line as long as there is something next
while (inputStream.hasNext()){
String data = inputStream.next();//gets a whole line
String[] values = data.split(",");
if (values[1].equals(block)){
//int speed = Integer.parseInt(values[tool]);
String blockname = values[0];
return blockname;
}
}
} catch (FileNotFoundException e) {
}
return filename;
}
}
Don't have enough reputation to comment, so writing here.
You should modify your if condition in each function() written above,
if (values[1].equals(block)){
}
It will not give you an output you are expecting.
Comparing string with int is incorrect, for example
System.out.println("1".equals(1)); -> will print false
You are observing that the default value is being returned.
Does this mean that your function returns 0? (As initialized here? double blockbreak = 0;)
If that is the case, you should look into what happens in your loop.
This if statement looks dodgy.
if (values[1].equals(block))
What do you expect to happen?
Also, please post a line that matches the if statement and a line that doesn't, and the expected output from the function.
Possible reasons why you only get the default value:
data.csv is an empty file.
values[1].equals(block) returns false. (Which will always be the case since you're comparing a String to an int.)
catch (FileNotFoundException e) doesn't do anything, so you wouldn't know if the file was not found.
To elaborate on point 2, consider values[1].equals(String.valueOf(block))
Let me suggest some troubleshooting tips.
Write a unit test so you can easily run this repeatedly.
Put a System.out.println into the code in a few places to see which places it hits and when (On small problems this is often easier than debugging if you don't typically debug, I often have it print out a letter at the beginning of any code that comes after a decision point like if, loop and try/catch constructs.)
Print out the value of each line as you read it.
Print the value of blockbreak
I would guess your loop or the if statement aren't executing. Printing some values will tell you this quickly.
Also, if you truly intend Blockbreak to be assigned a value, try NOT assigning a default value of 0 in the beginning. This will stop you from compiling until you have assigned a value in every possible program flow path--a very handy feature (May not help in your case because of the way your while loop is structured, but it's a useful habit not to assign initial values until you need to in Java).
Related
I'm kinda new to Java so I'm looking for an help to do this.
As the title says, I'm trying to write a program that checks if a number given by the user from console is inside a text file with one number for each line or not.
I am using the Scanner class to check every line, but I am having problems with what condition the if statement should have when the number is found inside the file.
I wrote down this part code (I'm not even sure if it's correct itself, so correct me if I'm wrong):
int lines = 0;
while (filescanner.hasNextLine()) {
String line = filescanner.nextLine();
lines++;
if(conditon here) {
System.out.println("I found the number on line " + lines);
}
}
Thanks in advance.
Since you are getting the input number from Scanner keyboard, you can get its value like this:
String input = keyboard.next();
Then your if condition can be if(line.contains(input))
You need to convert the line to an integer and then test it. If it is not an integer the parseInt method throws an exception.
try {
int n = Integer.parseInt(line);
if (n == number) {
// found it
}
} catch (NumberFormatException e) {
// Not a number
}
sorry, changed the question slightly.
essentially i want to know if aString contains String. My issue is when comparing say aS a substring of aString) "aS".contains("String") shows true.
String a="st", b="string";
I ran System.out.println(a.contains(b));
That returned false, as expected. I have an understanding of contains, i must be missing something else.
So It had seemed that my program was working properly, but I made some adjustments and came back and the whole thing stopped working. I sussed out what are usually the common culprits (brackets, file io, etc.). I found if(string.contains(string)) would continually run, ie: always true. not sure why this is happening, probably something I missed in the code.
This is an example of my output (Just a char by char reading of the file):
I
n
t
e
g
e
r
G
;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class comp{
public static void main(String[] args){
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> symbolTable = new ArrayList<String>();
ArrayList<String> parsedFile = new ArrayList<String>();
try {
File file = new File("symbolTable.txt");
Scanner scanner=new Scanner(file);
while (scanner.hasNextLine()&&symbolTable.add(scanner.nextLine().replaceAll("\\s+","").toLowerCase()));
scanner.close();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
File file = new File("APU_CS400_input.txt");
Scanner scanner=new Scanner(file);
while (scanner.hasNextLine()&&lines.add(scanner.nextLine().replaceAll("\\s+","").toLowerCase()));
scanner.close();
} catch (Exception ex) {
ex.printStackTrace();
}
//runs through line by line of the input file
for(String line: lines){
String sBuild = "";
StringBuilder identifier = new StringBuilder("");
//moves through the line char by char
for(int i=0;line.length()>i; i++){
sBuild+=line.charAt(i);
//moves through the symbol table comparing each symbol to each string
//that is built char by char
for(String symbol: symbolTable){
//if the char string matches the symbol then any identifiers are saved and
//symbols are saved, the string is then reset to empty
//This is where i seem to get an issue
***if(sBuild.contains(symbol)){***
if(symbol.length()<sBuild.length()){
identifier.append(sBuild,0,sBuild.length()-symbol.length());
parsedFile.add(identifier.toString());
identifier.delete(0,sBuild.length()-symbol.length());
}
sBuild="";
parsedFile.add(symbol);
}
}
}
}
for(String symbol:parsedFile){
System.out.println(symbol);
}
}
}
Blockquote
Think of it this way.
s1.contains(s2)
should return true, if a substring of s1 can be found such that
s1.substring(i, j).equals(s2)
is true.
If s2 is an empty string, then i = 0, j = 0 is one such substring, so contains() returns true.
As it should.
if(String.Contains("")) always should be true, as long as the String is not null.
essentially i want to know if "aString" contains "String".
Yes, "aString" as a string-value does contain the string-value of "String"
My issue is when comparing say "aS" (a substring of "aString") "aS".contains("String") shows true.
Are you sure? This cannot be, therefore I rather suspect bugs in your code.
To spare youself of "empty String symbols" consider this:
try {
File file = new File("symbolTable.txt");
Scanner scanner=new Scanner(file);
while (scanner.hasNextLine()) {
// toLowerCase will do nothing for characters that are not letters
// Don't spend CPU cycles with regex
String symbolLine=scanner.nextLine().toLowerCase();
// Collect the symbol only if non-empty?? This will save you from empty symbols
if(symbolLine.trim().length()>0) {
symbolTable.add(symbolLine); // or .add(symbolLine.trim()) ???
}
}
scanner.close();
} catch (Exception ex) {
ex.printStackTrace();
}
You may have to look at this one a bit mathematically to see why s.contains("") is always true. Suppose you think of this this way:
a.contains(b) is true if there are some values i and j such that a.substring(i,j) is equal to b.
If you think about it a bit, you'll see that this is exactly what contains means when the argument is a nonempty string like "xyz". If there is some substring of x that equals "xyz", then s.contains("xyz") is true. If there is no such substring, then s.contains("xyz") is false.
So it makes sense that the same logic would apply for an empty string, since it applies everywhere else. And it's always true that a.substring(0,0) equals "" (if a is not null). That's why a.contains("") should always be true.
It may not be intuitively obvious from the English meaning of "contains", but when you're dealing with "edge cases" like this, you sometimes have to think in different terms. Often, the Javadoc spells things out so that you can easily figure out what happens in the edge cases, without relying on intuition. Unfortunately, in this case, they didn't.
I have a text file like this;
7-Georgia
1-Andrew
6-John
8-Luke
9-Erica
3-Kim
2-Jude
5-Phil
4-Leo
The first column is id and second is name. How can I get these id's and names? So far I wrote this;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
#SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
#SuppressWarnings("unused")
Scanner fromFile = new Scanner(new File("id_name.txt"));
fromFile.useDelimiter("-");
while(fromFile.hasNext()){
String temp = fromFile.next();
System.out.println(temp);
}
while(fromFile.hasNext()){
String temp= fromFile.next();
int[] fileID;
fileID= new int[9];
for(int i=0; i<9; i++){
fileID[i]= Integer.parseInt(temp);
}
System.out.println(fileID);
}
}
}
But this doesn't get the id's. I'm not sure how to fix this, I'd be grateful if you help me.
You have two while loops in your code. Typically one while loop will go through every item until the condition is no longer true. I think you need to rework this to have a better "flow of control" which might mean using only one while loop (with sections to grab the number and then the name.
I imagine that you are looking for results from the second while loop, but by the time you get to it, the first while loop will have exhausted all of your data.
Finally, printing an array will print out the array reference identifier. If you want to actually print the contents of the array, you need a loop over the elements within the array, and you need to print out each array element explicitly.
As an alternative to the array printing technique above (which you should master), you can also use the Arrays.toString(<insert array here>) method call. However, in many cases it will give you a format that is not desired. That's why you need to know the above technique too.
Also, you have one hidden issue. You (in the second while loop) make the assumption that there are only nine inputs. Pay close attention to what you are writing. Every time you have to reach for a number, consider whether it is a "magic" number. Magic numbers are numbers that are in your code with no explanation or reason why they exist. They are indicators of errors in the code made by assumptions that probably won't last the test of time.
For example, you are using the number 9 because you have seen the input file. The next input file will probably not have nine entries in it, and your program will probably not work right if you gave it an input with eight entries, or an input with ten entries. Perhaps you should rewrite the loop to remove the magic number, by making the logic process while there is still (some) input.
Try this on for size
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
Scanner fromFile = new Scanner(new File("id_name.txt"));
} catch (FileNotFoundException e) {
System.err.println("File not found");
}
String[] arr = new String[9];
String[] oth = new String[9];
int i = 0;
while(fromFile.hasNextLine()) {
String temp = fromFile.nextLine();
oth[i] = temp.substring(0,1);
arr[i] = temp.substring(2);
i++;
}
int[] fileID;
fileID = new int[9];
for(int j = 0; j < 9; j++) {
fileID[j] = Integer.parseInt(oth[j]);
}
}
}
this should go through and retrieve the numbers(.substring(0,1)) and then the names(.substring(2)), and then converting the numbers to int values.
Try the following:
File file=new File("id_name.txt");
int[] fileID;
fileID= new int[9];
String[] result = file.nextLine().split("-");
for (int x = 0; x < result.length; x++){
if (Character.isDigit(result[x])) { // use the isDigit method to get the ids
System.out.println("this is an id");
fileID[i]= Integer.parseInt(result[x]);
}
Actually my friend, there are several mistakes here.
1) When the first while loop completes, it leaves fromfile.hasNext() as false Hence the second loop never starts.
>> To fix this, You need to put it all in one while loop.
2) fileID is an array. You cannot print it using System.out.println(fileID).
>> You have to tell what kind of output you want. The code will depend on that. For simply printing all the values, you need to make a for loop that prints each value separartely. You should use fileID.length for the no. of times you need to loop it.
3) Basically, fromfile.next() is not the way to do it.
>> You need to use fromfile.nextLine().
I am using 'java.util.Scanner' to read and scan for keywords and want to print the previous 5 lines and next 5 lines of the encountered keyword, below is my code
ArrayList<String> keywords = new ArrayList<String>();
keywords.add("ERROR");
keywords.add("EXCEPTION");
java.io.File file = new java.io.File(LOG_FILE);
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int count = 0;
String previousLine = null;
while(input.hasNext()){
String line = input.nextLine();
for(String keyword : keywords){
if(line.contains(keyword)){
//print prev 5 lines
system.out.println(previousLine); // this will print only last previous line ( i need last 5 previous lines)
???
//print next 5 lines
system.out.println(input.nextLine());
system.out.println(input.nextLine());
system.out.println(input.nextLine());
system.out.println(input.nextLine());
system.out.println(input.nextLine());
}
previousLine = line;
}
any pointers to print previous 5 lines..?
any pointers to print previous 5 lines..?
Save them in an Dequeue<String> such as a LinkedList<String> for its "First In First Out (FIFO)" behavior.
Either that or use 5 variables or an array of 5 Strings, manually move Strings from one slot or variable to another, and then print them.
If you use Dequeue/LinkedList, use the Dequeue's addFirst(...) method to add a new String to the beginning and removeLast() to remove the list's last String (if its size is > 5). Iterate through the LinkedList to get the current Strings it contains.
Other suggestions:
Your Scanner's check scanner.hasNextXXX() method should match the get method, scanner.nextXXX(). So you should check for hasNextLine() if you're going to call nextLine(). Otherwise you risk problems.
Please try to post real code here in your questions, not sort-of, will never compile code. i.e., system.out.println vs System.out.println. I know it's a little thing, but it means a lot when others try to play with your code.
Use ArrayList's contains(...) method to get rid of that for loop.
e.g.,
LinkedList<String> fivePrevLines = new LinkedList<>();
java.io.File file = new java.io.File(LOG_FILE);
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (input.hasNextLine()) {
String line = input.nextLine();
if (keywords.contains(line)) {
System.out.println("keyword found!");
for (String prevLine : fivePrevLines) {
System.out.println(prevLine);
}
} else {
fivePrevLines.addFirst(line);
if (fivePrevLines.size() > 5) {
fivePrevLines.removeLast();
}
}
}
if (input != null) {
input.close();
}
Edit
You state in comment:
ok i ran small test program to see if the contains(...) method works ...<unreadable unformatted code>... and this returned keyword not found...!
It's all how you use it. The contains(...) method works to check if a Collection contains another object. It won't work if you feed it a huge String that may or may not use one of the Strings in the collection, but will work on the individual Strings that comprise the larger String. For example:
ArrayList<String> temp = new ArrayList<String>();
temp.add("error");
temp.add("exception");
String s = "Internal Exception: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object";
String[] tokens = s.split("[\\s\\.:,]+");
for (String token : tokens) {
if (temp.contains(token.toLowerCase())) {
System.out.println("keyword found: " + token);
} else {
System.out.println("keyword not found: " + token);
}
}
Also, you will want to avoid posting code in comments since they don't retain their formatting and are unreadable and untestable. Instead edit your original question and post a comment to alert us to the edit.
Edit 2
As per dspyz:
For stacks and queues, when there isn't any significant functionality/performance reason to use one over the other, you should default to ArrayDeque rather than LinkedList. It's generally faster, takes up less memory, and requires less garbage collection.
If your file is small (< a million lines) you are way better off just copying the lines into an ArrayList and then getting the next and previous 5 lines using random access into the array.
Sometimes the best solution is just plain brute force.
Your code is going to get tricky if you have two keyword hits inside your +-5 line window. Let's say you have hits two lines apart. Do you dump two 10-line windows? One 12-line window?
Random access will make implementing this stuff way easier.
What I'm trying to do is create lots of random files but I'm just completely lost. The code below just doesn't work, I'm wondering why it doesn't work and what can i do to fix it.
import java.io.*;
import java.util.*;
public class main {
public static void main(String arg[]){
Random rn = new Random();
int randn = 1+rn.nextInt(999999990);
String I_S = Integer.toString(randn);
Formatter file;
try{
for(int i = 0; i < 9999999; i++){
file = new Formatter("%s.txt", I_S);
}
}
catch(Exception ex){
System.err.println("Error");
}
}
}
By just generating random numbers, you may end up creating / overwriting the same file multiple times. To have an absolutely unique set, do something like this:
final int MAX = 9999999;
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < MAX; i++) {
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < MAX; i++) {
// create files here
}
How to create multiple files, generating a random name for each file.
You probably want to have a look at File.createTempFile.
Looking at your code, you probably want something like
Random rn = new Random();
String file;
for (int i = 0; i < 100; i++)
file = String.format("%i.txt", 1+rn.nextInt(999999990));
I'm not sure exactly what you expect this code to achieve, but right now it effectively does nothing.
You're looping many, many times creating an instance of Formatter each time. This is not a file; instead, it's a class that knows how to replace tokens in strings to create other strings.
I think you're confused by the description of the constructor you're calling and the purpose of the class as a whole. The constructor takes as its first argument the name of the file to use for output - in your case, this will always be %s.txt. The second argument is the name of a supported charset to use for encoding the String to the file.
This code will always fail because:
Your I_S variable, e.g., "56437890" is not a valid encoding (whereas "UTF-8" would be). Hence the constructor will probably throw an exception when trying to work out the encoding scheme.
Even if the charset was miraculously right, you're still trying to write to the same file (%s.txt) every time, so you wouldn't get the desired multi-file behaviour.
This string may not even be a valid filename, depending on your OS, and so if the Formatter tries to create the file it will throw an exception.
If both arguments miraculously work out, you're still not actually doing anything with the formatter, so it doesn't have anything to write out to the file which thus may not be created.
Finally, you're not updating your random variable (I_S) in the loop - it gets set once, and then maintains the same value forever. So even if all the above problems weren't issues, you'd still create the same (single) randomly-named file over and over and over again.
And as I noted in the comments, when it fails, you're catching and swallowing the exception so you have absolutely no way of knowing what went wrong.
Fundamentally I think you're confused about the purpose of the Formatter class, and since I don't know what you're trying to achieve (should the files be empty? Have specific text in?) I can't suggest something which definitely works. However, if you just want to create empty files, try something like this inside your loop:
String filename = "%s.txt".format(I_S);
File file = new File(filename);
file.createNewFile();
// Add some logic to update the random variable here!
As a final point, adarshr's answer is entirely right that you stand a nontrivial chance of repeating random numbers, so you won't get exactly as many files as you expect. The answer goes on to describe a good way to avoid this, and it's worth following.
You may want to look into writing something more like this:
void Write()
{
try {
for(int i = 0; i < MAX_FILES; i++) {
FileWriter outFile = new FileWriter("C:\File" + i.toString() + ".txt");
PrintWriter out = new PrintWriter(outFile);
// Write text to file
out.println("This is line 1");
out.println("This is line 2");
out.print("This is line3 part 1, ");
out.println("this is line 3 part 2");
out.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
// obviously this requires a import java.io.*; at the top of the class
Source: http://www.abbeyworkshop.com/howto/java/writeText/index.html