Encrypt/Decrypt file. ASCII +1 for encryption/decryption - java

I'm trying to read in a file of text, and "encrypt"/convert each letter to +1 from the ASCII table (I also want to "decrypt" so -1 for that). So "a" will become "b", "b" to "c" and so forth. I only need to convert alphabetic letters (Ignore everything else, print them as is). I'm having troubles with this part of the code:
for(int i = 0; i <= words.size(); i++)
{
for(int j = 0; j <= words.get(i).length(); j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch += 1;
morewords.add(ch);
}
fileOut.print(morewords.get(i) + " ");
}
I've figured out how to +1 the char, but I'm not sure how to add that back in to an array or print it out correctly (Since "morewords.add(ch)" is only going to add the char, instead of converting all the chars an adding a string). The "words.get(i).length()" takes the entire length of the array "words", when I just want the length of the string # position "i" in the array, so it throws an error since the length of the array is longer than the string word. I've been stuck on this for hours and I cannot figure it out. I'm thinking maybe I shouldn't read them in as strings and should have read them in as chars and this might have all been simpler?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
ArrayList<Character> morewords = new ArrayList<Character>();
String fileName = ""; //Replace Test with this
File f;
Scanner fileIn;
System.out.println("Please enter a file name for encryption: ");
//fileName = in.nextLine();
fileName = "Test.txt";
try
{
//Build the file and attach a scanner to it
f = new File (fileName);
fileIn = new Scanner (f);
System.out.println(f.exists()); //For errors
int counting = 0;
//Reads in indvidual strings.
for(counting =0; fileIn.hasNext(); counting++)
{
words.add(fileIn.next());
System.out.println(words);
}
PrintWriter fileOut = new PrintWriter ("Backwards.txt");
for(int i = 0; i <= words.size(); i++)
{
for(int j = 0; j <= words.get(i).length(); j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch += 1;
morewords.add(ch);
}
fileOut.print(morewords.get(i) + " ");
}
fileOut.close();
}
catch(FileNotFoundException e)
{
System.out.println("Couldn't find file");
}
}

First in a for loops is right to do
for (int i = 0; i <= words.size()-1; i++){}
if you'r starting at 0 you end at length-1
what i have changed is
PrintWriter fileOut = new PrintWriter("C:/Backwards.txt");
for (int i = 0; i <= words.size()-1; i++)
{
for (int j = 0; j <= words.get(i).length()-1; j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch ++; // +=1
morewords.add(ch);
fileOut.print(ch);
}
fileOut.print(" ");
}
fileOut.close();
and it output right if i have understood right =)
this is my code
public static void main(String[] args) throws Exception
{
BufferedReader inChannel = new BufferedReader(new FileReader("C:/script.txt"));
BufferedWriter outChannel = new BufferedWriter(new FileWriter("C:/output.txt"));
String toParse = "";
while ( (toParse = inChannel.readLine()) != null )
{
String toWrite = "";
for(int i=0; i!=toParse.length();i++)
{
char c = toParse.charAt(i);
if(true) //check if must be encoded or not
{
c++;
toWrite += c;
}
}
outChannel.write(toWrite);
outChannel.newLine();
}
inChannel.close();
outChannel.close();
}
hope helped

Related

problem is that the code print the letters twice

i'm writing a code that read from a file then print the frequency of each alphabetic letter
that is my code
BufferedReader read = new BufferedReader(new FileReader("Text.txt"));
BufferedWriter write = new BufferedWriter(new FileWriter("Output.text"));
String str = "";
str = read.readLine();
str = str.toUpperCase();
while ((str = read.readLine()) != null) {
int[] count = new int[26];
str = str.toUpperCase();
for (int i = 0 ; i < str.length(); i++) {
if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
count[str.charAt(i) - 'A']++;
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] >= 0) {
write.write("The frequency of letter " + (char) ('a' + i) + " = " + count[i]);
write.newLine();
}
}
}
but the problem is that the code print the letters twice even i convert the letters to uppercase.
how can i fix this problem?
thank you so much guys
If your input file has two lines, then the frequencies will be printed "twice" because your file writer is inside the for-each-line loop.
If you're trying to print the character frequencies for the entire file, then try this
try (BufferedReader read = new BufferedReader(new FileReader("Text.txt"));
BufferedWriter write = new BufferedWriter(new FileWriter("Output.text"))) {
// counts for file
int[] count = new int[26];
// read whole file
String str;
while ((str = read.readLine()) != null) {
str = str.toUpperCase();
for (int i = 0 ; i < str.length(); i++) {
if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
count[str.charAt(i) - 'A']++;
}
}
}
// loop counts and write frequencies to output file
for (int i = 0; i < count.length; i++) {
if (count[i] >= 0) {
write.write("The frequency of letter " + (char) ('a' + i) + " = " + count[i]);
write.newLine();
}
}
} catch (Exception e) {
e.printStackTrace();
}
For large files, you may want a long[] count

