Read from File ASCII art Replace, Write to File - java

Trying to read text from ASCII art text file (it contains a series of blank spaces and '*' characters). Then, I want to be able to change the asterisks to whatever character the user wishes.
I also want to select a random file. All three files exist. I can store them as a list, if needed.
When executed, this code prompts user for substitution text but then just returns the file read location (including the random number 1-3).
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class AsciiArt
{
public static void main(String[]args) throws IOException
{
System.out.println("ASCII Art\n");
Scanner kbd = new Scanner(System.in);
Random randomGen = new Random();
int verSub = randomGen.nextInt(3)+1;
String fullSub = "/user/****/data/****"+verSub+".dat";
File inputFile = new File(fullSub);
System.out.print("Enter substitution text? ");
String subText = kbd.next();
Scanner input = new Scanner(fullSub);
PrintWriter outputFile = new PrintWriter("newFile.txt")
String line;
while(input.hasNext()){
line = input.nextLine();
int i, subIdx = 0;
for (i = 0; i < line.length(); i++){
if(line.charAt(i) == '*'){
outputFile.print(subText.charAt(subIdx));
++subIdx;
}
if(subIdx == subText.length()){
subIdx = 0;
}
else{
outputFile.print(line.charAt(i));
}
}
}
input.close();
outputFile.close();
System.out.println();
}
}

Related

Read a random word from a file for user to guess - Java

I'm write a code that pulls a word from a file and guesses it. For instance the word would be "apple".
The user will see: *****
If they input 'p' as a guess they see: *pp**
So far it's working if I manually the word apple in a variable called secretPhrase, however I'm not sure how to have the program pull the word from a text file and store it into secretPhrase for the user to guess.
public static void main(String args[]) {
String secretPhrase = "apple";
String guesses = " ";
Scanner keyboard = new Scanner(System.in);
boolean notDone = true;
Scanner word = new Scanner(System.in);
System.out.print("Enter a word: ");
while(true) {
notDone = false;
for(char secretLetter : secretPhrase.toCharArray()) {
if(guesses.indexOf(secretLetter) == -1) {
System.out.print('*');
notDone = true;
} else {
System.out.print(secretLetter);
}
}
if(!notDone) {
break;
}
System.out.print("\nEnter your letter:");
String letter = keyboard.next();
guesses += letter;
}
System.out.println("Congrats");
}
You have several options. One is to do the following. It is not complete and doesn't check on border cases. But you can figure that out. It presumes the file contains one word per line.
try {
RandomAccessFile raf = new RandomAccessFile(
new File("wordfile.txt"), "r");
Random r = new Random();
// ensure the length is an int
int len = (int)(raf.length()&0x7FFFFFFF);
// randomly select a location
long loc = r.nextInt(len);
// go to that file location
raf.seek(loc);
// find start of next line
byte c = raf.readByte();
while((char)c != '\n') {
c = raf.readByte();
}
// read the line
String line = raf.readLine();
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
}
A much easier solution for perhaps a smaller set of words is to just read them into a List<String> and the do a Collections.shuffle() to randomize them. Then just use them in the shuffled order.

How can I display file with line numbers in my Java program?

I want my program to display the contents of the file the user inputs with each line preceded with a line number followed by a colon. The line numbering should start at 1.
This is my program so far:
import java.util.*;
import java.io.*;
public class USERTEST {
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a file name: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
while (inputFile.hasNext()){
String name = inputFile.nextLine();
System.out.println(name);
}
inputFile.close();
}
}
I can display the contents of the file so far, but I don't know how to display the contents with the line numbers.
Integer i = 0;
while (inputFile.hasNext()) {
i++;
String line = inputFile.nextLine();
System.out.println(i.toString() + ": " + line);
}
You just need to concat an index to your output string.
int i=1;
while (inputFile.hasNext()){
String name = inputFile.nextLine();
System.out.println(i+ ","+name);
i++;
}
int lineNumber=0;
while (inputFile.hasNext()){
String name = inputFile.nextLine();
`System.out.println(lineNumber+ ":"+name);`
linenumber++;
}
Use an int initialized to 1 and increment it every time you read a line, then just output it before the line contents.
What about creating a numerical counter (increased every time you read a line) ... and putting that in front of the string that you are printing?

count characters, words and lines in file

