When isLetter() method is deleted everything is working fine but when I add it it gives an error. I removed private as it is in the main method. Please help. Thanks in advance.
import java.io.*;
class WordCounter{
public static void main(String args[]){
File file_in_obj = new File("E:/Problems","notes.txt");
File file_out_obj = new File("E:/Problems","notes_sorted.txt");
boolean isLetter(char let){
return ( let>= 'a'&& let <= 'z') || ( let >= 'A' && let <='Z');
}
try(BufferedReader fin = new BufferedReader(new FileReader(file_in_obj));
BufferedWriter fout = new BufferedWriter(new FileWriter(file_out_obj));){
String array[]=new String[500];
char ch[]=new char[25];
int rd,k=0;
String line=null;
/*do{
rd=fin.read();
if(Character.isWhitespace((char)rd))
fout.write(" ");
else if(Character.isLetter((char)rd)){
fout.write((char)rd);
}
}while(rd!=-1); */
while((line=fin.readLine())!=null){
// System.out.println(j++);
String[] tokens = line.split ("\\s+");
for(int i = 0; i < tokens.length; i++){
array[k]=tokens[i];
fout.write(array[k]+" ");
k++;
//System.out.println(tokens.length);
}
}
for(int p=0;p<k;p++){
for(int i=0;i<array[p].length();i++){
if(Character.isLetter(array[p].charAt(i)))
System.out.print(array[p].charAt(i));
}
System.out.println(p);
}
/*for(int j=tokens.length;j>1;j--)
for(int i=0;i<j-1;i++){
if(tokens[i].compareTo(tokens[i+1])>0){
String temp=tokens[i+1];
tokens[i+1]=tokens[i];
tokens[i]=temp;
}
}*/
} catch(IOException e){
System.out.println("I/O Exception occured");
}
}
}
You can't have a method inside another method. Try this:
boolean isLetter(char let){
return ( let>= 'a'&& let <= 'z') || ( let >= 'A' && let <='Z');
}
public static void main(String args[]){
File file_in_obj = new File("E:/Problems","notes.txt");
File file_out_obj = new File("E:/Problems","notes_sorted.txt");
...
}
Related
Exception in thread "main" java.lang.NumberFormatException: For input string: "zwitterionic"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at longestCompound.shortestStringPrefix(longestCompound.java:31)
at longestCompound.main(longestCompound.java:10)
Process finished with exit code 1
public static String readFile() {
String data = null;
try {
File myObj = new File("/Desktop/Github/java-project/Conditional-statement/src/words.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
//System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return data;
}
public static String shortestStringPrefix() {
String[] str = new String[Integer.parseInt(readFile())];
String longestComp = "";
if (str == null || str.length == 0) return longestComp;
int i = 0;
for (char c : str[0].toCharArray()) {
for (int j = 0; j < str.length; j++) {
if (i >= str[j].length() || c != str[j].charAt(i)) return longestComp;
}
longestComp += c;
i++;
}
System.out.println(longestComp);
return longestComp;
}
I have this program and I need it to count the lower and uppercase A's in a data file. I'm not sure what to use between charAt or substring. It's also all in a while loop, and I was getting at the fact that maybe I need to use the next() method? Maybe? I just need to find these characters and count them up in total.
import static java.lang.System.*;
import java.util.*;
import java.io.*;
public class Java2305{
public static void main(String args[]){
new Solution();
}}
class Solution
{
private Scanner fileScan;
Solution()
{
run();
}
void run()
{
int count = 0;
try
{
fileScan = new Scanner(new File("letters01.dat"));
while(fileScan.hasNext() )
{
String getA = fileScan.substring("A");
out.println(getA);
count++;
}
}
catch(Exception e){}
out.println();
out.println("The letter 'A' occurs "+count+" times.");
out.println();
out.println();
}
}
Why are you using Scanner? That is meant for scanning text for delimited tokens using regular expressions, but you are not really using that.
I suggest you use a Reader instead, then you can call its read() method to read individual characters:
int count = 0;
try
{
Reader fileReader = new FileReader("letters01.dat");
/* or:
Reader fileReader = new InputStreamReader(
new FileInputStream("letters01.dat"),
"the file's charset here"
);
*/
int value = fileReader.read();
while (value != -1)
{
char ch = (char) value;
if ((ch == 'a') || (ch == 'A'))
count++;
value = fileReader.read();
}
}
catch(Exception e){}
You can use a BufferedReader to read the file more efficiently:
Reader fileReader = new BufferedReader(new FileReader("letters01.dat"));
/* or:
Reader fileReader = new BufferedReader(
new InputStreamReader(
new FileInputStream("letters01.dat"),
"the file's charset here"
)
);
*/
And then optionally process it line-by-line instead of char-by-char (though you can still do that, too):
int count = 0;
try
{
String line = fileReader.readLine();
while (line != null)
{
for(int i = 0; i < line.length(); ++i)
{
char ch = line.charAt(i);
if ((ch == 'a') || (ch == 'A'))
count++;
}
line = fileReader.readLine();
}
}
catch(Exception e){}
I am trying to develop a basic java program to compare two huge text files and print non matching records .i.e. similar to minus function in SQL. but I am not getting the expected results because all the records are getting printed even though both files are same. Also suggest me whether this approach is performance efficient for comparing two huge text files.
import java.io.*;
public class CompareTwoFiles {
static int count1 = 0 ;
static int count2 = 0 ;
static String arrayLines1[] = new String[countLines("\\Files_Comparison\\File1.txt")];
static String arrayLines2[] = new String[countLines("\\Files_Comparison\\File2.txt")];
public static void main(String args[]){
findDifference("\\Files_Comparison\\File1.txt","\\Files_Comparison\\File2.txt");
displayRecords();
}
public static int countLines(String File){
int lineCount = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(File));
while ((br.readLine()) != null) {
lineCount++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return lineCount;
}
public static void findDifference(String File1, String File2){
String contents1 = null;
String contents2 = null;
try
{
FileReader file1 = new FileReader(File1);
FileReader file2 = new FileReader(File2);
BufferedReader buf1 = new BufferedReader(file1);
BufferedReader buf2 = new BufferedReader(file2);
while ((contents1 = buf1.readLine()) != null)
{
arrayLines1[count1] = contents1 ;
count1++;
}
while ((contents2 = buf2.readLine()) != null)
{
arrayLines2[count2] = contents2 ;
count2++;
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length ; i++) {
String a = arrayLines1[i];
for (int j = 0; j < arrayLines2.length; j++){
String b = arrayLines2[j];
boolean result = a.contains(b);
if(result == false){
System.out.println(a);
}
}
}
}
}
Based upon your explanation you do not need embedded loops
consider
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length && i < arrayLines2.length; i++)
{
String a = arrayLines1[i];
String b = arrayLines2[i];
if(!a.contains(b){
System.out.println(a);
}
}
For the performance wise, you should try to match the size of the files. If the sizes(in bytes) are exactly the same, you might not need to compare them.
I have created a very simple java program (I am only a beginner) that involves data from an array being stored in a text file at the end of the program; this works fine. I am experiencing issues when the program is run again. It should retrieve all the data but doesn't. I have tested it using: System.out.println("test"); The function I am using seems to be starting and the text file has the correct data.
Here is the function:
public static void getArrayData(String [][] array){
try {
Scanner scan2 = new Scanner(new File("arrayData.txt"));
System.out.println(array.length);
for(int i=0; i<array.length; i++)
{
for(int j=0; j<array[i].length; j++)
{
System.out.println("Test 1");
System.out.println(array[i][j]);
if ( ! scan2.hasNext() ) //if there's nothing left to read
return;
array[i][j]=scan2.next();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Test 2");
e.printStackTrace();
}
}
All the function seems to be returning is test null test null test null. Obviously this is not what I want.
I am new to programming so I apologise for the most probably simple issue or stupid mistake. Any help or tips are welcome. If you need any more information please don't hesitate to ask.
Many thanks in advance
Here is the full code:
import java.util.*;
import java.io.*;
public class simpleAI2
{
public static void main (String [] args)
{
int count = 0;
String[][] array = new String [20][4];
simpleAI2.getArrayData(array);
String leaveQ;
int rep = 1;
do
{
int countTwo = 0;
boolean flag = false;
Scanner scanName = new Scanner (System.in);
Scanner scanSport = new Scanner (System.in);
Scanner leave = new Scanner (System.in);
System.out.println("My name is A.I.S.C.M.B.T. What is your name?");
array[count][1] = scanName.nextLine ();
System.out.println("Hi "+array[count][1]+"! What's your favourite sport?");
array[count][2] = scanSport.nextLine ();
String sport = array[count][2];
for(int x = 1;x<rep;x++)
{
if(!array[countTwo][2].equals(null) && array[countTwo][2].equals(array[count][2]))
{
flag = true;
x = 28;
}
else
{
flag = false;
}
countTwo ++;
}
countTwo --;
if(flag == true)
{
System.out.println("I know "+array[countTwo][2]+". It is "+array[countTwo][3]+". My friend "+array[countTwo][1]+" knows it");
}
if(flag == false)
{
System.out.println("I don't know "+array[count][2]+". I only know robot boxing. Robots hit each other until one malfunctions. What is this alien sport you speak of?");
array[count][3] = scanSport.nextLine ();
}
System.out.println("Go again? Type no to leave me :(");
leaveQ = leave.nextLine ();
rep ++;
count ++;
if(leaveQ.equals("no"));
{
simpleAI2.Save(array);
}
}while (!leaveQ.equals("no"));
}
public static void Save(String [][] array){
try {
PrintWriter writer = new PrintWriter(new File("arrayData.txt"));
for(int x=0; x<array.length; x++){
for(int y=0; y<array[x].length; y++){
writer.write(String.valueOf(array[x][y]));
}
writer.println();
}
writer.flush();
writer.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void getArrayData(String [][] array){
try {
Scanner scan2 = new Scanner(new File("arrayData.txt"));
System.out.println(array.length);
for(int i=0; i<array.length; i++)
{
for(int j=0; j<array[i].length; j++)
{
System.out.println("Test 1");
System.out.println(array[i][j]);
if ( ! scan2.hasNext() ) //if there's nothing left to read
return;
array[i][j]=scan2.next();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Test 2");
e.printStackTrace();
}
}
}
I need help about inputting using file (file name is inp2.dat) and outputting using file (file name is out2.dat) in the SAME PROGRAM. Do I use FileInputStream and FileOutputStream in the same class? Please help. Its outputting File Not Found.
import java.io.*;
class MBF
{
static String fileinp="inp2.dat";
public void main()
{
boolean EOF=false;
try
{
FileInputStream fr=new FileInputStream(fileinp);
DataInputStream dr=new DataInputStream(fr);
while(!EOF)
{
try
{
System.out.println("Enter no. of inputs:");
int n=dr.readInt();
int max=0;
for(int a=1;a<=n;a++)
{
System.out.println("Enter:");
int p=dr.readInt();
String str=dr.readLine();
max=max+1;
if(str.charAt(1)==str.charAt(0))
max=max+1;
else
max=max+2;
for(int i=0;i<p-2;i++)
{
char f=str.charAt(i);
char s=str.charAt(i+1);
char t=str.charAt(i+2);
if((f==s)&&(f==t))
max=max+1;
else
if(((f==s)&&(f!=t))||((s==t)&&(f!=t))||((f==t)&&(t!=s)))
max=max+2;
else
max=max+3;
}
max=0;
}
}
catch(EOFException el)
{
System.out.println("end of file");
EOF=true;
}
catch(IOException e)
{
System.err.println(e);
}
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
}
}
There are a few problems throughout. I've made some changes with comments:
class MBF
{
static String fileinp = "C:\\inp2.dat";
public static void main(String[] args) // main method signature was wrong
{
// this line doesn't need to be outside of main, and you aren't using your fileinp string
Scanner in = new Scanner(new File(fileinp));
// added your writer
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\out2.dat"));
System.out.println("Enter no. of inputs:");
int n = in.readInt();
//in.close(); I don't think you meant to do this here.
int max=0;
for(int a = 1; a <= n; a++)
{
System.out.println("Enter:");
// these were originally dr.read... dr is not a variable in scope here. I think you meant in
int p = in.readInt();
String str = in.readLine();
max=max+1;
if(str.charAt(1)==str.charAt(0))
max=max+1;
else
max=max+2;
for(int i = 0; i < p - 2; i++)
{
char f = str.charAt(i);
char s = str.charAt(i + 1);
char t = str.charAt(i + 2);
if ((f == s) && (f == t))
max=max+1;
else if (((f == s) && (f != t)) || ((s == t) && (f != t)) || ((f == t) && (t != s)))
max=max+2;
else
max=max+3;
}
out.write(max + "\n");
max=0;
}
in.close();
out.close();
}
}
Should do what you want.