"Cannot read the array length because "contents" is null" in word unscrambler

I'm trying to program a word unscrambler in java, but I keep getting this error Cannot read the array length because "contents" is null. I tried to use java.io.File, but it also gave me the same error when I tried it.
public static void main(String[] args) throws FileNotFoundException {
String[] contents = txtToString("allwords.txt");
Scanner in = new Scanner(System.in);
System.out.println("Insert your letters");
String input = in.nextLine();
char[] inputArray = input.toCharArray();
for(int i = 0; i < contents.length; i++)
{
for(int j = 0; j < contents[i].length()-1; j++)
{
char[] word = contents[i].toCharArray();
for(int c = 0; c < word.length-1; c++)
{
while(c<inputArray.length)
{
if(word[c]==inputArray[c])
{
word[j]=' ';
for(int s = 0; s < word.length-1;s++)
{
if(word[s]!= ' ')
{
break;
}
else
{
System.out.println("The word is "+contents[i]);
break;
}
}
}
}
}
}
}
}
private static String[] txtToString(String file) {
int count = 0;
try {
Scanner g = new Scanner(new File (file));
while(g.hasNextLine()) {
count++;
}
String[] textToArray = new String[count];
Scanner helloReader = new Scanner(new File(file));
for(int z = 0; z < count; z++) {
textToArray[z] = helloReader.next();
}
return textToArray;
}
catch (FileNotFoundException e){
}
return null;
}
Why am I getting this error?

How to read a String from a txt file and store it into a char array java

So I am trying to read a txt file into a char array and print out the contents, but I only get the first index of the String to print out. The contents of the file are "EADBC"
public static void main(String args[]) throws IOException
{
char [] correctAnswers = new char [20];
String [] studentName = new String[5];
char [][] studentAnswers = new char [20][20];
Scanner sc = new Scanner (System.in);
System.out.println ("Welcome to the Quiz Grading System \n");
System.out.println ("Please Enter the name of the file that contains the correct answers");
Scanner answerFile = new Scanner (new File (sc.next() + ".txt"));
int i = 0;
int fillLvl = 0;
String answer;
while (answerFile.hasNext() )
{
answer = answerFile.next();
correctAnswers[i] = answer.charAt(i);
i++;
fillLvl = i;
}
answerFile.close();
System.out.println("Correct Answers: ");
for(int j = 0; j < fillLvl; j++)
{
System.out.println(correctAnswers[j]);
}
To read from a text file and convert into an array:
File file = new File("C:\\Users\\dell\\Desktop\\rp.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
char[] string1={};
int size = 0;
//reads the string and converts into array
while ((st = br.readLine()) != null){
string1 = st.toCharArray();
size = st.length();
}
//For printing
for(int i=0;i<size;i++){
System.out.println(string1[i]);
}
Inside while loop use like this..
while (answerFile.hasNext() )
{
answer = answerFile.next();
int j = 0;
while(answer != null && !answer.isEmpty() && j < answer.length()){
correctAnswers[i] = answer.charAt(j);
i++;
j++;
fillLvl = i;
}
}
It is always recommended to use FileReader, BufferedReader to perform file operation;
Here you go, read once and print them simple. Don't read them into a string and split them and again to a char.
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("\\path\\to\\file.extension"))
);
int c;
while((c = reader.read()) != -1) {
char character = (char) c;
System.out.println(character);
}
reader.close();

How do you convert a text file into a 2D character array?

