Increase all characters by 1 (JAVA) - java

So I need help with increasing all characters in a file. Whole file is able to read and get all the info form the user but when it comes to actual increasing all characters from (this case) a file it just outputs a blank file.
Goal of this program is to read in a users file get all the text from the file and increase or decrease the letters by one. So A is now a B or B is now a C or via versa B is now a A or C is now a B. When it goes to export/close the file it just is blank.
Here is that portion of the code:
while (fileIn.hasNext())
{
letter.add(fileIn.next());
for (int i = letter.size() - 1; i >= 0; i--)
{
ch = letter.get(i).charAt(0);
ch--;
fileout1.println(ch);
}
//Makes a new line at end of line
System.out.println();
}
Whole code is as follows:
import java.util.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.util.ArrayList;
public class Assignment9
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
Scanner fileIn;
File f;
char ch = 65;
String fileName = "";
boolean userA = false;
String usersChoice = "";
ArrayList<String> letter = new ArrayList<String>();
try
{
System.out.println("Please enter the file name that you would like encrypted/decrypted: ");
fileName = in.nextLine();
//Builds the file and attaches the Scanner
f = new File (fileName);
fileIn = new Scanner (f);
PrintWriter fileout1 = new PrintWriter ("decrypt.txt");
PrintWriter fileout2 = new PrintWriter ("encrypt.txt");
System.out.println("Would you like to Decrypt or Encrypt the file?");
usersChoice = in.nextLine();
userA = true;
//Loop through the file and translate the characters
if (usersChoice.equalsIgnoreCase("Decrypt"))
{
while (fileIn.hasNext())
{
letter.add(fileIn.next());
for (int i = letter.size() - 1; i >= 0; i--)
{
ch = letter.get(i).charAt(0);
ch--;
fileout1.println(ch);
}
//Makes a new line at end of line
System.out.println();
}
//Decrease every letter by 1 (runs backwords)
System.out.println("Decrypt.txt has been created.");
fileout1.close();
}
//encrypts the file by increasing by 1
if (usersChoice.equalsIgnoreCase("encrypt"))
{
while (fileIn.hasNext())
{
letter.add(fileIn.next());
}
//Decrease every letter by 1 (runs backwords)
for (int i = letter.size() -1; i >= 0; i--)
{
System.out.println(letter);
ch --;
}
System.out.println("Encrypted.txt has been created.");
fileout2.close();;
}
} //end of try
catch (FileNotFoundException e)
{
System.out.println("Sorry invalid file, please try again");
fileName = in.nextLine();
}
} // end of main
} //end of program

