Java text analysis program - java

The following requisites are those for the program I'm currently having an issue with:
The program must be able to open any text file specified by the user, and analyze the frequency of verbal ticks in the text. Since there are many different kinds of verbal ticks (such as "like", "uh", "um", "you know", etc) the program must ask the user what ticks to look for. A user can enter multiple ticks, separated by commas.
The program should output:
the total number of tics found in the text
the density of tics (proportion of all words in the text that are tics)
the frequency of each of the verbal tics
the percentage that each tic represents out of all the total number of tics
My program is working very well, but what I basically need to do is that I must use separate methods for each component of the analysis. So I think the idea is that I need to split up the program in a few parts, which I have done by using the comments // because I'm basically having problems determining which type I should return, I know the last part (// public static void output(){)
should definitely be void because it returns nothing and only prints out.
public static void main(String[] args) throws FileNotFoundException {
double totalwords = 0; // double so density (totalwords/totalticks) returned can be double
int totalticks = 0;
System.out.println("What file would you like to open?");
Scanner sc = new Scanner(System.in);
String files = sc.nextLine();
Scanner input = new Scanner(new File(files));
// public static int[] initialise()
System.out.println("What words would you like to search for? (please separate with a comma)");
String ticks = sc.nextLine();
ticks = ticks.toLowerCase();
String[] keys = ticks.split(",");
int[] values = new int[keys.length];
// public static int[] processing(){?
for (int z=0; z<keys.length; z++){
values[z] = 0;
}
while (input.hasNext()){
String next = input.next();
totalwords++;
for (int x = 0; x<keys.length; x++){
if (next.toLowerCase().equals(keys[x])){
values[x]+=1;
}
}
}
for (Integer u : values) {
totalticks += u;
}
//public static void output(){
System.out.println("Total number of tics :"+totalticks);
System.out.printf("Density of tics (in percent): %.2f \n", ((totalticks/totalwords)*100));
System.out.println(".........Tick Breakdown.......");
for (int z = 0; z<keys.length; z++){
System.out.println(keys[z] + " / "+ values[z]+" occurences /" + (values[z]*100/totalticks) + "% of all tics");
}
}
Essentially the problem I'm having is the scope of the variables because Eclipse (my IDE) no longer recognizes the variables within each method once I get them out of comments - I know I need to use some static variables but would really like a hand as to how I could hook my program up together using methods.
Thanks a bunch,
M

