Simple Java TextEditor program not working - java

So for I was suppose to create a text-editor program where editing is done via a command which, in turn, is executed by the corresponding method. I was suppose to utilize this text-editor program with two files a) A novel .txt file such as tale of two cities and b) a file that contains a list of properly spelled words as for reference for the spellcheck methods
I was to utilized the following:
boolean Find (String x) // Looks for a word "x" in the file and returns true if found or false otherwise.
boolean FindReplace (String x, String y) // looks for the first occurrence of word "x" in the file and replaces it with word "y" if found returning true, false otherwise.
boolean FindInsert (String x, String y) // looks for the first occurrence of word "x" in the file and then insert "y" right after "x", if x is found, returning true, false otherwise.
boolean Delete (String x) // looks for the first occurrence of word "x" in the file and deletes it from the file, returning true if x is found, returning false otherwise.
String spellCheck () // finds the first occurrence of spelling error and returns the misspelled word. If no word is misspelled returns "Spell Check Passed".
void spellCheckAll() // find all misspelled words and output them to the screen.
void save() // saves file with the changes made.
void print() // saves file with the changes and outputs the contents of the file to the screen.
void quit() should save() the file and exit.
10. boolean FindReplaceAll (String x, String y) // looks for all occurrences of word "x" in the file and replace each with word "y" if found returning true, false otherwise.
This is the code I have so far. It compiles. However, when I try to object test any of methods they won't work. For example, my method to find the occurrence of a string within a .txt file will always return false I'm assuming there are some issues either a) my boolean method loops b) there's some issues with the creation of my linked list that I used for my file that's being read in and/or my hash map that I used for my dictionary/reference file. I'm stumped.
package FileEditor;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
public class FileEditor {
static LinkedList<String> list = new LinkedList<String>();
public FileEditor() {
super();
}
public static void readNovelFile() {
String content = new String();
File file = new File("2city10.txt");
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()) {
content = sc.nextLine();
list.add(content);
}
sc.close();
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
}
public static boolean findText(String x) {
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x) || text.equals(x)) {
return true;
} else {
return false;
}
}
return false;
}
public static void findAndReplace(String x, String y) {
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x) || text.equals(x)) {
text = text.replaceAll(x, y);
list.remove(i);
list.add(i, text);
}
}
}
public static void findAndInsert(String x, String y) {
boolean flag = false;
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x) || text.equals(x)) {
if (flag == false)
text = text.replace(x, x + " " + y);
list.remove(i);
list.add(i, text);
}
flag = true;
}
}
public static void delete(String x) {
boolean flag = false;
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x) || text.equals(x)) {
if (flag == false)
text = text.replace(x, "");
list.remove(i);
list.add(i, text);
}
flag = true;
}
}
public static HashSet<String> readWords(String filename) throws FileNotFoundException {
HashSet<String> words = new HashSet<String>();
Scanner in = new Scanner(new File(filename));
// Use any characters other than a-z or A-Z as delimiters
in.useDelimiter("[^a-zA-Z]+");
while (in.hasNext()) {
words.add(in.next().toLowerCase());
}
return words;
}
public static void spellCheck() {
// Read the dictionary and the document
Set<String> dictionaryWords = null;
Set<String> documentWords = null;
boolean flag = false;
try {
dictionaryWords = readWords("EnglishWordList.txt");
documentWords = readWords("2city10.txt");
} catch (FileNotFoundException e) {
}
// Print all words that are in the document but not the dictionary
for (String word : documentWords) {
if (!dictionaryWords.contains(word) && flag == false) {
System.out.println(word);
flag = true;
}
}
}
public static void spellCheckAll() {
// Read the dictionary and the document
Set<String> dictionaryWords = null;
Set<String> documentWords = null;
try {
dictionaryWords = readWords("EnglishWordList.txt");
documentWords = readWords("2city10.txt");
} catch (FileNotFoundException e) {
}
// Print all words that are in the document but not the dictionary
for (String word : documentWords) {
if (!dictionaryWords.contains(word)) {
System.out.println("Misspelled words :" + word);
}
}
}
public static void saveFile() {
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter("2city10.txt"));
for (int i = 0; i < list.size(); i++) {
out.write(list.get(i).toString());
out.write('\n'); // add a new line
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void printFile() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
//out.write('\n'); // add a new line
}
}
public static void menuList() {
System.out.println("\n Enter the Choice ...");
System.out.println("\n Enter 1 to Find ");
System.out.println("\n Enter 2 to FindReplace ");
System.out.println("\n Enter 3 to FindInsert ");
System.out.println("\n Enter 4 to Delete ");
System.out.println("\n Enter 5 to spellCheck ");
System.out.println("\n Enter 6 to spellCheckAll ");
System.out.println("\n Enter 7 to save ");
System.out.println("\n Enter 8 to print ");
System.out.println("\n Enter 9 to quit ");
}
public static void main(String[] args) throws IOException {
readNovelFile();
int choice = 0;
menuList();
Scanner scanner = new Scanner(System.in);
choice = scanner.nextInt();
while (true) {
switch (choice) {
case 1:
{
String input = "";
System.out.println("\nEnter the string to Find ...");
Scanner textscan = new Scanner(System.in);
input = textscan.nextLine();
System.out.println("The String entered exists :" +
findText(input));
menuList();
choice = scanner.nextInt();
break;
}
case 2:
String find = "";
String replace = "";
System.out.println("\nEnter the string to Find ...");
Scanner findScan = new Scanner(System.in);
find = findScan.nextLine();
System.out.println("\nEnter the string to Replace ...");
Scanner replaceScan = new Scanner(System.in);
replace = replaceScan.nextLine();
findAndReplace(find, replace);
menuList();
choice = scanner.nextInt();
break;
case 3:
String findStr = "";
String insStr = "";
System.out.println("\nEnter the string to Find ...");
Scanner findStrScan = new Scanner(System.in);
findStr = findStrScan.nextLine();
System.out.println("\nEnter the string to Insert ...");
Scanner InsertStrScan = new Scanner(System.in);
insStr = InsertStrScan.nextLine();
findAndInsert(findStr, insStr);
menuList();
choice = scanner.nextInt();
break;
case 4:
String delete = "";
System.out.println("\nEnter the string to Delete ...");
Scanner deleteScan = new Scanner(System.in);
delete = deleteScan.nextLine();
delete(delete);
menuList();
choice = scanner.nextInt();
break;
case 5:
System.out.println("\nSpell checking for first occurence ....");
spellCheck();
menuList();
choice = scanner.nextInt();
break;
case 6:
System.out.println("\nSpell checking for All occurences ....");
spellCheckAll();
menuList();
choice = scanner.nextInt();
break;
case 7:
System.out.println("\nSaving the File ....");
saveFile();
menuList();
choice = scanner.nextInt();
break;
case 8:
System.out.println("\nSaving and Printing the File ....");
saveFile();
printFile();
menuList();
choice = scanner.nextInt();
break;
case 9:
System.out.println("\nEXIT MENU ....");
System.exit(0);
break;
}
}
}
}

