From c69964051818de71dd55170e84d30d5133610a9b Mon Sep 17 00:00:00 2001 From: pants Date: Wed, 18 Mar 2026 00:39:22 -0700 Subject: [PATCH] init --- MineSweeper.java | 99 ++ Music.java | 132 ++ MusicPlaylist.java | 95 ++ MusicPlaylistMain.java | 43 + Review.java | 42 + Stonks.java | 169 +++ WordStats.java | 75 ++ absurdle/Absurdle.java | 232 ++++ absurdle/dict.txt | 5 + absurdle/dictionary1.txt | 2309 +++++++++++++++++++++++++++++++++ absurdle/dictionary2.txt | 9 + absurdle/dictionary3.txt | 30 + absurdle/small_dict.txt | 9 + helloworld.java | 8 + linter/BlankPrintlnCheck.java | 19 + linter/BreakCheck.java | 23 + linter/Check.java | 11 + linter/Error.java | 43 + linter/Linter.java | 39 + linter/LinterMain.java | 22 + linter/LongLineCheck.java | 21 + linter/TestFile.java | 10 + linter/TestFile.txt | 89 ++ printer.java | 7 + stonks.tsv | 7 + variables.java | 10 + wordcount.java | 18 + 27 files changed, 3576 insertions(+) create mode 100644 MineSweeper.java create mode 100644 Music.java create mode 100644 MusicPlaylist.java create mode 100644 MusicPlaylistMain.java create mode 100644 Review.java create mode 100644 Stonks.java create mode 100644 WordStats.java create mode 100644 absurdle/Absurdle.java create mode 100644 absurdle/dict.txt create mode 100644 absurdle/dictionary1.txt create mode 100644 absurdle/dictionary2.txt create mode 100644 absurdle/dictionary3.txt create mode 100644 absurdle/small_dict.txt create mode 100644 helloworld.java create mode 100644 linter/BlankPrintlnCheck.java create mode 100644 linter/BreakCheck.java create mode 100644 linter/Check.java create mode 100644 linter/Error.java create mode 100644 linter/Linter.java create mode 100644 linter/LinterMain.java create mode 100644 linter/LongLineCheck.java create mode 100644 linter/TestFile.java create mode 100644 linter/TestFile.txt create mode 100644 printer.java create mode 100644 stonks.tsv create mode 100644 variables.java create mode 100644 wordcount.java diff --git a/MineSweeper.java b/MineSweeper.java new file mode 100644 index 0000000..22b8966 --- /dev/null +++ b/MineSweeper.java @@ -0,0 +1,99 @@ +// Miya Natsuhara +// CSE 122 +// 1-5-2024 + +import java.util.*; + +// This program randomly-generates and displays a MineSweeper board according to the difficulty +// level specified by the user. + +public class MineSweeper { + public static final int BOARD_SIZE = 15; // assume a board size board, square + public static final int MINE_INDICATOR = -1; + + public static void main(String[] args) { + int[][] board = new int[BOARD_SIZE][BOARD_SIZE]; + + int difficultyLevel = intro(); // introduce game and get level of difficulty (more mines -> harder) + int numMines = getNumMines(difficultyLevel); + generateMines(numMines, board); // generate coordinates for all the mines + updateCounts(board); // updates the board with all the counts of mines + displayBoard(board); + } + + // Prints a welcome message and prompts the user for difficulty level (between 1 and 10). + // Restricts the user's response to this range and returns the result. + public static int intro() { + Scanner console = new Scanner(System.in); + System.out.println("Welcome to MineSweeper!"); + System.out.print("Please choose game difficulty (NOTE: Difficulty: 1 to 10): "); + int userNum = console.nextInt(); + if (userNum > 10) { + userNum = 10; + } else if (userNum < 1) { + userNum = 1; + } + return userNum; + } + + // Given a difficulty level, returns the number of mines that should be placed on the board. + public static int getNumMines(int difficultyLevel) { + return difficultyLevel * (BOARD_SIZE / 5); // arbitrary + } + + // Given the desired number of mines and game board, randomly places the specified number of + // mines throughout the board. + public static void generateMines(int numMines, int[][] board) { + Random r = new Random(); + for (int i = 0; i < numMines; i++) { + int xCoord = r.nextInt(BOARD_SIZE); + int yCoord = r.nextInt(BOARD_SIZE); + board[xCoord][yCoord] = MINE_INDICATOR; + } + } + + // Given the board and a location (x, y) to check, returns the number of mines adjacent to + // location (x, y). + public static int placeCount(int[][] board, int x, int y) { + int count = 0; + for (int i = -1; i < 2; i++) { + for (int j = -1; j < 2; j++) { + int xCoord = x + i; + int yCoord = y + j; + boolean validSquare = xCoord >= 0 && xCoord < BOARD_SIZE && + yCoord >= 0 && yCoord < BOARD_SIZE; + if (validSquare && board[xCoord][yCoord] == MINE_INDICATOR) { + count++; + } + } + } + return count; + } + + // Given the game board, places the appropriate numbers in non-mine cells throughout the + // board. + public static void updateCounts(int[][] board) { + for (int i = 0; i < BOARD_SIZE; i++) { + for (int j = 0; j < BOARD_SIZE; j++) { + if (board[i][j] != MINE_INDICATOR) { + board[i][j] = placeCount(board, i, j); + } + } + } + } + + // Prints the board to the console, with each square's contents evenly-spaced. + public static void displayBoard(int[][] board) { + for (int i = 0; i < BOARD_SIZE; i++) { + for (int j = 0; j < BOARD_SIZE; j++) { + if (board[i][j] == MINE_INDICATOR) { + System.out.print("X "); + } else { + System.out.print(board[i][j] + " "); + } + } + System.out.println(); + } + System.out.println(); + } +} diff --git a/Music.java b/Music.java new file mode 100644 index 0000000..082c5b0 --- /dev/null +++ b/Music.java @@ -0,0 +1,132 @@ +// Nik Johnson +// 1-7-2024 +// CSE 122 + +import java.util.*; + +public class Music { + public static final String NOTES = "CDEFGAB"; + public static final String SHARP = "♯"; + public static final String FLAT = "♭"; + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + String[][] song = composeSong(scanner); + mostCommonNaturals(song); + System.out.println(Arrays.toString(mostCommonNaturals(song))); + } + +// "parent" method that calls helper methods getSongParams and composeMelodies +// returns 2D array containing user-composed song + + public static String[][] composeSong(Scanner scanner) { + + int[] songParams = getSongParams(scanner); + + return composeMelodies(scanner, songParams[0], songParams[1]); + } + + // get user input on song parameters, return for use with composeMelodies + public static int[] getSongParams(Scanner scanner) { + + System.out.print("Enter the number of melodies: "); + String inputNum = scanner.nextLine(); + int numMelodies = Integer.parseInt(inputNum); + + System.out.print("Enter the length of each melody: "); + String inputLength = scanner.nextLine(); + int lengthMelodies = Integer.parseInt(inputLength); + + + + return new int[] {numMelodies, lengthMelodies}; + } + // iterate through array of dimensions defined by list songParams, storing user-inputted notes as we go + public static String[][] composeMelodies(Scanner scanner, int numMelodies, int lengthMelodies) { + System.out.println(""); + + String[][] songArray = new String[numMelodies][lengthMelodies]; + + for (int n = 0; n < numMelodies; n++) { + + System.out.println("Composing melody #" + (n+1)); + + for (int i = 0; i < lengthMelodies; i++) { + System.out.print(" Enter note #" + (i+1) + ": "); + String note = scanner.nextLine(); + songArray[n][i] = note; + + + if (numMelodies > 1) { + + } else if (lengthMelodies > 1) { + System.out.println(); + } + } + System.out.println(); + } + return songArray; + } + + // parent method, use data from helper methods to assemble output array + public static String[] mostCommonNaturals(String[][] song) { + // new function + + // string array thats # of melodies long -> since there will be that many notes + + String[] notes = NOTES.split(""); + + String[] result = new String[song.length]; + for (int i = 0; i < result.length; i++) { + // get frequency list PER melody + int[] numNaturals = getNumNaturals(song[i]); + + // get largest frequency # in list + + int largestFreq = getLargestFrequency(numNaturals); + + // put note matching that largest frequency (in order of NOTES) into result array + // "CDEFGAB"; + // [0, 1, 2, 1, 2, 0, 0] + // 2 + // result = ["E"] + + for (int n = 0; n < numNaturals.length; n++) { + if (numNaturals[n] == largestFreq) { + result[i] = notes[n]; + break; + } + } + } + + + return result; + } + + // look for frequency of note that appears most frequently in song + public static int getLargestFrequency(int[] numNaturals) { + int freq = 0; + for (int j = 0; j < numNaturals.length; j++) { + if (numNaturals[j] > freq) { + freq = numNaturals[j]; + } + } + return freq; + } + + public static int[] getNumNaturals(String[] melody) { + int[] numNaturals = new int[NOTES.length()]; + + for (int n = 0; n < melody.length; n++) { + String note = melody[n]; + if (note.length() == 1) { + int index = NOTES.indexOf(note); + numNaturals[index]++; + } + + } + return numNaturals; + } + + +} diff --git a/MusicPlaylist.java b/MusicPlaylist.java new file mode 100644 index 0000000..c25e4eb --- /dev/null +++ b/MusicPlaylist.java @@ -0,0 +1,95 @@ +import java.util.*; + +public class MusicPlaylist { + + private Queue playlist; + private Stack history; + + public MusicPlaylist() { + playlist = new LinkedList<>(); + history = new Stack<>(); + } + + // add song to playlist according to user input + // no return + public void addSong(String songToAdd) { + System.out.print("Enter song name: "); + playlist.add(songToAdd); + System.out.println("Successfully added " + songToAdd); + System.out.println(); + System.out.println(); + } + + // play song at the front of the playlist + // no return + public void playSong() { + // if user attempts to play song when playlist is empty, throw exception + if (playlist.isEmpty()) throw new IllegalStateException(); + String songToPlay = playlist.remove(); + System.out.println("Playing song: " + songToPlay); + history.push(songToPlay); + System.out.println(); + System.out.println(); + } + + // print history of played songs + // return unmodified history after printing it + public void printHistory() { + int size = history.size(); + // if there is no history and user attempts to print history, throw exception + if (history.isEmpty()) throw new IllegalStateException(); + String[] historyArray = new String[size]; + if (size != 0) { + for (int i = (size - 1); i >= 0; i--) { + historyArray[i] = history.pop(); + System.out.println(" " + historyArray[i]); + } + for (int n = 0; n < size; n++) { + history.push(historyArray[n]); + } + } + System.out.println(); + System.out.println(); + } + + public void clearHistory() { + playlist.clear(); + } + + // delete from history according to user input, starting either from most recent or oldest history + // return modified history + public void deleteFromHistory(int numToDelete) { + int size = history.size(); + List historyArrayList = new ArrayList<>(); + if (!history.isEmpty()) { + for (int i = 0; i < size; i++) { + historyArrayList.add(history.pop()); + } + } + System.out.println("A positive number will delete from recent history."); + System.out.println("A negative number will delete from the beginning of history."); + System.out.print("Enter number of songs to delete: "); + int absNum = Math.abs(numToDelete); + if (absNum > size) { + throw new IllegalArgumentException(); + } + System.out.println(); + if (size != 0 && absNum != 0) { + if (absNum == size) { + historyArrayList.clear(); + } else if (numToDelete < 0) { + int lastIndex = size - 1; + for (int n = lastIndex; n >= (size - absNum); n--) { + historyArrayList.remove(n); + } + } else if (numToDelete > 0) { + for (int i = 0; i < numToDelete; i++) { + historyArrayList.remove(0); + } + } + } + for (int n = (historyArrayList.size() - 1); n >= 0; n--) { + history.push(historyArrayList.get(n)); + } + } + } diff --git a/MusicPlaylistMain.java b/MusicPlaylistMain.java new file mode 100644 index 0000000..b093b5f --- /dev/null +++ b/MusicPlaylistMain.java @@ -0,0 +1,43 @@ +import java.util.*; + +public class MusicPlaylistMain { + public static void main(String[] args) { + Scanner console = new Scanner(System.in); + System.out.println("Welcome to the CSE 122 Music Playlist!"); + + MusicPlaylist playlist = new MusicPlaylist(); + + String destination = navigator(console); + while (!destination.equalsIgnoreCase("Q")) { + if (destination.equalsIgnoreCase("A")) { + String songToAdd = console.nextLine(); + playlist.addSong(songToAdd); + } else if (destination.equalsIgnoreCase("P")) { + playlist.playSong(); + } else if (destination.equalsIgnoreCase("Pr")) { + playlist.printHistory(); + } else if (destination.equalsIgnoreCase("C")) { + playlist.clearHistory(); + } else if (destination.equalsIgnoreCase("D")) { + int numToDelete = Integer.parseInt(console.nextLine()); + playlist.deleteFromHistory(numToDelete); + } + destination = navigator(console); + } + } + + // menu function, called initially and after any other functions + // return String for use in main menu loop + public static String navigator(Scanner console) { + System.out.println("(A) Add song"); + System.out.println("(P) Play song"); + System.out.println("(Pr) Print history"); + System.out.println("(C) Clear history"); + System.out.println("(D) Delete from history"); + System.out.println("(Q) Quit"); + System.out.println(); + System.out.print("Enter your choice: "); + String destination = console.nextLine(); + return destination; + } +} diff --git a/Review.java b/Review.java new file mode 100644 index 0000000..cd449b4 --- /dev/null +++ b/Review.java @@ -0,0 +1,42 @@ +import java.util.*; + +public class Review { + // Create a Map of students in section to their favorite word/movie/song/etc + // Then, edit and print out the Map + + public static void main(String[] args) { + // Create the Map (do you want it to do ordered?) + Map favorites = new TreeMap<>(); + // Add key/value pairs to the Map + favorites.put("me", "キュ毛付きさぼたじ"); + favorites.put("nik", "warp star"); + favorites.put("andy", "none"); + System.out.println(favorites); + // Delete one of the entries from the Map + favorites.remove("andy"); + // Override one of the values + favorites.put("boner", "balls"); + // Loop over the Map and print out all the values seperated by a comma and space + // Before printing - hypothesize what the output will look like! + for (String key : favorites.keySet()) { + System.out.print(favorites.get(key) + ", "); + } + + System.out.println(); + + Set intset = new HashSet<>(); + + for (int i = 0; i < 10; i++) { + intset.add(i); + } + + System.out.println(intset); + + Stack s = new Stack<>(); + System.out.println(s.isEmpty()); + + MusicPlaylist p1 = new MusicPlaylist(); + p1.addSong("ohyeahyeah"); + p1.playSong(); + } +} diff --git a/Stonks.java b/Stonks.java new file mode 100644 index 0000000..de99ba5 --- /dev/null +++ b/Stonks.java @@ -0,0 +1,169 @@ +// Nik Johnson +// 1-25-2024 +// TA: Andy Ruan +// modified attempt for resubmission 1 + +import java.util.*; +import java.io.*; + +// stock simulator +// stock market sandbox which reads fake market data from "stonks.tsv", and allows users to: +// buy and sell stocks, and save their portfolio to a file. +// upon quitting, the value of the users portfolio will be calculated and printed. + +public class Stonks { + public static final String STOCKS_FILE_NAME = "stonks.tsv"; + + public static void main(String[] args) throws FileNotFoundException { + Scanner console = new Scanner(System.in); + File stonks = new File(STOCKS_FILE_NAME); + Scanner stonklines = new Scanner(stonks); + int numStocks = Integer.parseInt(stonklines.nextLine()); + + String[] tickers = new String[numStocks]; + Double[] prices = new Double[numStocks]; + Double[] portfolio = new Double[numStocks]; + + // fill portfolio with zeros to prevent null exceptions + // without using Arrays.fill() + for (int n = 0; n < numStocks; n++) { + portfolio[n] = 0.0; + } + + String info = stonklines.nextLine(); + + // this runs once. + // functionally decomposing it would add lines of code, but no functionality. + int index = 0; + while (stonklines.hasNextLine()) { + String nextline = stonklines.nextLine(); + Scanner token = new Scanner(nextline); + tickers[index] = token.next(); + prices[index] = token.nextDouble(); + index++; + } + + System.out.println("Welcome to the CSE 122 Stocks Simulator!"); + System.out.println("There are " + numStocks + " stocks on the market:"); + + for (int i = 0; i < numStocks; i++) { + System.out.println(tickers[i] + ": " + prices[i]); + + } + + System.out.println(); + String next = navigator(console); + + while (!next.equals("quit")) { + if (next.equals("buy")) { + portfolio = buy(console, tickers, prices, portfolio); + } else if (next.equals("sell")) { + portfolio = sell(console, tickers, prices, portfolio); + } else if (next.equals("save")) { + save(console, tickers, portfolio); + } else { + System.out.println("Invalid choice: " + next); + System.out.println("Please try again"); + System.out.println(); + } + next = navigator(console); + } + + Double value = quit(prices, portfolio); + System.out.println("Your portfolio is currently valued at: $" + value); + } + + // menu method, called for inital prompt and then after using any other methods + // returns String which decides which function to use + + public static String navigator(Scanner console) { + System.out.println("Menu: buy, sell, save, quit"); + System.out.print("Enter your choice: "); + String destination = console.next(); + return destination; + } + + // add (buy) to portfolio according to user input, no lower than $5.0 + // takes console scanner, and all data arrays defined in main lines 24-26 + // return modified portfolio with MORE shares than before + + public static Double[] buy(Scanner console, String[] tickers, + Double[] prices, Double[] portfolio) { + System.out.print("Enter the stock ticker: "); + String order = console.next(); + System.out.print("Enter your budget: "); + Double budget = console.nextDouble(); + + if (budget >= 5.0) { + for (int i = 0; i < tickers.length; i++) { + if (order.equals(tickers[i])) { + portfolio[i] += (budget / prices[i]); + System.out.println("You successfully bought " + tickers[i] + "."); + System.out.println(); + } + } + } else { + System.out.println("Budget must be at least $5"); + System.out.println(); + } + return portfolio; + } + + // subtract (sell) from portfolio according to user input, if they have enough to sell + // takes console scanner, and all data arrays defined in main lines 24-26 + // return modified portfolio with LESS shares than before + + public static Double[] sell(Scanner console, String[] tickers, + Double[] prices, Double[] portfolio) { + System.out.print("Enter the stock ticker: "); + String ticker = console.next(); + System.out.print("Enter the number of shares to sell: "); + Double sellAmount = console.nextDouble(); + for (int i = 0; i < tickers.length; i++) { + if (ticker.equals(tickers[i])) { + if (sellAmount > portfolio[i]) { + System.out.println("You do not have enough shares of " + ticker + " to sell " + sellAmount + " shares."); + System.out.println(); + } else if (sellAmount <= portfolio[i]) { + portfolio[i] = portfolio[i] - sellAmount; + System.out.println("You successfully sold " + sellAmount + " shares of " + ticker + "."); + System.out.println(); + } + } + } + return portfolio; + } + + // write current portfolio to file named according to user input + // takes console scanner, array of tickers and the users current portfolio + + public static void save(Scanner console, String[] tickers, Double[] portfolio) throws FileNotFoundException { + System.out.print("Enter new portfolio file name: "); + String fileName = console.next(); + System.out.println(); + File saveData = new File(fileName); + PrintStream savePortfolio = new PrintStream(saveData); + for (int i = 0; i < tickers.length; i++) { + if (portfolio[i] != 0.0) { + savePortfolio.println(tickers[i] + " " + portfolio[i]); + } + } + } + + // upon quitting, calculate total portfolio value using- + // -values in portfolio and current market prices + // return total value for printing + + public static double quit(Double[] prices, Double[] portfolio) { + System.out.println(); + Double portfolioValue = 0.0; + for (int i = 0; i < prices.length; i++) { + if (portfolio[i] != null) { + Double currValue = prices[i]*portfolio[i]; + portfolioValue += currValue; + } else portfolioValue += 0; + } + return portfolioValue; + } + +} diff --git a/WordStats.java b/WordStats.java new file mode 100644 index 0000000..22c3c76 --- /dev/null +++ b/WordStats.java @@ -0,0 +1,75 @@ +import java.util.*; + +public class WordStats { + public static void main(String[] args) { + Scanner console = new Scanner(System.in); + + String[] words = getListOfWords(console); + System.out.println("Words: " + Arrays.toString(words)); + + String longestWord = getLongestWord(words); + System.out.println("Longest word: " + longestWord); + + vowelSearch(words); + } + + + /* + * ask user for number of words to test, and store that (integer) as "number_of_Words" + * loop for that number of iterations, adding each word to array "words" + */ + public static String[] getListOfWords(Scanner console) { + System.out.print("How many words? "); + int numbers_of_WORDS = console.nextInt(); + + String[] words = new String[numbers_of_WORDS]; + + for (int i = 0; i < numbers_of_WORDS; i++) { + System.out.print("Next word? "); + String Word = console.next(); + words[i] = Word; + } + + return words; + } + + /* + * iterate through array "words" + * return longest word + */ + + public static String getLongestWord(String[] words) { + String longestWord = ""; + for (int i = 0; i < words.length; i++) { + String curr = words[i]; + if (curr.length() > longestWord.length()) { + longestWord = curr; + } + } + return longestWord; + + } + + /* + * test first character of each word in array "words" + * if first char is any defined in upper or lower case vowels, print it + */ + + public static void vowelSearch(String[] words) { + char[] uppercaseVowels = { 'A', 'E', 'I', 'O', 'U' }; + char[] lowercaseVowels = { 'a', 'e', 'i', 'o', 'u' }; + System.out.println("Words beginning with vowels: "); + for (int i = 0; i < words.length; i++) { + String curr = words[i]; + char firstChar = curr.charAt(0); + for (int j = 0; j < uppercaseVowels.length; j++) { + if (firstChar == uppercaseVowels[j] || firstChar == lowercaseVowels[j]) { + System.out.println(" " + curr); + } + } + } + + } + + +} diff --git a/absurdle/Absurdle.java b/absurdle/Absurdle.java new file mode 100644 index 0000000..61443af --- /dev/null +++ b/absurdle/Absurdle.java @@ -0,0 +1,232 @@ +// Nik Johnson +// 2-11-2024 +// TA: Andy Ruan + +/* +absurd wordle-like game +instead of guessing one word, prolongs game as long as possible by +testing users guess against every word in selected dictionary, and +choosing the largest set of words associated with a possible pattern +for the users guess. the game only ends when the next set to be +considered is narrowed down to one, and the user guesses it. +*/ + +import java.util.*; +import java.io.*; + +public class Absurdle { + public static final String GREEN = "🟩"; + public static final String YELLOW = "🟨"; + public static final String GRAY = "⬜"; + + // [[ ALL OF MAIN PROVIDED ]] + public static void main(String[] args) throws FileNotFoundException { + Scanner console = new Scanner(System.in); + System.out.println("Welcome to the game of Absurdle."); + + System.out.print("What dictionary would you like to use? "); + String dictName = console.next(); + + System.out.print("What length word would you like to guess? "); + int wordLength = console.nextInt(); + + List contents = loadFile(new Scanner(new File(dictName))); + Set words = pruneDictionary(contents, wordLength); + + List guessedPatterns = new ArrayList<>(); + while (!isFinished(guessedPatterns)) { + System.out.print("> "); + String guess = console.next(); + String pattern = record(guess, words, wordLength); + guessedPatterns.add(pattern); + System.out.println(": " + pattern); + System.out.println(); + } + System.out.println("Absurdle " + guessedPatterns.size() + "/∞"); + System.out.println(); + printPatterns(guessedPatterns); + console.close(); + } + + // [[ PROVIDED ]] + // Prints out the given list of patterns. + // - List patterns: list of patterns from the game + public static void printPatterns(List patterns) { + for (String pattern : patterns) { + System.out.println(pattern); + } + } + + // [[ PROVIDED ]] + // Returns true if the game is finished, meaning the user guessed the word. Returns + // false otherwise. + // - List patterns: list of patterns from the game + public static boolean isFinished(List patterns) { + if (patterns.isEmpty()) { + return false; + } + String lastPattern = patterns.get(patterns.size() - 1); + return !lastPattern.contains("⬜") && !lastPattern.contains("🟨"); + } + + // [[ PROVIDED ]] + // Loads the contents of a given file Scanner into a List and returns it. + // - Scanner dictScan: contains file contents + public static List loadFile(Scanner dictScan) { + List contents = new ArrayList<>(); + while (dictScan.hasNext()) { + contents.add(dictScan.next()); + } + return contents; + } + + /* + look through list of words from dictionary, removing words that aren't of + the user specified length. + + takes list of words from user specified dictionary, and user specified word length + + return set of words pruned according to user input + + if the user specified length is less than one, throw IllegalArgumentException + */ + public static Set pruneDictionary(List contents, int wordLength) { + if (wordLength < 1) throw new IllegalArgumentException(); + Set prunedDict = new HashSet<>(); + for (String word : contents) { + if (word.length() == wordLength) { + prunedDict.add(word); + } + } + return prunedDict; + } + + /* + evaluate users guess, looking for the largest set of words that have the pattern + of the guess. if all possible patterns have the same number of words, pick the + first one in alphabetical order. + + takes users guess, set of words determined by pruneDictionary, and length of users guess + + return the pattern associated with the largest set of words + + if the users guess is the wrong length, or there is no words to be guessed, + throw IllegalArgumentException + */ + public static String record(String guess, Set words, int wordLength) { + if (guess.length() != wordLength || words.isEmpty()) { + throw new IllegalArgumentException(); + } + + Map> wordMap = new TreeMap<>(); + for (String word : words) { + String nextPattern = patternFor(word, guess); + if (!wordMap.containsKey(nextPattern)) { + wordMap.put(nextPattern, new HashSet()); + } + wordMap.get(nextPattern).add(word); + } + + Boolean allSameSize = true; + int setSize1 = 0; + + for (String pattern : wordMap.keySet()) { + int size = wordMap.get(pattern).size(); + if (setSize1 == 0) setSize1 = size; + if (setSize1 != size) allSameSize = false; + } + + if (allSameSize) { + for (String pattern : wordMap.keySet()) { + removeAllNonMatching(words, wordMap.get(pattern)); + return pattern; + } + } + + String pattern = ""; + int setSize = 0; + for (String word : wordMap.keySet()) { + int nextSetSize = (wordMap.get(word)).size(); + if (nextSetSize > setSize) { + setSize = nextSetSize; + pattern = word; + } + } + removeAllNonMatching(words, wordMap.get(pattern)); + return pattern; + } + + /* + helper method for record, removes words from next considered set that arent in + the largest set determined in record + + takes next set of words to be considered as determined by record, + which will be used to trim the previous set + + no return + */ + public static void removeAllNonMatching(Set words, Set match) { + Iterator iter = words.iterator(); + while(iter.hasNext()) { + if(!match.contains(iter.next())) { + iter.remove(); + } + } + } + + /* + produce pattern for users guess against every word in set of + considered words. + + takes users guess, and the word to generate a pattern against + + return pattern of colored squares for use in record + */ + public static String patternFor(String word, String guess) { + List splitGuess = new ArrayList<>(); + String pattern = new String(); + for (int i = 0;i < guess.length(); i++) { + String nextChar = Character.toString(guess.charAt(i)); + splitGuess.add(nextChar); + } + + Map wordMap = new HashMap<>(); + for (int j = 0; j < word.length(); j++) { + char wordChar = word.charAt(j); + if (!wordMap.containsKey(wordChar)) { + wordMap.put(wordChar, 1); + } else { + wordMap.put(wordChar, (wordMap.get(wordChar) + 1)); + } + } + + for (int n = 0; n < splitGuess.size(); n++) { + if ((Character.toString(word.charAt(n))).equals(splitGuess.get(n))) { + int currCount = wordMap.get((splitGuess.get(n)).charAt(0)); + wordMap.put(word.charAt(n), (currCount - 1)); + splitGuess.set(n, GREEN); + } + } + + for (int n = 0; n < splitGuess.size(); n++) { + char charToCheck = (splitGuess.get(n)).charAt(0); + if ((wordMap.keySet()).contains(charToCheck) + && wordMap.get(charToCheck) != 0) { + int currCount2 = wordMap.get(charToCheck); + wordMap.put(charToCheck, (currCount2 - 1)); + splitGuess.set(n, YELLOW); + } + } + + for (int n = 0; n < splitGuess.size(); n++) { + if ((splitGuess.get(n)).length() == 1) { + splitGuess.set(n, GRAY); + } + } + + for (int i = 0; i < splitGuess.size(); i++) { + pattern += splitGuess.get(i); + } + return pattern; + } +} diff --git a/absurdle/dict.txt b/absurdle/dict.txt new file mode 100644 index 0000000..196d2cd --- /dev/null +++ b/absurdle/dict.txt @@ -0,0 +1,5 @@ +argh +beta +flew +crew +else diff --git a/absurdle/dictionary1.txt b/absurdle/dictionary1.txt new file mode 100644 index 0000000..e6be740 --- /dev/null +++ b/absurdle/dictionary1.txt @@ -0,0 +1,2309 @@ +cigar +rebut +sissy +humph +awake +blush +focal +evade +naval +serve +heath +dwarf +model +karma +stink +grade +quiet +bench +abate +feign +major +death +fresh +crust +stool +colon +abase +marry +react +batty +pride +floss +helix +croak +staff +paper +unfed +whelp +trawl +outdo +adobe +crazy +sower +repay +digit +crate +cluck +spike +mimic +pound +maxim +linen +unmet +flesh +booby +forth +first +stand +belly +ivory +seedy +print +yearn +drain +bribe +stout +panel +crass +flume +offal +agree +error +swirl +argue +bleed +delta +flick +totem +wooer +front +shrub +parry +biome +lapel +start +greet +goner +golem +lusty +loopy +round +audit +lying +gamma +labor +islet +civic +forge +corny +moult +basic +salad +agate +spicy +spray +essay +fjord +spend +kebab +guild +aback +motor +alone +hatch +hyper +thumb +dowry +ought +belch +dutch +pilot +tweed +comet +jaunt +enema +steed +abyss +growl +fling +dozen +boozy +erode +world +gouge +click +briar +great +altar +pulpy +blurt +coast +duchy +groin +fixer +group +rogue +badly +smart +pithy +gaudy +chill +heron +vodka +finer +surer +radio +rouge +perch +retch +wrote +clock +tilde +store +prove +bring +solve +cheat +grime +exult +usher +epoch +triad +break +rhino +viral +conic +masse +sonic +vital +trace +using +peach +champ +baton +brake +pluck +craze +gripe +weary +picky +acute +ferry +aside +tapir +troll +unify +rebus +boost +truss +siege +tiger +banal +slump +crank +gorge +query +drink +favor +abbey +tangy +panic +solar +shire +proxy +point +robot +prick +wince +crimp +knoll +sugar +whack +mount +perky +could +wrung +light +those +moist +shard +pleat +aloft +skill +elder +frame +humor +pause +ulcer +ultra +robin +cynic +aroma +caulk +shake +dodge +swill +tacit +other +thorn +trove +bloke +vivid +spill +chant +choke +rupee +nasty +mourn +ahead +brine +cloth +hoard +sweet +month +lapse +watch +today +focus +smelt +tease +cater +movie +saute +allow +renew +their +slosh +purge +chest +depot +epoxy +nymph +found +shall +harry +stove +lowly +snout +trope +fewer +shawl +natal +comma +foray +scare +stair +black +squad +royal +chunk +mince +shame +cheek +ample +flair +foyer +cargo +oxide +plant +olive +inert +askew +heist +shown +zesty +hasty +trash +fella +larva +forgo +story +hairy +train +homer +badge +midst +canny +fetus +butch +farce +slung +tipsy +metal +yield +delve +being +scour +glass +gamer +scrap +money +hinge +album +vouch +asset +tiara +crept +bayou +atoll +manor +creak +showy +phase +froth +depth +gloom +flood +trait +girth +piety +payer +goose +float +donor +atone +primo +apron +blown +cacao +loser +input +gloat +awful +brink +smite +beady +rusty +retro +droll +gawky +hutch +pinto +gaily +egret +lilac +sever +field +fluff +hydro +flack +agape +voice +stead +stalk +berth +madam +night +bland +liver +wedge +augur +roomy +wacky +flock +angry +bobby +trite +aphid +tryst +midge +power +elope +cinch +motto +stomp +upset +bluff +cramp +quart +coyly +youth +rhyme +buggy +alien +smear +unfit +patty +cling +glean +label +hunky +khaki +poker +gruel +twice +twang +shrug +treat +unlit +waste +merit +woven +octal +needy +clown +widow +irony +ruder +gauze +chief +onset +prize +fungi +charm +gully +inter +whoop +taunt +leery +class +theme +lofty +tibia +booze +alpha +thyme +eclat +doubt +parer +chute +stick +trice +alike +sooth +recap +saint +liege +glory +grate +admit +brisk +soggy +usurp +scald +scorn +leave +twine +sting +bough +marsh +sloth +dandy +vigor +howdy +enjoy +valid +ionic +equal +unset +floor +catch +spade +stein +exist +quirk +denim +grove +spiel +mummy +fault +foggy +flout +carry +sneak +libel +waltz +aptly +piney +inept +aloud +photo +dream +stale +vomit +ombre +fanny +unite +snarl +baker +there +glyph +pooch +hippy +spell +folly +louse +gulch +vault +godly +threw +fleet +grave +inane +shock +crave +spite +valve +skimp +claim +rainy +musty +pique +daddy +quasi +arise +aging +valet +opium +avert +stuck +recut +mulch +genre +plume +rifle +count +incur +total +wrest +mocha +deter +study +lover +safer +rivet +funny +smoke +mound +undue +sedan +pagan +swine +guile +gusty +equip +tough +canoe +chaos +covet +human +udder +lunch +blast +stray +manga +melee +lefty +quick +paste +given +octet +risen +groan +leaky +grind +carve +loose +sadly +spilt +apple +slack +honey +final +sheen +eerie +minty +slick +derby +wharf +spelt +coach +erupt +singe +price +spawn +fairy +jiffy +filmy +stack +chose +sleep +ardor +nanny +niece +woozy +handy +grace +ditto +stank +cream +usual +diode +valor +angle +ninja +muddy +chase +reply +prone +spoil +heart +shade +diner +arson +onion +sleet +dowel +couch +palsy +bowel +smile +evoke +creek +lance +eagle +idiot +siren +built +embed +award +dross +annul +goody +frown +patio +laden +humid +elite +lymph +edify +might +reset +visit +gusto +purse +vapor +crock +write +sunny +loath +chaff +slide +queer +venom +stamp +sorry +still +acorn +aping +pushy +tamer +hater +mania +awoke +brawn +swift +exile +birch +lucky +freer +risky +ghost +plier +lunar +winch +snare +nurse +house +borax +nicer +lurch +exalt +about +savvy +toxin +tunic +pried +inlay +chump +lanky +cress +eater +elude +cycle +kitty +boule +moron +tenet +place +lobby +plush +vigil +index +blink +clung +qualm +croup +clink +juicy +stage +decay +nerve +flier +shaft +crook +clean +china +ridge +vowel +gnome +snuck +icing +spiny +rigor +snail +flown +rabid +prose +thank +poppy +budge +fiber +moldy +dowdy +kneel +track +caddy +quell +dumpy +paler +swore +rebar +scuba +splat +flyer +horny +mason +doing +ozone +amply +molar +ovary +beset +queue +cliff +magic +truce +sport +fritz +edict +twirl +verse +llama +eaten +range +whisk +hovel +rehab +macaw +sigma +spout +verve +sushi +dying +fetid +brain +buddy +thump +scion +candy +chord +basin +march +crowd +arbor +gayly +musky +stain +dally +bless +bravo +stung +title +ruler +kiosk +blond +ennui +layer +fluid +tatty +score +cutie +zebra +barge +matey +bluer +aider +shook +river +privy +betel +frisk +bongo +begun +azure +weave +genie +sound +glove +braid +scope +wryly +rover +assay +ocean +bloom +irate +later +woken +silky +wreck +dwelt +slate +smack +solid +amaze +hazel +wrist +jolly +globe +flint +rouse +civil +vista +relax +cover +alive +beech +jetty +bliss +vocal +often +dolly +eight +joker +since +event +ensue +shunt +diver +poser +worst +sweep +alley +creed +anime +leafy +bosom +dunce +stare +pudgy +waive +choir +stood +spoke +outgo +delay +bilge +ideal +clasp +seize +hotly +laugh +sieve +block +meant +grape +noose +hardy +shied +drawl +daisy +putty +strut +burnt +tulip +crick +idyll +vixen +furor +geeky +cough +naive +shoal +stork +bathe +aunty +check +prime +brass +outer +furry +razor +elect +evict +imply +demur +quota +haven +cavil +swear +crump +dough +gavel +wagon +salon +nudge +harem +pitch +sworn +pupil +excel +stony +cabin +unzip +queen +trout +polyp +earth +storm +until +taper +enter +child +adopt +minor +fatty +husky +brave +filet +slime +glint +tread +steal +regal +guest +every +murky +share +spore +hoist +buxom +inner +otter +dimly +level +sumac +donut +stilt +arena +sheet +scrub +fancy +slimy +pearl +silly +porch +dingo +sepia +amble +shady +bread +friar +reign +dairy +quill +cross +brood +tuber +shear +posit +blank +villa +shank +piggy +freak +which +among +fecal +shell +would +algae +large +rabbi +agony +amuse +bushy +copse +swoon +knife +pouch +ascot +plane +crown +urban +snide +relay +abide +viola +rajah +straw +dilly +crash +amass +third +trick +tutor +woody +blurb +grief +disco +where +sassy +beach +sauna +comic +clued +creep +caste +graze +snuff +frock +gonad +drunk +prong +lurid +steel +halve +buyer +vinyl +utile +smell +adage +worry +tasty +local +trade +finch +ashen +modal +gaunt +clove +enact +adorn +roast +speck +sheik +missy +grunt +snoop +party +touch +mafia +emcee +array +south +vapid +jelly +skulk +angst +tubal +lower +crest +sweat +cyber +adore +tardy +swami +notch +groom +roach +hitch +young +align +ready +frond +strap +puree +realm +venue +swarm +offer +seven +dryer +diary +dryly +drank +acrid +heady +theta +junto +pixie +quoth +bonus +shalt +penne +amend +datum +build +piano +shelf +lodge +suing +rearm +coral +ramen +worth +psalm +infer +overt +mayor +ovoid +glide +usage +poise +randy +chuck +prank +fishy +tooth +ether +drove +idler +swath +stint +while +begat +apply +slang +tarot +radar +credo +aware +canon +shift +timer +bylaw +serum +three +steak +iliac +shirk +blunt +puppy +penal +joist +bunny +shape +beget +wheel +adept +stunt +stole +topaz +chore +fluke +afoot +bloat +bully +dense +caper +sneer +boxer +jumbo +lunge +space +avail +short +slurp +loyal +flirt +pizza +conch +tempo +droop +plate +bible +plunk +afoul +savoy +steep +agile +stake +dwell +knave +beard +arose +motif +smash +broil +glare +shove +baggy +mammy +swamp +along +rugby +wager +quack +squat +snaky +debit +mange +skate +ninth +joust +tramp +spurn +medal +micro +rebel +flank +learn +nadir +maple +comfy +remit +gruff +ester +least +mogul +fetch +cause +oaken +aglow +meaty +gaffe +shyly +racer +prowl +thief +stern +poesy +rocky +tweet +waist +spire +grope +havoc +patsy +truly +forty +deity +uncle +swish +giver +preen +bevel +lemur +draft +slope +annoy +lingo +bleak +ditty +curly +cedar +dirge +grown +horde +drool +shuck +crypt +cumin +stock +gravy +locus +wider +breed +quite +chafe +cache +blimp +deign +fiend +logic +cheap +elide +rigid +false +renal +pence +rowdy +shoot +blaze +envoy +posse +brief +never +abort +mouse +mucky +sulky +fiery +media +trunk +yeast +clear +skunk +scalp +bitty +cider +koala +duvet +segue +creme +super +grill +after +owner +ember +reach +nobly +empty +speed +gipsy +recur +smock +dread +merge +burst +kappa +amity +shaky +hover +carol +snort +synod +faint +haunt +flour +chair +detox +shrew +tense +plied +quark +burly +novel +waxen +stoic +jerky +blitz +beefy +lyric +hussy +towel +quilt +below +bingo +wispy +brash +scone +toast +easel +saucy +value +spice +honor +route +sharp +bawdy +radii +skull +phony +issue +lager +swell +urine +gassy +trial +flora +upper +latch +wight +brick +retry +holly +decal +grass +shack +dogma +mover +defer +sober +optic +crier +vying +nomad +flute +hippo +shark +drier +obese +bugle +tawny +chalk +feast +ruddy +pedal +scarf +cruel +bleat +tidal +slush +semen +windy +dusty +sally +igloo +nerdy +jewel +shone +whale +hymen +abuse +fugue +elbow +crumb +pansy +welsh +syrup +terse +suave +gamut +swung +drake +freed +afire +shirt +grout +oddly +tithe +plaid +dummy +broom +blind +torch +enemy +again +tying +pesky +alter +gazer +noble +ethos +bride +extol +decor +hobby +beast +idiom +utter +these +sixth +alarm +erase +elegy +spunk +piper +scaly +scold +hefty +chick +sooty +canal +whiny +slash +quake +joint +swept +prude +heavy +wield +femme +lasso +maize +shale +screw +spree +smoky +whiff +scent +glade +spent +prism +stoke +riper +orbit +cocoa +guilt +humus +shush +table +smirk +wrong +noisy +alert +shiny +elate +resin +whole +hunch +pixel +polar +hotel +sword +cleat +mango +rumba +puffy +filly +billy +leash +clout +dance +ovate +facet +chili +paint +liner +curio +salty +audio +snake +fable +cloak +navel +spurt +pesto +balmy +flash +unwed +early +churn +weedy +stump +lease +witty +wimpy +spoof +saner +blend +salsa +thick +warty +manic +blare +squib +spoon +probe +crepe +knack +force +debut +order +haste +teeth +agent +widen +icily +slice +ingot +clash +juror +blood +abode +throw +unity +pivot +slept +troop +spare +sewer +parse +morph +cacti +tacky +spool +demon +moody +annex +begin +fuzzy +patch +water +lumpy +admin +omega +limit +tabby +macho +aisle +skiff +basis +plank +verge +botch +crawl +lousy +slain +cubic +raise +wrack +guide +foist +cameo +under +actor +revue +fraud +harpy +scoop +climb +refer +olden +clerk +debar +tally +ethic +cairn +tulle +ghoul +hilly +crude +apart +scale +older +plain +sperm +briny +abbot +rerun +quest +crisp +bound +befit +drawn +suite +itchy +cheer +bagel +guess +broad +axiom +chard +caput +leant +harsh +curse +proud +swing +opine +taste +lupus +gumbo +miner +green +chasm +lipid +topic +armor +brush +crane +mural +abled +habit +bossy +maker +dusky +dizzy +lithe +brook +jazzy +fifty +sense +giant +surly +legal +fatal +flunk +began +prune +small +slant +scoff +torus +ninny +covey +viper +taken +moral +vogue +owing +token +entry +booth +voter +chide +elfin +ebony +neigh +minim +melon +kneed +decoy +voila +ankle +arrow +mushy +tribe +cease +eager +birth +graph +odder +terra +weird +tried +clack +color +rough +weigh +uncut +ladle +strip +craft +minus +dicey +titan +lucid +vicar +dress +ditch +gypsy +pasta +taffy +flame +swoop +aloof +sight +broke +teary +chart +sixty +wordy +sheer +leper +nosey +bulge +savor +clamp +funky +foamy +toxic +brand +plumb +dingy +butte +drill +tripe +bicep +tenor +krill +worse +drama +hyena +think +ratio +cobra +basil +scrum +bused +phone +court +camel +proof +heard +angel +petal +pouty +throb +maybe +fetal +sprig +spine +shout +cadet +macro +dodgy +satyr +rarer +binge +trend +nutty +leapt +amiss +split +myrrh +width +sonar +tower +baron +fever +waver +spark +belie +sloop +expel +smote +baler +above +north +wafer +scant +frill +awash +snack +scowl +frail +drift +limbo +fence +motel +ounce +wreak +revel +talon +prior +knelt +cello +flake +debug +anode +crime +salve +scout +imbue +pinky +stave +vague +chock +fight +video +stone +teach +cleft +frost +prawn +booty +twist +apnea +stiff +plaza +ledge +tweak +board +grant +medic +bacon +cable +brawl +slunk +raspy +forum +drone +women +mucus +boast +toddy +coven +tumor +truer +wrath +stall +steam +axial +purer +daily +trail +niche +mealy +juice +nylon +plump +merry +flail +papal +wheat +berry +cower +erect +brute +leggy +snipe +sinew +skier +penny +jumpy +rally +umbra +scary +modem +gross +avian +greed +satin +tonic +parka +sniff +livid +stark +trump +giddy +reuse +taboo +avoid +quote +devil +liken +gloss +gayer +beret +noise +gland +dealt +sling +rumor +opera +thigh +tonga +flare +wound +white +bulky +etude +horse +circa +paddy +inbox +fizzy +grain +exert +surge +gleam +belle +salvo +crush +fruit +sappy +taker +tract +ovine +spiky +frank +reedy +filth +spasm +heave +mambo +right +clank +trust +lumen +borne +spook +sauce +amber +lathe +carat +corer +dirty +slyly +affix +alloy +taint +sheep +kinky +wooly +mauve +flung +yacht +fried +quail +brunt +grimy +curvy +cagey +rinse +deuce +state +grasp +milky +bison +graft +sandy +baste +flask +hedge +girly +swash +boney +coupe +endow +abhor +welch +blade +tight +geese +miser +mirth +cloud +cabal +leech +close +tenth +pecan +droit +grail +clone +guise +ralph +tango +biddy +smith +mower +payee +serif +drape +fifth +spank +glaze +allot +truck +kayak +virus +testy +tepee +fully +zonal +metro +curry +grand +banjo +axion +bezel +occur +chain +nasal +gooey +filer +brace +allay +pubic +raven +plead +gnash +flaky +munch +dully +eking +thing +slink +hurry +theft +shorn +pygmy +ranch +wring +lemon +shore +mamma +froze +newer +style +moose +antic +drown +vegan +chess +guppy +union +lever +lorry +image +cabby +druid +exact +truth +dopey +spear +cried +chime +crony +stunk +timid +batch +gauge +rotor +crack +curve +latte +witch +bunch +repel +anvil +soapy +meter +broth +madly +dried +scene +known +magma +roost +woman +thong +punch +pasty +downy +knead +whirl +rapid +clang +anger +drive +goofy +email +music +stuff +bleep +rider +mecca +folio +setup +verso +quash +fauna +gummy +happy +newly +fussy +relic +guava +ratty +fudge +femur +chirp +forte +alibi +whine +petty +golly +plait +fleck +felon +gourd +brown +thrum +ficus +stash +decry +wiser +junta +visor +daunt +scree +impel +await +press +whose +turbo +stoop +speak +mangy +eying +inlet +crone +pulse +mossy +staid +hence +pinch +teddy +sully +snore +ripen +snowy +attic +going +leach +mouth +hound +clump +tonal +bigot +peril +piece +blame +haute +spied +undid +intro +basal +shine +gecko +rodeo +guard +steer +loamy +scamp +scram +manly +hello +vaunt +organ +feral +knock +extra +condo +adapt +willy +polka +rayon +skirt +faith +torso +match +mercy +tepid +sleek +riser +twixt +peace +flush +catty +login +eject +roger +rival +untie +refit +aorta +adult +judge +rower +artsy +rural +shave diff --git a/absurdle/dictionary2.txt b/absurdle/dictionary2.txt new file mode 100644 index 0000000..31bb410 --- /dev/null +++ b/absurdle/dictionary2.txt @@ -0,0 +1,9 @@ +ally +betablocker +cool +dealer +else +flew +dogood +hope +ibex diff --git a/absurdle/dictionary3.txt b/absurdle/dictionary3.txt new file mode 100644 index 0000000..a14bf9a --- /dev/null +++ b/absurdle/dictionary3.txt @@ -0,0 +1,30 @@ +stews +birds +braid +bends +rates +slabs +abash +frags +rares +drags +garbs +stair +steer +trail +great +crane +slate +stink +frier +yacht +carts +craft +hobby +lobby +train +break +treat +skunk +drank +bunny diff --git a/absurdle/small_dict.txt b/absurdle/small_dict.txt new file mode 100644 index 0000000..32e2fed --- /dev/null +++ b/absurdle/small_dict.txt @@ -0,0 +1,9 @@ +rgrasfally +beta +cool +deal +else +flew +good +hope +ibex diff --git a/helloworld.java b/helloworld.java new file mode 100644 index 0000000..f9f58c0 --- /dev/null +++ b/helloworld.java @@ -0,0 +1,8 @@ +// package src; +// import src.printer; + +public class helloworld { + public static void main(String[] args) { + System.out.println("hellow"); + } +} \ No newline at end of file diff --git a/linter/BlankPrintlnCheck.java b/linter/BlankPrintlnCheck.java new file mode 100644 index 0000000..dfb4f22 --- /dev/null +++ b/linter/BlankPrintlnCheck.java @@ -0,0 +1,19 @@ +// Nik Johnson +// 2-24-2024 +// TA: Andy Ruan + +import java.util.*; + +// checks lines for the characters "System.out.println("")" +public class BlankPrintlnCheck implements Check { + + // if the line being checked has a blank println statement, return a new error (code 3) + // takes line and line number + // returns error inside optional + public Optional lint(String line, int lineNumber) { + if (line.contains("System.out.println(\"\")")) { + return Optional.of(new Error(3, lineNumber, "Line contains blank print statement")); + } + return Optional.empty(); + } +} diff --git a/linter/BreakCheck.java b/linter/BreakCheck.java new file mode 100644 index 0000000..0007fe3 --- /dev/null +++ b/linter/BreakCheck.java @@ -0,0 +1,23 @@ +// Nik Johnson +// 2-24-2024 +// TA: Andy Ruan + +import java.util.*; + +// checks Strings for the characters "break" that come BEFORE the characters "//" +public class BreakCheck implements Check { + + // if the line being checked has "break" in it + // after removing all single line comments, return a new error (code 2) + // takes line and line number + // returns error inside optional + public Optional lint(String line, int lineNumber) { + String input = line; + String output = input.replaceAll("//.*", ""); + + if (output.contains("break")) { + return Optional.of(new Error(2, lineNumber, "we cant use break in this class bro")); + } + return Optional.empty(); + } +} diff --git a/linter/Check.java b/linter/Check.java new file mode 100644 index 0000000..2b3bca5 --- /dev/null +++ b/linter/Check.java @@ -0,0 +1,11 @@ +import java.util.*; + +// A common interface for linters that can check a single line of code +// Every Check will check for its own type of error on a single line of code. +public interface Check { + // Checks for this Check's error condition on this line with this line number. + // If an error exists on this line, returns an Optional with an Error present + // indicating an error occurred. If no errors are present, returns an empty Optional. + public Optional lint(String line, int lineNumber); +} + diff --git a/linter/Error.java b/linter/Error.java new file mode 100644 index 0000000..da4a051 --- /dev/null +++ b/linter/Error.java @@ -0,0 +1,43 @@ +// Nik Johnson +// 2-24-2024 +// TA: Andy Ruan + +/* +Defining an object called Error, which has the fields: +code: the errors code, represented by an int +lineNumber: the line where the error occurred +message: a description of the error +*/ +public class Error { + + private int code; + private int lineNumber; + private String message; + + // construct an error with its fields + public Error(int code, int lineNumber, String message) { + this.code = code; + this.lineNumber = lineNumber; + this.message = message; + } + + // format an error and its information nicely + public String toString() { + return ("(Line: " + lineNumber + ") " + "has error code " + code + "\n" + message); + } + + // return line where the error occurs + public int getLineNumber() { + return this.lineNumber; + } + + // return the error code (a number) + public int getCode() { + return this.code; + } + + // return the errors description + public String getMessage() { + return this.message; + } +} diff --git a/linter/Linter.java b/linter/Linter.java new file mode 100644 index 0000000..e30a8c3 --- /dev/null +++ b/linter/Linter.java @@ -0,0 +1,39 @@ +// Nik Johnson +// 2-24-2024 +// TA: Andy Ruan + +import java.util.*; +import java.io.*; + +// file-based linting object, linting based on checks defined in a list +public class Linter { + + private List checks; + + // constructor, takes list of checks to perform + public Linter(List checks) { + this.checks = checks; + } + + // compile list of errors based on output of check classes + // takes filename to perform checks on + // return list of errors present in that file + public List lint(String fileName) throws FileNotFoundException { + File toBeChecked = new File(fileName); + Scanner fileScanner = new Scanner(toBeChecked); + List errors = new ArrayList<>(); + int lineNumber = 1; + while (fileScanner.hasNext()) { + String line = fileScanner.nextLine(); + for (Check check : checks) { + Optional error = check.lint(line, lineNumber); + if (error.isPresent()) { + errors.add(error.get()); + } + } + lineNumber++; + } + fileScanner.close(); + return errors; + } +} diff --git a/linter/LinterMain.java b/linter/LinterMain.java new file mode 100644 index 0000000..97fb2b8 --- /dev/null +++ b/linter/LinterMain.java @@ -0,0 +1,22 @@ +// Nik Johnson +// 2-24-2024 +// TA: Andy Ruan + +import java.util.*; +import java.io.*; + +public class LinterMain { + public static final String FILE_NAME = "TestFile.txt"; + + public static void main(String[] args) throws FileNotFoundException { + List checks = new ArrayList<>(); + checks.add(new LongLineCheck()); + checks.add(new BreakCheck()); + checks.add(new BlankPrintlnCheck()); + Linter linter = new Linter(checks); + List errors = linter.lint(FILE_NAME); + for (Error e : errors) { + System.out.println(e); + } + } +} diff --git a/linter/LongLineCheck.java b/linter/LongLineCheck.java new file mode 100644 index 0000000..d5d4368 --- /dev/null +++ b/linter/LongLineCheck.java @@ -0,0 +1,21 @@ +// Nik Johnson +// 2-24-2024 +// TA: Andy Ruan + +import java.util.*; + +// long line checker +public class LongLineCheck implements Check { + + // if the line being checked is 100 characters or longer, return a new error (code 1) + // takes line and line number + // returns error inside optional + public Optional lint(String line, int lineNumber) { + if (line.length() >= 100) { + return Optional.of(new Error(1, lineNumber, + "Line length exceeded maximum length of 100 characters")); + } + + return Optional.empty(); + } +} diff --git a/linter/TestFile.java b/linter/TestFile.java new file mode 100644 index 0000000..ebdff55 --- /dev/null +++ b/linter/TestFile.java @@ -0,0 +1,10 @@ +public class TestFile { + public static void main(String[] args) { + System.out.println("This is a really really really long line that should fail the long line check"); + while (true) { + System.out.println(""); + break; + } + // break + } +} diff --git a/linter/TestFile.txt b/linter/TestFile.txt new file mode 100644 index 0000000..76a8979 --- /dev/null +++ b/linter/TestFile.txt @@ -0,0 +1,89 @@ +package com.example; + +public class Example { + public static void main(String[] args) { + int x = 5; + while (x < 10) { + System.out.println("Hello, world!"); + break; + } + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + continue; + } else { + System.out.println(i); + } + } + try { + throw new Exception("Test"); + } catch (Exception e) { + System.out.println("Caught an exception: " + e.getMessage()); + } finally { + System.out.println("Finally block executed."); + } + for (int j = 0; j < 100; j++) { + if (j % 2 == 0) { + break; + } else { + System.out.println(j); + } + } + while (x > 5) { + System.out.println("Hello, world!"); + break; + } + if (x % 2 == 0) { + continue; + } else { + System.out.println(x); + } + for (int k = 0; k < 1000; k++) { + if (k % 2 == 0) { + break; + } else { + System.out.println(k); + } + } + while (x > 5) { + System.out.println("Hello, world!"); + break; + } + if (x % 2 == 0) { + continue; + } else { + System.out.println(x); + } + for (int l = 0; l < 10000; l++) { + if (l % 2 == 0) { + break; + } else { + System.out.println(l); + } + } + while (x > 5) { + System.out.println("Hello, world!"); + break; + } + if (x % 2 == 0) { + continue; + } else { + System.out.println(x); + } + for (int m = 0; m < 100000; m++) { + if (m % 2 == 0) { + break; + } else { + System.out.println(m); + } + } + while (x > 5) { + System.out.println("Hello, world!"); + break; + } + if (x % 2 == 0) { + continue; + } else { + System.out.println(x); + } + } +} diff --git a/printer.java b/printer.java new file mode 100644 index 0000000..9392884 --- /dev/null +++ b/printer.java @@ -0,0 +1,7 @@ +public class printer { + public static void main(String[] args) { + System.out.println("hellow"); + System.out.println("hello"); + System.out.println("helw"); + } +} \ No newline at end of file diff --git a/stonks.tsv b/stonks.tsv new file mode 100644 index 0000000..16256ca --- /dev/null +++ b/stonks.tsv @@ -0,0 +1,7 @@ +5 +Symbol Price P/E Ratio Dividend Yield +AAPL 150.2 30.0 1.5% +COST 673.58 45.8 1.5% +GOOGL 2750.50 35.0 0.8% +MSFT 310.75 28.5 1.2% +AMZN 3400.25 40.0 0.5% diff --git a/variables.java b/variables.java new file mode 100644 index 0000000..5c1803c --- /dev/null +++ b/variables.java @@ -0,0 +1,10 @@ +public class variables { + public static void main(String[] args) { + int x = 8; + int xy = 16; + int y = 32; + System.out.println((x+3)*200); + System.out.println(xy); + System.out.println(y); + } +} \ No newline at end of file diff --git a/wordcount.java b/wordcount.java new file mode 100644 index 0000000..8aba15d --- /dev/null +++ b/wordcount.java @@ -0,0 +1,18 @@ +import java.util.*; +import java.io.*; + +public class wordcount { + public static void main(String[] args) throws FileNotFoundException { + File input = new File(args[0]); + Scanner fileScanner = new Scanner(input); + + int count = 0; + while (fileScanner.hasNext()) { + String nextToken = fileScanner.next(); + count++; + } + + fileScanner.close(); + System.out.println(count); + } +}