You should do an object (class) decomposition. First ask the question "What objects do I have". (At a quick glance you might have "Text" and "Ticks" objects. You then want to see what methods you want to use for each object. For example in Text have countTicks(Ticks). Conotinue in this fashion to decompose your program.

First, please indent your code more consistently, with the first line of a block three spaces farther to the right, such as
for(...) {
//Do stuff
if(...) {
//Do stuff
}
}
It is hard to read what you've posted (luckily someone spruced it up for you!).
Consider re-writing your program from scratch, instead of trying to fix what you already have. Your current knowledge of the problem should allow you to recreate it pretty quickly. You will probably be able to cut and paste bits and pieces from your original code as well.
How about starting small, with something like
Scanner sc = getInputScannerFromUserInput();
private static final Scanner getInputScannerFromUserInput() {
System.out.println("What file would you like to open?");
return new Scanner(System.in);
}
and just go from there. Bit by bit. Good luck!

Related

Sudoku Code Program - Checking Rows,Columns, and Boxes

I need help checking rows, columns, and boxes for a Sudoku program. I am a high school student that needs help completing this project. If any one could provide help that would be awesome! I am currently working on checking boxes where I have a comment saying "Start Here". Thanks!
import java.util.*;
public class Run
{
Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
char [][] board = new char [9][9];
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Sudoku!\n");
fill(board);
printBoard(board);
inputLengthandDigits(board);
System.out.println();
printBoard(board);
}
public static void fill(char[][] arr){
for(int row = 0; row < arr.length; row++){
for(int col= 0; col< arr[row].length; col++){
arr[row][col] = '-';
}
}
}
public static void printBoard(char [][] array)
{
for(char[] row: array)
{
for(char play: row)
{
System.out.print(play+ " ");
}
System.out.println();
}
}
public static void inputLengthandDigits(char[][] array){
Scanner in = new Scanner(System.in);
for (int i = 0; i < 9; i++)
{
System.out.println("\nEnter the numbers in row " + (i+1) + ":");
String input = in.nextLine();
String numbers = "123456789-";
boolean numberscheck = false;
boolean endCheck = true;
boolean onlyOnce = true;
//Input Validation Starts Here!
//Checks if Input is only digits 0-9
do{
if(endCheck==false){
System.out.println("\nPlease input numbers only (1-9)!");
input = in.nextLine();
}
if(onlyOnce==false){
System.out.println("\nPlease input numbers only once!");
input = in.nextLine();
}
//Checks Length of User Input
while(input.length() < 9 || input.length() > 9){
System.out.println("\nPlease input 9 numbers!");
input = in.nextLine();
}
//Start Here
for(int a = 0; a<input.length()-1; a++){
for(int b= a + 1; b<input.length(); b++){
if(input.charAt(a)==input.charAt(b)){
onlyOnce = false;
}
}
}
for(int x = 0; x < input.length(); x++){
char thing = input.charAt(x);
numberscheck = false;
for(int y = 0; y < numbers.length(); y++){
char numbersn = numbers.charAt(y);
if(thing == numbersn){
numberscheck = true;
endCheck = true;
break;
}
}
if(numberscheck == false){
endCheck = false;
break;
}
}
}while(endCheck==false || onlyOnce==false);
for(int j=0; j<9; j++){
array[i][j] = input.charAt(j);
}
}
}
}
My initial response is too long for a comment. I'm not sure I have a solution to your problem, largely because you haven't actually pointed out which bit is a problem yet, but these pointers should help improve things anyway:
Please reformat your code. It is actually quite painful to look at. Spaces should be used consistently around variables, key words, brackets and operands. Opening curly braces should be on the same line as the method signature, for() loop or whatever else comes first. You have random blank lines within methods which don't separate logical sections so are just confusing. The compiler won't care about any of this, but if you can make your code look neater people will instinctively presume you care and are more likely to credit you with the ability to write decent code.
You have declared a new scanner variable three times. This is redundant and wasteful clutter. Either have a single, class-wide scanner, or (preferably), only create a scanner in a method which actually uses it and then remember to call scanner.close() once the scanner is no longer required.
inputLengthandDigits is a weird name. Is 'Lengthand' a single word, or should it be 'inputLengtHandDigits' or 'inputLengthAndDigits'? In camel case, capitalise every word except the first to make the whole easier to read. Whatever it should be, I don't understand from the name what this method does. It isn't inputting anything, it's getting inputs from someone else. Perhaps getData or populateGrid might be more explanatory.
9 appears quite a few times, with no explanation. I know where it came from, because I spend far too much time playing Sudoku, but it is a magic number and these are to be avoided at all costs. I met a magic number in the workplace once, wasted half a day trying to do what could have been a ten minute job if colleagues had recorded what the number was and where it came from. Here, just have a private static final int maxNumber = 9; statement.
A good thing: your main() method has almost no fiddly details in it. You have effectively used method calls to tell a story and describe what is happening elsewhere. This is a really, really good thing to do :)
Some of your logic tests can be tidied up a bit, e.g. !onlyOnce is the same as onlyOnce == false, and input.length() < maxNumber || input.length() > maxNumber can be simplified to input.length() != maxNumber. It's exactly the same logic, but faster to type and easier to read :)
It looks like your code under the //Start here comment is checking that you don't have any duplicate numbers. If you do get duplicate numbers, the program is still going to try and run the next bit of code before asking the user for alternative input. Is that something you want to happen, or a waste of time?
I actually burst out laughing when I saw a variable called 'thing'. Please, find a name which actually describes the purpose of this variable.
I have now run the code, and it rightly pointed out an error when I tried to key in duplicate numbers for row 4. However, it's now stuck there and keeps asking me to try again even when I put in a valid set of digits. This needs to be fixed. Look closely at which flags are triggering the request to retry. Run your code in debugging mode (you are using an IDE like IntelliJ or Eclipse, aren't you?) and deliberately enter a bad row to see the behaviour for yourself and where the logic is going wrong.
This whole method to get the row input, validate it, and then populate the array, is very big and confusing. You need to refactor it into a lot of smaller methods. Here is a suggestion to play with:
private static char[][] populateGrid(char[][] array) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i <maxNumber; i++) {
String rowData = getRowInput(scanner);
populateRow(array, rowNumber, rowData);
}
scanner.close;
return array;
}
private static String getRowInput(Scanner scanner) {
System.out.println("\nEnter the numbers in row " + (i + 1) + ":");
String input = scanner.nextLine();
while (!isValidInput(input) {
System.out.println("Please enter only the digits 1-9 in any order, with no duplicates or omissions");
input = scanner.nextLine();
}
return input;
}
private static boolean isValidInput(String input) {
if (!rightLengthOfInput(input)) {
return false;
}
if (!allUniqueDigits(input)) {
return false;
}
if (!usesCorrectCharacters(input)) {
return false;
}
return true;
}
I'll leave you to make the different input validation methods. It will largely be a case of moving your existing code, but the method names will help humans understand what each section is doing. This structure also allows you to cleanly add more validation checks, should such a thing be desired in the future.
Things to consider after all that:
Are you going to check that you have a viable Sudoku solution, or will you trust the user to put in correct data such that the columns also have each of the nine digits in them? How will you handle an invalid grid, e.g. each row is identical?
How far does this assignment want you to go? Do you need to systematically remove numbers to get a solvable puzzle rather than a completed grid? Will the assignment stop at a puzzle which can be seen in the console, or do you need a printable format, or will the user be able to play through the program? If the latter option, will this be in the console or using a graphical interface?
I appreciate that there is a lot to think about and work on here. Take it steadily, one step at a time, and keep asking questions if you need too.

Want to programm calculator, want to change String into real operator

I want to code a simple calculator and already got some code. But now I want to change the String I got there into an Operator. For example:
My input is: "1,5 - 1,1 + 3,2 ="
Now I have a double array and a String array.
So after that I want to put it together, so it calculates this complete task.
double result = double[0] String[0] double[1] ....
I hope you can help there, and I apologize for my grammar etc., english is not my main language.
import java.util.*;
public class calculator
{
public static void main(String[] args)
{
int a = 0;
int b = 0;
double[] zahl;
zahl = new double[10];
double ergebnis;
String[] zeichen;
zeichen = new String[10];
Scanner input = new Scanner (System.in);
while (input.hasNext())
{
if (input.hasNextDouble())
{
zahl[a] = input.nextDouble();
a++;
}
else if (input.hasNext())
{
zeichen[b] = input.next();
if (zeichen.equals ("=")) break;
b++;
}
}
input.close();
}
}
If I type in: "1,5 + 2,3 * 4,2 =" I want to get the result with point before line and without .math
What you want to do is parse a single String and convert it into a mathematical expression, which you then want to resolve and output the result. For that, you need to define a "language" and effectively write an interpreter. This is not trivial, specifically if you want to expand your syntax with bracketing and thelike.
The primary question you have to answer is, whether you want to use a solution (because you are not the first person to attempt this) or if you want to actually write this yourself.
There are "simple" solutions, for example, you could instantiate a javascript engine in Java and input your string, but that would allow much more, and maybe even things you don't want. Or you could use a library which already does this. This Thread already answered a similar question with multiple interesting answers:
How to evaluate a math expression given in string form?
Otherwise, you might be in for a surprise, concerning the amount of work, you are getting yourself into. :)