For your findText always returning false....
public static boolean findText(String x) {
boolean found;
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x)) { // You also dont need that "equals()" here
found=true;
break; // Break loop if text found
} else {
found=false;
}
}
return found;
}
But as mentioned in comments, better way is this:
public static boolean findText(String x) {
boolean found;
for (int i = 0; i < list.size(); i++) {
if(list.get(i).indexOf(x) >= 0){
found = true;
break;
}
else
found = false
}
return found;
}
Another way to do this without manually involving loops is:
public static boolean findText(String x) {
int index = Collections.binarySearch(list, x);
if(index >= 0)
return true;
return false;
}

Related

Java changing upper or lower case by entering CAPS

i want to write a program which at first it gets an integer number which is the number of strings of characters that are supposed to be entered including CAPS and i want that after each CAPS that was entered the rest of characters change in upper or lower case (the default is lower case at first) and finally the program outputs the final string. here is an example:
input:
8
s
f
k
CAPS
h
j
CAPS
p
output:
sfkHJp
here is what i tried so far first i wanted to check out whether this algorithm will work out or not but it actually did not because it does not print the result at all !
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int CAPScounter = 0;
String result = "";
String temp = "";
String singles = "";
boolean CAPSval = false;
if (CAPSval) {
singles = "CAPS";
}
Scanner input = new Scanner(System.in);
int n = input.nextInt();
// System.out.print(n);
while (true) {
if (result.length() == n - CAPScounter) {
break;
}
//temp += input.next();
singles = input.next();
if (CAPSval) {
CAPScounter += 1;
result += temp;
temp = "";
}
}
System.out.print(result);
}
}
This could be a simple solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String result = "";
String singles = "";
boolean isCAPSEnabled = false;
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while (n-- > 0) {
singles = input.next();
if (singles.equals("CAPS")) {
isCAPSEnabled = !isCAPSEnabled; // reverse
} else {
result += isCAPSEnabled ? singles.toUpperCase() : singles.toLowerCase();
}
}
System.out.print(result);
}
}
you can set limit for while
CAPSval if first button second it value equal false or true
if CAPSval == true single change to Upper else toLower
if n == 0 while end and output result
Sorry I update solution you nofify first time button caps and If not button caps you enter upper or lower character then output same with enter
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int CAPScounter = 0;
String result = "";
String singles = "";
boolean CAPSval = false, fistButton = false;
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while (n-- > 0) {
singles = input.next();
if (singles.equals("CAPS")) {
fistButton = true;
CAPSval = !CAPSval;
CAPScounter += 1;
} else {
if (fistButton) {
if (CAPSval)
singles = singles.toUpperCase();
else singles = singles.toLowerCase();
}
result += singles;
}
}
System.out.print(result);
}
}

