George George - 1 month ago 5
Java Question

Java Input/Output program that works with files

So here's a code which reads input from the file


date.in.txt


Then encrypts by doing the XOR operation between the k character from the text read from the file and the (k%n) character from the key, where is the key length. Then, it outputs it to


date.out.txt


In the second part, it does the reverse, decrypts the text from


date.out.txt


and outputs it to


date.in.txt


Here's an example of the first part:


date.in: Hello World! How are you?

date.out: 43 4 5 2 10 67 54 6 28 9 7 64 73 100 45 12 22 73 15 23 6 65
16 1 16 92


And here is one for the reverse:


date.out.txt: 43 4 5 2 10 67 54 6 28 9 7 64 73 100 45 12 22 73 15 23 6 65
16 1 16 92

date.in.txt: Hello World! How are you?


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws FileNotFoundException
{Scanner scan=new Scanner(System.in);


File file = new File("date.in.txt");
File file2 = new File("date.out.txt");


String [] s= new String[100];
String S= new String();
for(int i=0;i<100;i++)
s[i]=new String();
int nr=0;


int vec[]=new int[100];
int nrvec=0;


String cuv;
System.out.print("Enter key: ");
cuv=scan.nextLine();
System.out.print("\n");
int n=cuv.length();


try
{ Scanner input = new Scanner( file );
while(input.hasNextLine())
{ s[nr++]=input.nextLine();
s[nr++]="\n";} }

catch (FileNotFoundException ex)
{ System.out.printf("ERROR: %s!\n", ex); }


for(int i=0;i<nr;i++)
for(int j=0;j<s[i].length();j++)
{ vec[nrvec++]=s[i].codePointAt(j); }


for(int i=0;i<nrvec;i++)
{ int d=cuv.codePointAt(i%n);
vec[i]=vec[i] ^ d; }


nrvec--;


try
{ PrintWriter output = new PrintWriter(file2);
for(int i=0;i<nrvec;i++)
output.print(vec[i]+" ");
output.close(); }

catch (IOException ex)
{ System.out.printf("ERROR: %s!\n", ex); }


int ok=1; // SECOND PART
if(ok==1)
{System.out.print("Enter key: ");
cuv=scan.nextLine();
System.out.print("\n");
n=cuv.length();

File file3 = new File("date.out.txt");
File file4 = new File("date.in.txt");

nrvec=0;

try
{ Scanner input = new Scanner( file3 );
while(input.hasNext())
{ vec[nrvec++]=input.nextInt(); } }

catch (FileNotFoundException ex)
{ System.out.printf("ERROR: %s!\n", ex); }

int e;
try
{ PrintWriter output = new PrintWriter(file4);
for(int i=0;i<nrvec;i++)
{ e=cuv.codePointAt(i%n);
output.print(vec[i]^e +" ");} // 93
output.close(); }

catch (IOException ex)
{ System.out.printf("ERROR: %s!\n", ex); }


}}}


The problem is that I get an error on line 93, that says:


Exception in thread "main" java.lang.Error: Unresolved compilation
problem: The operator ^ is undefined for the argument type(s) int,
String

at Main.main(Main.java:93)


And I don't know why that is.

Answer

Just change the line at 93 to:

output.print((vec[i]^e) +" ");}

The problem you had was with precedence.

Comments