Matching user input against a string array in java?

I am incredibly new to java and have been given the following task:
Write a Java Program to prompt a user for a 3 letter body part name which has to be in the 'official' list of 3 letter body parts. (Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe)
If a user makes a guess correctly then display the correct guess as part of a list.
Allow the user to keep guessing until they have all 10.
If a body part is incorrect then display an appropriate message.
Display the number of guesses they have made including
the correct ones.
The advice given was to use Arrays and Collections as well as Exception Handling where appropriate but I don't know where to go from what I've coded so far. Any help would be appreciated so much, thank you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] bodyparts = new String [10];
bodyparts[0] = "Arm";
bodyparts[1] = "Ear";
bodyparts[2] = "Eye";
bodyparts[3] = "Gum";
bodyparts[4] = "Hip";
bodyparts[5] = "Jaw";
bodyparts[6] = "Leg";
bodyparts[7] = "Lip";
bodyparts[8] = "Rib";
bodyparts[9] = "Toe";
Set<String> bodypartSet = new TreeSet<>();
Collections.addAll(bodypartSet, bodyparts);
System.out.println("Please enter a 3 letter body part: ");
String bodypart = input.nextLine();
if (bodypartSet.contains(bodypart)) {
System.out.println("Correct, " + bodypart + " is on the list!");
} else {
System.out.println("Nope, try again!");
}
}
There are a lot of way to do this. The following, isn't the best or the most efficient, but it should work...
First of all, you have to put your "official" list in a structure, like an array:
private static String[] offList={Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe};
Now you have to write a method that can find a world in that "offList", like that:
private static boolean find(String word){
for( int i=0; i<offList.length; i++){
if(word.equals(offList[i])) //if "word" is in offList
return true;
}
return false;
}
Now, let's create this guessing game GUI:
public static void main(String[] args){
LinkedList<String> guessed=new LinkedList<>();
String s;
Scanner input = new Scanner(System.in);
while(guessed.size()<offList.length){
System.out.println("Guessed= "+guessed.toString()); //you have to change it, if you want a better look
System.out.print("Try:");
s=input.nextLine();
/*Here we ask to the user the same thing, unless the guessed list
contains all the words of offList.
Every time we print the guessed worlds list*/
if(find(s)){
System.out.println("This world is in offList!");
if(!guessed.contains(s)) //the world is counted only one time!
guessed.add(s);
}else
System.out.println("Sorry...");
}
System.out.println("The complete list is "+guessed.toString());
}
If you want to show this game in a window, you should have to study some Java Swing classes.
EDIT: I post my answer before the main post editing. First of all you have to understand the Collections advantages and usage... When you know all the LinkedList methods, for example, this assignment looks like a joke! ;)
You need a loop for that, otherwise it will only ask for input once.
Something like this should do:
ArrayList<String> bodyParts = new ArrayList<String>();
bodyParts.add("Arm");
bodyParts.add("Ear");
bodyParts.add("Eye");
bodyParts.add("Gum");
bodyParts.add("Hip");
bodyParts.add("Jaw");
bodyParts.add("Leg");
bodyParts.add("Lip");
bodyParts.add("Rib");
bodyParts.add("Toe");
String input = "";
int totalGuesses = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Start guessing...");
while (!bodyParts.isEmpty()) {
totalGuesses++;
input = sc.nextLine();
if (input.length() != 3 || !bodyParts.contains(input)) {
// incorrect, do nothing
System.out.println("Nope.");
} else {
// correct, remove entry
bodyParts.remove(input);
System.out.println("Correct! " + (10 - bodyParts.size()) + " correct guess" + ((10 - bodyParts.size()) != 1 ? "es" : ""));
}
}
System.out.println("Done. You have found them all after " + totalGuesses + " guesses.");
sc.close();
Also, this is case sensitive. It will not find Arm when typing arm. And if you need the number of all guesses you can simply add an int before the loop and increase it inside.
The result of my example:
Start guessing...
arm
Nope.
Arm
Correct! 1 correct guess
Arm
Nope.
Ear
Correct! 2 correct guesses
Eye
Correct! 3 correct guesses
(...)
Rib
Correct! 9 correct guesses
Toe
Correct! 10 correct guesses
Done. You have found them all after 12 guesses.