How to filter out inputs to include only letters not numbers

Im trying to write a program that finds Palindromes in words, when I type a number it says that it is true and I want to prevent numbers from being used in the code. I am new to this so as much explanation you could give me would be welcome! If you could drop an example below that would be very welcome!
import java.util.Scanner;
public class Lab08HC
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
boolean notFinished = false;
do
{
System.out.print("Enter a string ===>> ");
String str = input.nextLine();
System.out.println();
System.out.println("Entered String: " + str);
System.out.println("Palindrome: " + Palindrome.isPal(str));
System.out.println("Almost Palindrome: " + Palindrome.almostPal(str));
System.out.print("Do you wish to repeat this program [Y/N]? ===>> ");
String repeat = input.nextLine();
notFinished = (repeat.equals("Y")) || (repeat.equals("y"));
System.out.println();
}
while (notFinished);
}
}
class Palindrome
{
public static boolean isPal(String s)
{
s = s.toUpperCase();
String reverse = new StringBuffer(s).reverse().toString();
if(reverse.equals(s))
{
return true;
}
else
{
return false;
}
}
private static boolean isLetter(String letter)
{
letter = letter.toUpperCase();
int x = Integer.parseInt(letter);
char character = letter.charAt(x);
if(character >= 65 || character <= 90)
{
return true;
}
else
{
return false;
}
}
private static String purge(String s)
{
String purged = "";
s = s.toUpperCase();
for(int x = 0; x < s.length(); x++)
{
String letter = s.substring(x,x+1);
char character = s.charAt(x);
if(Character.isLetter(character))
{
purged = purged + letter;
}
}
return purged;
}
public static boolean almostPal(String s)
{
s = purge(s.toUpperCase());
String reverse = new StringBuffer(s).reverse().toString();
if(reverse.equals(s))
{
return true;
}
else
{
return false;
}
}
}

Java--I get an infinite loop when attempting to run my alphabetizer program. I can't seem to find the error

The code runs correctly until the for-loops. That's really all to it; I just can't seem to figure out why I'm getting an infinite loop. I've just been trying to sort the word "May" and "Code", so it outputs [Code, May].
import java.util.*;
public class Alphabetical
{
public static void main(String[]args)
{
List<String>words = new ArrayList();
String word = "";
while(!word.equals("stop"))
{
Scanner s = new Scanner(System.in);
System.out.println("Enter a word. Enter 'stop' when finished.");
word = s.nextLine();
words.add(word);
}
words.remove(words.size()-1);
System.out.print(words);
String temp = "";
boolean breakthis = false ;
for(int i = words.size()-1; i >= 1;i--)
{
if(breakthis)
break;
temp = words.get(i);
for(int j = 0;j < words.size();i++)
{
if(temp.charAt(0) == words.get(j).charAt(0))
{
breakthis = true;
break;
}
if(temp.charAt(0) > words.get(j).charAt(0))
{
words.add(j, temp);
words.remove(words.size()-1);
i = words.size()-1;
break;
}
}
}
System.out.print(words);
}
}