You can do something like as below,
FileReader fr = null;
FileWriter fw = null;
int c;
try {
fr = new FileReader("C:\\Zia\\test.txt");
fw = new FileWriter("C:\\Zia\\Result.txt");
while ((c = fr.read()) != -1) {
if(c!=32)
fw.write((char)--c);
else
fw.write((char)c);
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
My test.txt file contains the below content,
Hello How are you doing.
and result.txt contains the below result after decreasing the char by one.
Gdkkn Gnv `qd xnt cnhmf-
you may interchange the file name for both the file for Reader and writer and increase the char by 1 to verify the decryption.

Related

NumberFormatException when reading CSV file in java

I'm beginner in java and kinda stuck in these two problems so I'm trying to
let the program read from a CSV file line by line.
So in the file I have first row as String and the column is double.
So the problem is when it read first line It's reading the titles as double and it gives me an error.
By the way it is CSV file
The error i got are these below
Exception in thread "main" java.lang.NumberFormatException: For input string: "CLOSE" This is first error
Second error >> at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecima‌​l.java:1222) –
Third error >> at java.lang.Double.parseDouble(Double.java:510)
Forth error >>> at AlgorithmTrader.ReadInputData(AlgorithmTrader.java:63)
Fifth Error >> at AlgorithmTrader.Run(AlgorithmTrader.java:16)
Last error >> SimpleAlgorithmTradingPlatform.main(SimpleAlgorithmTradingPl‌​atform.java:15)
So the first row in the file has TIMESTAMP | Close | High | Low | open | volume and under each of those row there is numbers as double except volume has integer numbers
Your suggestion will appreciated. Thanks
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class AlgorithmTrader {
public void Run() {
ReadInputData();
}
public void ReadInputData() {
// create object of scanner class for user input
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from user for input file
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();
try {
PrintWriter pw = new PrintWriter("output.csv");// to open the file
// create a new file
File file = new File(inputFileName);
// create a new scanner object to read file
Scanner readFile = new Scanner(file);
// for each line data
String line = "";
line = readFile.nextLine();//skip the first line
while (readFile.hasNextLine()) {
readFile.nextLine();
// pass file to scanner again
readFile = new Scanner(file);
ArrayList<String> list = new ArrayList<String>();
// read stock data line by line
while (readFile.hasNextLine()) {
// read line from file
line = readFile.nextLine();
// split line data into tokens
String result[] = line.split(",");
// variables to create a Stock object
String timestamp = result[0];
double close = Double.parseDouble(result[1]);
double high = Double.parseDouble(result[2]);
double low = Double.parseDouble(result[3]);
double open = Double.parseDouble(result[4]);
int volume = Integer.parseInt(result[5]);
// store data into ArrayList
list.add(readFile.next());
pw.print(list.add(readFile.next()));
Stock stock = new Stock(timestamp, close, high, low, open, volume);
}// end of while to read file
//close readFile object
readFile.close();
pw.close();//close file
}
} catch (FileNotFoundException e1) {
System.out.println(" not found.\n");
System.exit(0);
} catch (IOException e2) {
System.out.println("File can't be read\n");
}
}
}
I have another file Stock class
public class Stock {
String timestamp;
double close;
double high;
double low;
double open;
int volume;
Stock(String t, double c, double h, double l, double o, int v) {
timestamp = t;
close = c;
high = h;
low = l;
open = o;
volume = v;
}
public void settimestamp(String t) {
this.timestamp = t;
}
public void setclose(double c) {
this.close = c;
}
public void sethigh(double h) {
this.high = h;
}
public void setopen(double o) {
this.open = o;
}
public void setvolume(int v) {
this.volume = v;
}
public String gettimestamp() {
return timestamp;
}
public double close() {
return close;
}
public double high() {
return high;
}
public int volume() {
return volume;
}
}
And The main method in another file as well
import java.text.DecimalFormat;
public class SimpleAlgorithmTradingPlatform {
public static void main(String[] args) {
DecimalFormat fmt = new DecimalFormat("#0.00"); // to get the DecimalFormat
AlgorithmTrader test = new AlgorithmTrader();
test.Run();
}
}
You are you having NumberFormatException because here
line = readFile.nextLine();//skip the first line
you are not skipping first line.
You'd better use BufferedReader instead of Scanner after getting file name. I have corrected you code a bit.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class AlgorithmTrader {
public void Run() {
ReadInputData();
}
public void ReadInputData() {
// create object of scanner class for user input
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from user for input file
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();
// create a new file
File csvFile = new File(inputFileName);
String line;
ArrayList<Stock> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
System.out.println("Reading file " + csvFile);
System.out.println("Skipping title of the CSV file");
// Skip first line because it is title
br.readLine();
System.out.println("Converting line to Stock");
while ((line = br.readLine()) != null) {
String result[] = line.split(",");
String timestamp = result[0];
double close = Double.parseDouble(result[1]);
double high = Double.parseDouble(result[2]);
double low = Double.parseDouble(result[3]);
double open = Double.parseDouble(result[4]);
int volume = Integer.parseInt(result[5]);
list.add(new Stock(timestamp, close, high, low, open, volume));
}
System.out.println("Done");
} catch (FileNotFoundException e1) {
System.out.println(" not found.");
System.exit(0);
} catch (IOException e2) {
System.out.println("File can't be read");
}
}
}
It would be nice to see a fictional example of the contents within your CSV file but please spare us any additional comments. ;)
It looks like your errors (and probably all of them) are most likely coming from your Stock Class. That's for another posted question however your getters and setters need attention. Some are missing as well but perhaps this is by choice.
You should be able to carry out this task with one Scanner object and one while loop. Use the same Scanner object for User input and file reading, it's reinitialized anyways.
The code below is one way to do it:
ArrayList<String> list = new ArrayList<>();
// create object of scanner class for user input
// and File Reading.
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from User for input file name.
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();
String tableHeader = "";
try {
// create a new file with PrintWriter in a
PrintWriter pw = new PrintWriter("output.csv");
File file = new File(inputFileName);
// Does the file to read exist?
if (!file.exists()) {
System.err.println("File Not Found!\n");
System.exit(0);
}
// create a new scanner object to read file
scan = new Scanner(file);
// for each line data
String line = "";
tableHeader = scan.nextLine();
String newline = System.getProperty("line.separator");
// Print the Table Header to our new file.
pw.print(tableHeader + newline);
while (scan.hasNextLine()) {
line = scan.nextLine();
// Make sure we don't deal with a blank line.
if (line.equals("") || line.isEmpty()) {
continue;
}
// split line data into a String Array.
// Not sure if there is a space after
// comma delimiter or not but I'm guessing
// there is. If not then remove the space.
String result[] = line.split(", ");
// variables to create a Stock object
String timestamp = "";
double close = 0.0;
double high = 0.0;
double low = 0.0;
double open = 0.0;
int volume = 0;
// Make sure there are enough array elements
// from our split string to fullfil all our
// variables. Maybe some data is missing.
int resLen = result.length;
if (resLen > 0) {
if (resLen >= 1) { timestamp = result[0]; }
if (resLen >= 2) { close = Double.parseDouble(result[1]); }
if (resLen >= 3) { high = Double.parseDouble(result[2]); }
if (resLen >= 4) { low = Double.parseDouble(result[3]); }
if (resLen >= 5) { open = Double.parseDouble(result[4]); }
if (resLen >= 6) { volume = Integer.parseInt(result[5]); }
}
// store data into ArrayList.
// Convert the result Array to a decent readable string.
String resString = Arrays.toString(result).replace("[", "").replace("]", "");
list.add(resString);
// Print the string to our output.csv file.
pw.print(resString + System.getProperty("line.separator"));
//Stock stock = new Stock(timestamp, close, high, low, open, volume);
}
//close file
scan.close();
pw.close();
}
catch (IOException ex ){
System.err.println("Can Not Read File!\n" + ex.getMessage() + "\n");
System.exit(0);
}
// Example to show that the ArrayList actually
// contains something....
// Print data to Console Window.
tableHeader = tableHeader.replace(" | ", "\t");
tableHeader = "\n" + tableHeader.substring(0, 10) + "\t" + tableHeader.substring(10);
System.out.println(tableHeader);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).replace(", ", "\t"));
}

I'm getting FileNotFound exception while trying to create a file

I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}

Character Count

I'm trying to count the number of Words, Lines and characters(excluding whitespace). The only part I can't get to work is ignoring the whitespace for the character count.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) throws IOException{
File file = getValidFile();
int count = wordCount(file);
int lines = lineCount(file);
int characters = characterCount(file);
System.out.println("Total Words = " + count);
System.out.println("Total Lines = " + lines);
System.out.println("Total Characters = " + characters);
}
public static int characterCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file).useDelimiter(",\\s*");;
int characters = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
characters++; //count the word
}
inputFile.close();
return characters;
}
}
public static int lineCount(File file)throws IOException {
{
Scanner inputFile = new Scanner(file);
int lines = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.nextLine(); //read in a line
lines++; //count the line
}
inputFile.close();
return lines;
}
}
public static int wordCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file);
int count = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
count++; //count the word
}
inputFile.close();
return count;
}
}
public static File getValidFile()
{
String filename; // The name of the file
File file;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get a valid file name.
do
{
/*for (int i = 0; i < 2; i ++ )
{*/
System.out.print("Enter the name of a file: ");
filename = keyboard.nextLine();
file = new File(filename);
if (!file.exists())
System.out.println("The specifed file does not exist - please try again!");
}while( !file.exists());
return file;
}
}
If you want to count the characters in the file, excluding any whitespace, you can read your file line by line and accumulate the character count, or read the whole file in a String and do the character count, e.g.
String content = new Scanner(file).useDelimiter("\\Z").next();
int count = 0;
for (int i = 0; i < content.length(); i++) {
if (!Character.isWhitespace(content.charAt(i))) {
count++;
}
}
System.out.println(count);
EDIT
Other solutions if you don't care about the content of the file, then there is no need to load it into a String, you can just read character by character.
Example counting the non-whitespace characters in Arthur Rimbaud poetry.
Using a Scanner
URL rimbaud = new URL("http://www.gutenberg.org/cache/epub/29302/pg29302.txt");
int count = 0;
try (BufferedReader in = new BufferedReader(new InputStreamReader(rimbaud.openStream()))) {
int c;
while ((c = in.read()) != -1) {
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);
Using a plain StreamReader
count = 0;
try (Scanner sin = new Scanner(new BufferedReader(new InputStreamReader(rimbaud.openStream())))) {
sin.useDelimiter("");
char c;
while (sin.hasNext()) {
c = sin.next().charAt(0);
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);

Scanner will take user input but will not find the file

This is a program to read a file and print out the file with some of the text edited. The code will compile the issue is that it will read the users input but will say file is not found when the file is there. I feel like I am missing something. I am brand new at this so go easy on me.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainTest {
public static void main(String args[]) {
// if (args[0] != null)
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = "";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count;
} else if (ch == '}') {
out = out + " " + count;
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
You can use System.getProperty("user.dir") to find where Scanner looking to find your file. And you should be sure your file is located here.

How to tokenize an input file in java

i'm doing tokenizing a text file in java. I want to read an input file, tokenize it and write a certain character that has been tokenized into an output file. This is what i've done so far:
package org.apache.lucene.analysis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
class StringProcessing {
// Create BufferedReader class instance
public static void main(String[] args) throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyboardInput = new BufferedReader(input);
System.out.print("Please enter a java file name: ");
String filename = keyboardInput.readLine();
if (!filename.endsWith(".DAT")) {
System.out.println("This is not a DAT file.");
System.exit(0);
}
File File = new File(filename);
if (File.exists()) {
FileReader file = new FileReader(filename);
StreamTokenizer streamTokenizer = new StreamTokenizer(file);
int i = 0;
int numberOfTokensGenerated = 0;
while (i != StreamTokenizer.TT_EOF) {
i = streamTokenizer.nextToken();
numberOfTokensGenerated++;
}
// Output number of characters in the line
System.out.println("Number of tokens = " + numberOfTokensGenerated);
// Output tokens
for (int counter = 0; counter < numberOfTokensGenerated; counter++) {
char character = file.toString().charAt(counter);
if (character == ' ') { System.out.println(); } else { System.out.print(character); }
}
} else {
System.out.println("File does not exist!");
System.exit(0);
}
System.out.println("\n");
}//end main
}//end class
When i run this code, this is what i get:
Please enter a java file name: D://eclipse-java-helios-SR1-win32/LexractData.DAT
Number of tokens = 129
java.io.FileReader#19821fException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 25
at java.lang.String.charAt(Unknown Source)
at org.apache.lucene.analysis.StringProcessing.main(StringProcessing.java:40)
The input file will look like this:
-K1 Account
--Op1 withdraw
---Param1 an
----Type Int
---Param2 amount
----Type Int
--Op2 deposit
---Param1 an
----Type Int
---Param2 Amount
----Type Int
--CA1 acNo
---Type Int
-K2 CheckAccount
--SC Account
--CA1 credit_limit
---Type Int
-K3 Customer
--CA1 name
---Type String
-K4 Transaction
--CA1 date
---Type Date
--CA2 time
---Type Time
-K5 CheckBook
-K6 Check
-K7 BalanceAccount
--SC Account
I just want to read the string which are starts with -K1, -K2, -K3, and so on... can anyone help me?
The problem is with this line --
char character = file.toString().charAt(counter);
file is a reference to a FileReader that does not implement toString() .. it calls Object.toString() which prints a reference around 25 characters long. Thats why your exception says OutofBoundsException at the 26th character.
To read the file correctly, you should wrap your filereader with a bufferedreader and then put each readline into a stringbuffer.
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null) {
sb.append(s);
}
// Now use sb.toString() instead of file.toString()
If you are wanting to tokenize the input file then the obvious choice is to use a Scanner. The Scanner class reads a given input stream, and can output either tokens or other scanned types (scanner.nextInt(), scanner.nextLine(), etc).
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("filename.dat"));
while (in.hasNext) {
String s = in.next(); //get the next token in the file
// Now s contains a token from the file
}
}
Check out Oracle's documentation of the Scanner class for more info.
public class FileTokenize {
public static void main(String[] args) throws IOException {
final var lines = Files.readAllLines(Path.of("myfile.txt"));
FileWriter writer = new FileWriter( "output.txt");
String data = " ";
for (int i = 0; i < lines.size(); i++) {
data = lines.get(i);
StringTokenizer token = new StringTokenizer(data);
while (token.hasMoreElements()) {
writer.write(token.nextToken() + "\n");
}
}
writer.close();
}

Categories

Resources