I am trying to convert a text file into a 2 dimensional character array. I am part of the way there but the last line of my array is not fully correct. Here's my code:
protected void readMap(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
char[] chars;
int lines=0;
while (br.readLine() != null) {
lines++;
}
File file = new File(fileName);
try (FileReader reader = new FileReader(file)) {
chars = new char[(int) file.length()];
reader.read(chars);
reader.close();
} catch (IOException e) {
}
int columns = ((int) file.length())/lines;
map = new char[lines][columns];
for(int i=0; i<lines;i++){
for(int j=0;j<columns;j++){
map[i][j] = chars[j%columns+i*columns];
}
}
for(int ro=0; ro<map.length; ro++){
for(int colum=0; colum<(map[0].length); colum++){
System.out.print(map[ro][colum]);
}
}
return null;
}
Here's the output:
##########################
#........................#
#.....###........###.....#
#......G..........G......#
#........................#
#...........E............#
#......G.........G.......#
#........G.....G.........#
#..........###...........#
#........................#
#################
^missing #'s here
I'm very confused on why this is occuring. I've tried changing how I print the array but i'm pretty sure its how its to do with how i've converted the 1d 'chars' array to the 2d 'map' array.
I'm really lost so any help would be much appreciated! Thank you.
I'm guessing your file looks something like this
##########################
#........................#
#.....###........###.....#
#......G..........G......#
#........................#
#...........E............#
#......G.........G.......#
#........G.....G.........#
#..........###...........#
#........................#
##########################
If you print the file length, you will see that the file length is 296
As Your code row = 11 and columns = 26
When you are copying to map you are copying up to 11 * 26 = 286
Try the UPDATED code below
public void readMap(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
int lines = 0, columns = 0;
String str;
List<String> lineList = new ArrayList<>();
while ((str = br.readLine()) != null && str.length() != 0) {
lines++;
columns = Math.max(columns, str.length()); // as it's not fixed
lineList.add(str);
}
System.out.println("Row : " + lines);
System.out.println("Columns : " + columns);
char[][] map = new char[lines][columns];
for (int i = 0; i < lines; i++) {
String currentLine = lineList.get(i);
int idx = 0;
for (int j = 0; j < currentLine.length(); j++) {
map[i][j] = currentLine.charAt(idx++);
}
}
for (int r = 0; r < map.length; r++) {
for (int c = 0; c < (map[0].length); c++) {
System.out.print(map[r][c]);
}
System.out.println();
}
}
I've just executed the code and the map prints as expected. The issue may be down to the file itself as that is the uncommon factor.
edit:
The results you have observed is because you may have a new line character, or other special character, at the end of or somewhere in the file. Removing this you should see the consistent map you want.
Alternative
protected static void readMap(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = "";
List<String> lines = new ArrayList<>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
char[][] chars = new char[lines.size()][];
for (int col = 0; col < lines.size(); col++) {
for (int row = 0; row < lines.get(col).length(); row++) {
chars[col] = lines.get(col).toCharArray();
}
}
for (int col = 0; col < chars.length; col++) {
for (int row = 0; row < chars[col].length; row++) {
System.out.print(chars[col][row]);
}
System.out.println();
}
}//My rows and cols may be back to front
Few other notes:
You shouldn't be returning a value from a void method, even null (You'll want to return null if the return type is Void).
Your compiler may complain if you don't initialize chars initially, as mine did. char[] chars = null; would do it in this scenario.

Reading a text file into a char[][] array in Java

I am trying to fill a char[][] array from a text file and I cannot seem to figure out how to do it. I've tried to use .toCharArray() but it doesn't seem to work. If you can give any insight on how to make this work that would be awesome!
String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
for(int row = 0; row < testAnswers.length; row++)
{
for(int col = 0; col < testAnswers[row].length; col++)
{
testAnswers[row][col] = input.next().toCharArray();
}
}
input.close();
The basic problem is that you are trying to assign a character array to something was meant to hold a character. You might think of char[] type as storing the location in memory where characters are recorded, and a char type as the character itself.
When you call toCharArray() on a String, the return type is char[]. It looks like you expect this array to have a single character, like the A, B, C, or D of a multiple-choice test. You could get the first (and only?) character of that array with something like ...toCharArray()[0], but this is wasteful because a new array is created, and characters are copied into it from the source string. It's simpler to use the getCharAt() method on the String directly.
String filename = "ArrayHW2.txt";
char[][] testAnswers = new char[50][5];
try (Scanner input = new Scanner(Paths.get(filename))) {
for(int row = 0; row < testAnswers.length; row++) {
for(int col = 0; col < testAnswers[row].length; col++) {
String token = r.next();
if (token.length() != 1)
throw new IllegalArgumentException("Answers must be one character");
testAnswers[row][col] = token.charAt(0);
}
}
} catch (IOException ex) {
System.err.println("Error reading file: " + ex.getMessage());
System.exit(1);
}
String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
//char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
int counter = 0;
while(scanner.hasNext())
{
copyString(testAnswers[counter], scanner.nextLine());
}
input.close();
its been a while i haven't code in java and im not sure about the methods but consider it a pseudo code .
you can use this copy :
void copyString(char[] arr, String x)
{
int size = x.length();
for (int i=0; i<size; i++){
arr[i] = x.CharAt(i);
}

Categories