This should count number of lines, words and characters into file.
But it doesn't work. From output it shows only 0.
Code:
public static void main(String[] args) throws IOException {
int ch;
boolean prev = true;
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner in = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}
// count the characters of the file till the end
while(in.hasNext()) {
ch = in.next().charAt(0);
if (ch != ' ') ++charsCount;
if (!prev && ch == ' ') ++wordsCount;
// don't count if previous char is space
if (ch == ' ')
prev = true;
else
prev = false;
if (ch == '\n') ++linesCount;
}
//display the count of characters, words, and lines
charsCount -= linesCount * 2;
wordsCount += linesCount;
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
in.close();
}
I can't understand what's going on.
Any suggestions?
Different approach. Using strings to find line,word and character counts:
public static void main(String[] args) throws IOException {
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner in = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}
while (in.hasNext()) {
String tmpStr = in.nextLine();
if (!tmpStr.equalsIgnoreCase("")) {
String replaceAll = tmpStr.replaceAll("\\s+", "");
charsCount += replaceAll.length();
wordsCount += tmpStr.split(" ").length;
}
++linesCount;
}
//display the count of characters, words, and lines
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
in.close();
}
Note:
For other encoding styles use new Scanner(new File(selectedFile), "###"); in place of new Scanner(selectedFile);.
### is the Character set to needed. Refer this and wiki
Your code is looking at only the first characters of default tokens (words) in the file.
When you do this ch = in.next().charAt(0), it gets you the first character of a token (word), and the scanner moves forward to the next token (skipping rest of that token).
You have a couple of issues in here.
First is the test for the end of line is going to cause problems since it usually isn't a single character denoting end of line. Read http://en.wikipedia.org/wiki/End-of-line for more detail on this issue.
The whitespace character between words can be more than just the ASCII 32 (space) value. Consider tabs as one case. You want to check for Character.isWhitespace() more than likely.
You could also solve the end of line issues with two scanners found in How to check the end of line using Scanner?
Here is a quick hack on the code you provided along with input and output.
import java.io.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
public final class TextApp {
public static void main(String[] args) throws IOException {
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner fileScanner = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
fileScanner = new Scanner(selectedFile);
}
while (fileScanner.hasNextLine()) {
linesCount++;
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
// count the characters of the file till the end
while(lineScanner.hasNext()) {
wordsCount++;
String word = lineScanner.next();
charsCount += word.length();
}
lineScanner.close();
}
//display the count of characters, words, and lines
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
fileScanner.close();
}
}
Here is the test file input:
$ cat ../test.txt
test text goes here
and here
Here is the output:
$ javac TextApp.java
$ java TextApp
# of chars: 23
# of words: 6
# of lines: 2
$ wc test.txt
2 6 29 test.txt
The difference between character count is due to not counting whitespace characters which appears to be what you were trying to do in the original code.
I hope that helps out.
You could store every line in a List<String> and then linesCount = list.size().
Calculating charsCount:
for(final String line : lines)
charsCount += line.length();
Calculating wordsCount:
for(final String line : lines)
wordsCount += line.split(" +").length;
It would probably be a wise idea to combine these calculations together as opposed to doing them seperately.
Use Scanner methods:
int lines = 0;
int words = 0;
int chars = 0;
while(in.hasNextLine()) {
lines++;
Scanner lineScanner = new Scanner(in.nextLine());
lineScanner.useDelimiter(" ");
while(lineScanner.hasNext()) {
words++;
chars += lineScanner.next().length();
}
}
Looks like everyone is suggesting you an alternative,
The flaw with your logic is, you are not looping through the all the characters for the entire line. You are just looping through the first character of every line.
ch = in.next().charAt(0);
Also, what does 2 in charsCount -= linesCount * 2; represent?
You might also want to include a try-catch block, while accessing a file.
try {
in = new Scanner(selectedFile);
} catch (FileNotFoundException e) {}
Maybe my code will help you...everything work correct
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class LineWordChar {
public static void main(String[] args) throws IOException {
// Convert our text file to string
String text = new Scanner( new File("way to your file"), "UTF-8" ).useDelimiter("\\A").next();
BufferedReader bf=new BufferedReader(new FileReader("way to your file"));
String lines="";
int linesi=0;
int words=0;
int chars=0;
String s="";
// while next lines are present in file int linesi will add 1
while ((lines=bf.readLine())!=null){
linesi++;}
// Tokenizer separate our big string "Text" to little string and count them
StringTokenizer st=new StringTokenizer(text);
while (st.hasMoreTokens()){
`enter code here` s = st.nextToken();
words++;
// We take every word during separation and count number of char in this words
for (int i = 0; i < s.length(); i++) {
chars++;}
}
System.out.println("Number of lines: "+linesi);
System.out.println("Number of words: "+words);
System.out.print("Number of chars: "+chars);
}
}
public class WordCount {
/**
* #return HashMap a map containing the Character count, Word count and
* Sentence count
* #throws FileNotFoundException
*
*/
public static void main() throws FileNotFoundException {
lineNumber=2; // as u want
File f = null;
ArrayList<Integer> list=new ArrayList<Integer>();
f = new File("file.txt");
Scanner sc = new Scanner(f);
int totalLines=0;
int totalWords=0;
int totalChars=0;
int totalSentences=0;
while(sc.hasNextLine())
{
totalLines++;
if(totalLines==lineNumber){
String line = sc.nextLine();
totalChars += line.length();
totalWords += new StringTokenizer(line, " ,").countTokens(); //line.split("\\s").length;
totalSentences += line.split("\\.").length;
break;
}
sc.nextLine();
}
list.add(totalChars);
list.add(totalWords);
list.add(totalSentences);
System.out.println(lineNumber+";"+totalWords+";"+totalChars+";"+totalSentences);
}
}