Read words until user writes 'end', then, order lexicographically(as in a dictionary), show the last word

User will enter words until the last word written is "end", then the code has to order lexicographically, as we have in a dictionary, all the words entered before 'end' and print the last word, the one classified the last.
//.....
Scanner word = new Scanner (System.in);
String keyword="end";
String finalstring;
String[] firststring= new String[1000]; //Don't know how to stablish a //dynamic string[] length, letting the user stablish the string[].length
for(int c=0;c<firststring.length;c++){
firststring[c]=word.next();
if(firststring[c].equals(keyword)){
finalstring=firststring[c].substring(0,c);
c=cadena.length-1; //To jump out of the for.
}
}
for (int c=0;c<finalstring.length();c++) {
for(int i=c+1;i<finalstring.length();i++) {
if (firststring[c].compareTo(firststring[i])>0) {
String change = firststring[c];
firststring[c] = firststring[i];
firststring[i] = change;
}
}
}
System.out.print("\nYou entered "end" and the last word classified is "+finalstring[finalstring.length()-1]); //Of course, error here, just did it to put one System.out.print of how should the result be.
}
}
This is what I tried, though, without any type of success, any help of yours will be a big help, thank you ALL!
Don't know how to stablish a dynamic string[] length, letting the user establish the string[].length
It is not necessary to do that. But here's how.
Approach #1: ask the user to give you a number and then allocate the array like this:
String[] strings = new String[theNumber];
Warning: the requirements don't say you are allowed to do that, and you may lose marks for deviating from the requirements.
Approach #2: use an ArrayList to accumulate a list of words, the use List.toArray to create an array from the list contents. (Read the javadocs for list to work it out.)
Of course, error here, just did it to put one System.out.print of how should the result be.
Yea. One problem is that the length is 1000, but you don't have 1000 actual strings in the array. The same problem affects your earlier code too. Think about is ...
I'm not going to fix your code to make it work. I've given you enough hints for you to do that for yourself. If you are prepared to put in the effort.
One more hint: you can / should use break to break out of the first loop.
I know some words are not in English but in Catalan, but the code can be perfectly understood, yesterday I finally programmed this answer:
public static void main(String[] args) {
Scanner entrada= new Scanner(System.in);
System.out.println("Escriu les paraules que vulguis, per acabar, usa la paraula 'fi'.");
String paraules = "";
int c=0;
do {
String paraula = entrada.next();
if (paraula.equals("fi")) {
c++;
} else {
if (paraula.compareTo(paraules) > 0) {
paraules = paraula;
}
}
} while (c==0);
System.out.println("L'última parala ordenada alfabèticament és "+paraules+".\n");
}
}

