Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

How do I compare characters from a BufferedReader in Java?  RSS feed

 
Greenhorn
Posts: 13
C++ Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The program I currently have outputs numbers from a file into a string. But, I also want to "validate a string" by making sure the final number is equal to the sum of the first 5 numbers divided by 10.

       
 
Marshal
Posts: 61727
193
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Thank you for using the code button, but youi didn't quite get it right: the [/code] part goes after the code. Don't worry: I have corrected that for you, and doesn't it look better now
You cannot compare characters from a buffered reader because the buffered reader diesn't give you characters. It either gives you ints from the read() method, which I look on as a pain similar to toothache, or you can get a String representing the line with the readLine() method. That is what you are using. Youi diddn't explain what format the lines are in, whether they are one number per line or five. You will have to find some way of retaining the info in a variable of some sort, turning in into an int, and doing the arithmetic. We all know you can use this to convert your Strings to numbers, but I wouldn't use a buffered reader myself. Watch this space for a further post with different suggestions.
 
Campbell Ritchie
Marshal
Posts: 61727
193
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right. Have you not been told always to close buffered readers reading files? It used to be necessary to use a finally block, but Java7 introduced try with resources, which will do all the closing for you. Always close files, sockets, etc., but never close System.in System.out nor System.err. So now you would have:-Don't declare your method as throwing Exception. Use something more specific, e.g. IOException. Notice how to break the long line in lines 1‑3 into three parts. No semicolon if you only create one resource. I would prefer to call the output from the buffered reader line rather than file. Don't use \\ in the file path: use / and let the JVM convert that to backslash.
I wouldn't use a buffered reader, but a Scanner which will give you the int directly. You may be able to get away with catching FileNotFoundException rather than IOException because Scanners can consume IOExceptions, but I am not certain. Note it is a bad idea to use a magic number like 5 or 10, but it would look a bit daft to have constants FIVE and TEN, so I have a compromise style.Links to API: Paths#get() Scanner() constructor Scanner#nextInt()
You will notice that I haven't made any attempt to work out the logic of equality of those numbers. Also I haven't told you what sort of exception will be thrown if your file doesn't contain the requisite number of ints. I will however tell you not to use / 10. Don't divide. Multiply the sum of five numbers by ten instead. I shall leave you to work out why.
 
Campbell Ritchie
Marshal
Posts: 61727
193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the +1s; I presume you  have got it all working now. Do show us what you have achieved.
 
Blaine Jackson
Greenhorn
Posts: 13
C++ Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry it took so long to reply, but this is what I've gotten so far

It compiles and runs, but the program won't output anything. Can you please help me with this as well?
 
Campbell Ritchie
Marshal
Posts: 61727
193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Start by moving all that code out of the main method. I think you have at least enough code there to make three methods. Also, make sure the names of your variables make it clear what they mean. Also, what are you closing in lines 59‑60?
I am not sure what the method is supposed to produce as output; please explain that too.
 
Bartender
Posts: 9494
184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a couple of things wrong with that code:

  • Don't put everything in main(). Split your logic into methods.
  • Don't open multiple streams to the same file at the same time. First finish reading, then open the OutputStream.
  • Use try-with-resources when dealing with readers and streams. That way you can be sure your streams are closed successfully.
  • Use Path instead of File.
  • Don't declare your variables before you need them.
  • Get rid of unused code (newline is not used).
  • Escape sequences in strings start with a backslash. The newline character is '\n' not '/n'.
  • Use descriptive names. acct doesn't mean anything.
  • Use comments to explain why you're doing something, not what you're doing.
  • Even when explaining 'what', your comments must be correct. Line 33 doesn't print anything.
  • Use compound assignment operators instead of a combination of an operator and an assignment.
  • Don't use deprecated methods like String.getBytes(). If you want to write text, use an instance of Writer.
  • Make sure your code is indented properly. Lines 38 to 56 should be indented another level.
  •  
    Blaine Jackson
    Greenhorn
    Posts: 13
    C++ Java Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I FINALLY MANAGED TO GET TO GET THIS THING TO WORK THE RIGHT WAY! Thank you both so much!
    This is the code I used:

    The program outputted:
    223355 is valid
    541437 is valid
    582904 is valid
    125690 is invalid
    325640 is valid
    123455 is valid
    563891 is valid
    425786 is valid
    014549 is invalid
    292711 is valid
    163213 is valid
    692052 is valid
    297536 is valid
    157935 is valid


    I  didn't have time to figure out how to do some of the stuff you told me to do because I was on a bit of a time crunch, but I still managed to get it to work perfectly!
     
    Campbell Ritchie
    Marshal
    Posts: 61727
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Well done, but Iknow if I had handed that in for an assessment when I was a student, I wouldn't have got more than 45%.
    Please avoid boldface type and ALL UPPER‑CASE WRITING.

    Let's see if we can't show you what you mean. I would use a Scanner object for a text file, I shall be using my KeyboardInputs class for, would you believe, keyboard inputs, but I think the intention of the methods should be obvious.
    What are you doing on line 30? Why do you think the number will always have six digits? Are you trying to calculate the transverse sum of the digits for some sort of validation? Do you know what the transverse sum of the digits signifies? That bit of the code is by no means clear. Nor is the indentation. The code from line 14 to line 54 is only one space right of the {}, which makes it difficult to see where the block ends. It is you who will have difficulty reading the blocks if anything goes wrong.
  • Line 3: Use a Path not a File; File is now regarded as legacy code. Note that the Path is a field of the object, so you are using a more OO (=object‑oriented) approach.
  • Line 17: Try wih resources allows you to open the buffered reader and ensures it is closed, so you don't need to write close(); The Files#newBufferedReader(Path) method creates the buffered reader for you.
  • Line 20: Learn this syntax off by heart; it is the conventional way to iterate the output of a buffered reader. No need for break. Note the = operator has to be wrapped in () so its result is evaluated before the != operator.
  • Line 31: Note the non‑javadoc comment to explain what I think the method does. Such an explanatory comment is essential because the algorithm isn't obvious on a casual reading.
  • Line 37: This method could have been a static method in a utility class instead. It shows that you are very closely coupled between the structure of the file, the structure of your numbers, and the format of your code.
  • Line 39: Think how much easier that would have been using a Scanner, which can give you the int directly.
  • I shall leave you to write the notifyXXX methods.
    Why are you using a class with a name ending Stream for what appears to be text? It will only work because you are lucky and the text can be encoded with UTF-8; other text using characters > 0x7f may be encoded incorrectly with the byte array. I would use a Formatter myself. You might do well to store the outputs in a List so you can write the whole lot at once. Alternatively use this method to get a buffered writer; you can probably use this OpenOption constant if you need to write repeatedly. I have never worked out how to make a Formatter append; I am not sure it is possible. You may then need two Path fields one for input and one for output. Note that final fields have to be initialised before the constructor completes. A better version of the code would verify the Paths in the constructors.
    Don't use System.getProperty("line.seperator"); use this method instead.

    You are welcome to hand in my code, but rest assured it will be found on the net within a few minutes and will earn you a nice round number as a mark. Round as in the way this number is round: 0.
     
    Stephan van Hulst
    Bartender
    Posts: 9494
    184
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Well done. When you have time, please go back to your code and our comments and fix it. This is a great way of learning more about Java and getting skilled at coding.
     
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!