Counting a specific character in a file with Scanner

I'm trying to write a program that prompts the user to enter a character, and count the number of instances said character appears in a given file. And display the number of times the character appears.
I'm really at a loss, and I'm sorry I don't have much code yet, just don't know where to go from here.
import java.util.Scanner;
import java.io.*;
public class CharCount {
public static void main(String[] args) throws IOException {
int count = 0;
char character;
File file = new File("Characters.txt");
Scanner inputFile = new Scanner(file);
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a single character");
character = keyboard.nextLine().charAt(0);
}
}
You need the below code to read from the file and check it with the character you've entered. count will contain the occurrences of the specified character.
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) !=null) {
for(int i=0; i<line.length();i++){
if(line.charAt(i) == character){
count++;
}
}
}
} catch (FileNotFoundException e) {
// File not found
} catch (IOException e) {
// Couldn't read the file
}

Java simple counting words in a file

I am creating a simple program that counts the number of words, lines and total characters (not including whitespace) in a paper. It is a very simple program. My file compiles but when I run it I get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at WordCount.wordCounter(WordCount.java:30)
at WordCount.main(WordCount.java:16)
Does anyone know why this is happening?
import java.util.*;
import java.io.*;
public class WordCount {
//throws the exception
public static void main(String[] args) throws FileNotFoundException {
//calls on each counter method and prints each one
System.out.println("Number of Words: " + wordCounter());
System.out.println("Number of Lines: " + lineCounter());
System.out.println("Number of Characters: " + charCounter());
}
//static method that counts words in the text file
public static int wordCounter() throws FileNotFoundException {
//inputs the text file
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
//while there are more lines
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
return countWords;
}
//static method that counts lines in the text file
public static int lineCounter() throws FileNotFoundException {
//inputs the text file
Scanner input2 = new Scanner(new File("words.txt"));
int countLines = 0;
//while there are more lines
while (input2.hasNextLine()) {
//casts each line as a string
String line = input2.nextLine();
//counts each line
countLines++;
}
return countLines;
}
//static method that counts characters in the text file
public static int charCounter() throws FileNotFoundException {
//inputs the text file
Scanner input3 = new Scanner(new File("words.txt"));
int countChar = 0;
int character = 0;
//while there are more lines
while(input3.hasNextLine()) {
//casts each line as a string
String line = input3.nextLine();
//goes through each character of the line
for(int i=0; i < line.length(); i++){
character = line.charAt(i);
//if character is not a space (gets rid of whitespace)
if (character != 32){
//counts each character
countChar++;
}
}
}
return countChar;
}
}
I can't really say the exact reason for the problem without looking at the file (Maybe even not then).
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
Is your problem. If you are using the input.hasNextLine() in the while conditional statement use input.nextLine(). Since you are using input.next() you should use input.hasNext() in the while loops conditional statement.
public static int wordCounter() throws FileNotFoundException
{
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
while (input.hasNextLine()) {
if(input.hasNext()) {
String word = input.next();
countWords++;
}
}
return countWords;
}
I have just added an if condition within the while loop. Just make sure to check there are token to be parsed. I have changed only in this place. Just make sure to change wherever needed.
This link will give good info. in regard to that.
Hope it was helpful. :)

Categories