arrays not recognized outside of for loop

I am trying to write a program that takes input from an external file, prints it, then calculates total world length and also the frequency of 3 letter words within the file. I'm only supposed to use string methods... I have tried to create an array of lines from the input and then create another array using .split to analyze each word. However, everytime I try to test wordcount or write a code segment to calculate frequency of 3 letter words, I get an error of can not find symbol... I don't know what this means. Can someone help me with what the error means and how to fix it, please?
import java.util.*;
import java.io.*;
public class Program
{
public static void main(String args[])
{
Scanner inFile = null; //adds the data
try {
inFile = new Scanner (new File("prog512h.dat"));}
catch (FileNotFoundException e) {
System.out.println ("File not found!");
System.exit (0);}
String[] line = new String[18]; //there are 18 lines of code in the external file
int wordcount=0;
for (int i=0; i<18; i++){
line[i] = inFile.nextLine();
System.out.println(line[i]);
String word[] = line[i].split(" ");
}
wordcount = word.length();
System.out.println();
System.out.println("Total Wordcount: " +wordcount);
}}
The external data file referenced reads this:
Good morning life and all
Things glad and beautiful
My pockets nothing hold
But he that owns the gold
The sun is my great friend
His spending has no end
Hail to the morning sky
Which bright clouds measure high
Hail to you birds whose throats
Would number leaves by notes
Hail to you shady bowers
And you green fields of flowers
Hail to you women fair
That make a show so rare
In cloth as white as milk
Be it calico or silk
Good morning life and all
Things glad and beautiful
You are creating a local variable inside a loop, so as soon as you leave the loop it goes out of scope.
Read up on variable scoping for more detail. The easiest fix is to declare the variable before you enter the loop - although note that that would overwrite the variable each time so only the last time around the loop would do anything.
You probably actually want to do:
wordCount += word.length;
Inside the loop.
Right now, your code as it is, doesn't make very much sense. Even if word[] was visible outside your for loop, it would only represent the very last line after the loop was done.
But, if you just want to update the wordcount without making any major changes to your code, you can update wordcount inside your loop
int wordcount = 0;
for (int i=0; i<18; i++)
{
line[i] = inFile.nextLine();
System.out.println(line[i]);
String word[] = line[i].split(" ");
wordcount += word.length;
}

Categories

Resources