NullPointerException, Reservation Seat using Array [duplicate]

This question already has answers here:
java multi-dimensional array fails with a nullpointerexception
(3 answers)
Closed 3 years ago.
can someone look into this code? I have been receiving this error
Exception in thread "main" java.lang.NullPointerException
at project.Project.IsOccupied(Project.java:80)
at project.Project.ReserveSeat(Project.java:51)
at project.Project.main(Project.java:142)
I don't know what's wrong I've done. I have been doing a reservation seat using an array. I'm trying to reserve a seat and check if the seat number entered is occupied or if all the seats are occupied.
package project;
import java.util.*;
import java.io.*;
public class Project {
static String MSR[][] = new String [10][3], Name, SeatNo, Reserved;
static Scanner user = new Scanner(System.in);
static boolean IsEmpty(){
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
if (MSR[i][1] != null) {
return false;
}
}
}
return true;
}
static boolean IsFull(){
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
if ((MSR[i][2]) == null) {
return false;
}
}
}
return true;
}
static void ReserveSeat()throws IOException{
PrintWriter save = new PrintWriter("MovieSeats.txt");
if(IsFull()){
System.out.println("All seats are occupied");
}
else {
System.out.print("Enter seat number to reserved: ");
SeatNo = user.next();
if (IsOccupied(SeatNo)) {
int RSeatNo = Integer.parseInt(SeatNo);
MSR[RSeatNo][1]=SeatNo;
save.print(SeatNo);
System.out.print("Enter name: ");
Name=user.next();
MSR[RSeatNo][0]=Name;
save.print(Name);
Reserved="X";
MSR[RSeatNo][2]=Reserved;
save.print(Reserved);
}
else {
System.out.println("Seat is occupied");
}
}
}
static boolean IsOccupied(String Seat) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
if (MSR[i][1].equals(Seat)) {
MSR[i][2]="X";
return true;
}
}
}
return false;
}
static void displayList(){
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader("MovieSeats.txt");
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException e)
{
System.out.println("Error reading file name");
}
}
public static void main (String[]args) throws IOException {
String yn;
do{
System.out.println("\t\tMOVIE SEAT RESERVATION");
System.out.println("===========================================================");
System.out.println("\t\tA. Reserve Seat");
System.out.println("\t\tB. Cancel Reserve Seat");
System.out.println("\t\tD. Display List of Reserved Seat ");
System.out.println("\t\tE. Clear Seats");
System.out.println("\t\tF. Quit");
System.out.println("===========================================================");
System.out.println();//SPACE
System.out.print("Enter a valid input: ");
String choice = user.next();
switch(choice.toUpperCase()){
case "A":
ReserveSeat();
break;
case "B":
break;
case "C":
break;
case "D":
displayList();
break;
case "E":
break;
case "F":
System.exit(0);
break;
default:
System.err.println("Invalid Input, Please try again.");
break;
}
System.out.print("Do you want to try again? ");
yn= user.next();
}
while(yn.equalsIgnoreCase("Y"));
}
}
The following line of code if (MSR[i][1].equals(Seat)) in the IsOcupied method throws the NullPointerException. You are calling .equals method on MSR[i][1] which contains null.
You have to assign a value to that element before calling .equals on it. You could check whether the element is null, and if it is, return false (=the seat is not occupied yet).
static boolean IsOccupied(String Seat) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
if (MSR[i][1] != null && MSR[i][1].equals(Seat)) {
MSR[i][2]="X";
return true;
}
}
}
return false;
}
The null check will be evaluated first, so if MSR[i][1] != null returns false, then the right hand operand of the AND (&&) operator won't be evaluated. That means you won't be checking .equals on a null anymore.
in if block in IsOccupied method use Seat.equals(MSR[i][1]) instead of using MSR[i][1].equals(Seat). array elements are initially null which produces NullPointerException at this line when trying to execute equalsmethod.

Determining a Palindrome using Stack and Queue in java

Here I am trying to determine if a word or phrase is a palindrome by using stacks and queues depending on the phrase I write in.
What it is doing is that it says that everything is a palindrome and writes "Palindrome" by how many letters it has.
I'm guessing that I need to add something between the last for loop and the while loop, but I'm not sure what.
public class CheckPalindrome {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.toLowerCase().equals("quit")) {
break;
}
Stack<Character> stack = new Stack<Character>();
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < line.length(); i++) {
stack.push(line.charAt(i));
}
for (int i = line.length() - 1; i >= 0; i--) {
queue.add(line.charAt(i));
}
while (!queue.isEmpty()) {
if (queue.remove().equals(stack.pop())) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
}
}
I made some very minor modifications (first to fix one of your for loops, and second to prevent your "Palindrome/Not a Palindrome" message from printing once for every character in the input) to your code to get it to work:
import java.util.Stack;
import java.util.LinkedList;
import java.util.Queue;
import java.io.*;
class Palindrome {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.toLowerCase().equals("quit")) {
break;
}
Stack<Character> stack = new Stack<Character>();
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < line.length(); i++) {
stack.push(line.charAt(i));
}
for (int i = 0; i < line.length(); i++) {
queue.add(line.charAt(i));
}
boolean isPalindrome=true;
while (!queue.isEmpty()) {
if (queue.remove().equals(stack.pop())) {
continue;
} else {
isPalindrome=false;
break;
}
}
if (!isPalindrome) {
System.out.println("Not a Palindrome");
} else {
System.out.println("Palindrome");
}
}
}
}
You need to put the characters into each of the stack and the queue in the same order. The point of using both is that one reverses the order and the other doesn't. Reversing the order yourself on one of them, as you are doing now, negates that.
Incase it's of interest, here's a variation on your approach using a Deque<E> as opposed to a Stack and Queue separately. A Deque is just a double ended queue (i.e. operates as both).
public static boolean isPalindrome(String word) {
boolean isPalindrome = word.length() == 1;
if (!isPalindrome) {
Deque<Character> wordDeque = new LinkedList<>();
for (Character c : word.toCharArray()) {
wordDeque.add(Character.toLowerCase(c));
}
isPalindrome = true;
while (isPalindrome && wordDeque.size() > 1) {
isPalindrome = wordDeque.pollFirst().compareTo(wordDeque.pollLast()) == 0;
}
}
return isPalindrome;
}
Here is new Solution. Try this one. If any modification ,let me know.
package Stack;
public class pallindrome {
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
void pushh(int new_Data) {
stack.push(new_Data);
}
void enquee(int new_Data) {
queue.add(new_Data);
}
int popStack(){
return stack.pop();
}
int dequeueQueue() {
return queue.remove();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
scan.close();
// Convert input String to an array of characters:
char[] s = input.toCharArray();
// Create a Solution object:
pallindrome p = new pallindrome();
// Enqueue/Push all Integer to their respective data structures:
for(int i=0;i<input.length();i++)
{
p.pushh(i);
p.enquee(i);
}
// Pop/Dequeue the chars at the head of both data structures and compare them:
boolean isPalindrome = true;
for ( i = 0; i < s.length/2; i++) {
if (p.popStack() != p.dequeueQueue()) {
isPalindrome = false;
break;
}
}
//Finally, print whether string s is palindrome or not.
System.out.println( "The Integer, " + input + ", is "
+ ( (!isPalindrome) ? "not a palindrome." : "a palindrome." ) );
}
}
Using both stack and queue together for checking palindrome in JAVA
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the String:: ");
String real = input.nextLine();
Queue q = new LinkedList();
Stack st = new Stack();
for(int i=0; i<=real.length()-1; i++) {
q.add(real.charAt(i));
}
for(int i=0; i<real.length(); i++) {
st.push(real.charAt(i));
}
if(q.remove().equals(st.pop())) {
System.out.println("Palindrom");
}else {
System.out.println("Not Palindrom");
}
}
}

Categories

Resources