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
Here is my program:
public class TextfileHW2 {
// initiate(
public static int[] initiate(int[] values){
for (int z=0; z<keys.length; z++){
values[z] = 0;
}
return values;
processing(values);
}
// processing(values)
public static int[] processing(int[] valuez){
while (input.hasNext()){
String next = input.next();
totalwords++;
for (int x = 0; x<keys.length; x++){
if (next.toLowerCase().equals(keys[x])){
valuez[x]+=1;
}
}
return valuez;
output();
}
for (Integer u : valuez){
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");
}
sc.close();
input.close();
}
public static void main(String[] args) throws FileNotFoundException {
static double totalwords = 0; // double so density (totalwords/totalticks) returned can be double
static int totalticks = 0;
System.out.println("What file would you like to open?");
static Scanner sc = new Scanner(System.in);
static String files = sc.nextLine();
static Scanner input = new Scanner(new File(files));
System.out.println("What words would you like to search for? (please separate with a comma)");
static String ticks = sc.nextLine(), tics = ticks.toLowerCase();
static String[] keys = tics.split(",");
static int[] values = new int[keys.length];
initiate(values);
}
My program should be logically right as I wrote it and successfully ran it for a while last week, but the difference with this one (which doesn't work) is that I must use separate methods for each component of the analysis, which shouldn't be too difficult a task considering the program was working before So I naturally tried to split up my program such that I can call my first method (which I called initiate) then my 2nd and 3rd methods called processing and output.
First of all, what does static really mean? I remember my teacher saying that it represents a global variable which I can use anywhere in the program. As you can see I changed every variable to static to perhaps make my task easier.
Also, do I strictly need to use public static + type returned if I'm going to change something?
Let's say I want to change the values of an array (like I do in my program and use public static void) do I need to return something to actually change the values of the array or is it ok to use public static void?
If anyone also has any general pointers for what concerns my methods I would really appreciate it.
Your problem is in your initiate method:
return values;
processing(values);
Once you call return, your method stops. If you are using Eclipse (which I highly recommend), you should have gotten an error saying "Unreachable code," because there is simply no way for the program to execute your processing method.
I also saw this flaw in your output method.
First of all, what does static really mean? I remember my teacher
saying that it represents a global variable which I can use anywhere
in the program. As you can see I changed every variable to static to
perhaps make my task easier.
It depends on the context. There is a good overall description here. The meaning is different when applied to methods, fields, and classes. To say it makes variables "global" is a bit simplified.
Also, do I strictly need to use public static + type returned if I'm going to change something?
I'm a little confused about what you mean. A method declared as public static *return_type* has three separate, independent qualities:
public: It is accessible by any other class.
static: It does not require an instance of the class to function (see above link).
*return_type*: This is, of course, the return type.
These properties aren't really related to "changing something". Unless I misunderstood your question, the answer is: No, the method specifiers and return type have no impact on its ability to change something with the exception that static methods cannot modify non-static fields or call non-static methods of this (there is no this in static methods).
Let's say I want to change the values of an array (like I do in my program and use public static void) do I need to return something to actually change the values of the array or is it ok to use public static void?
What you do in the function is entirely independent of the access specifier and static-ness of it (with the above-mentioned exception that this does not exist in static methods). If your function has any side-effects like changing the values in an array (or any values for that matter), then it does it regardless of public, or static, or its return type.
Check out the More on Classes section of the official language tutorial. It is concise and well-written and should help complete your understanding of the general concepts you're asking about. Check out some of the other tutorials there as well if you'd like.
Related
I dont know how well I'll be able to ask this question, but given a text file I need to parse through and extract the productID data and store it in a HashSet, userID data and store it in a HashSet, and the review/score and store it in an ArrayList. They also need to be used to create a graph, where the productID is connected with an edge between the userID.
The data is found here http://snap.stanford.edu/data/web-FineFoods.html
You can ignore review/time, review/helpfulness, review/summary, and review/text information, they dont need to be stored in memory.
My current code looks like this:
import java.io.*;
import java.util.*;
import java.nio.charset.*;
public class Reviews
{
String fileName = "newfinefoods.txt";
GraphType<String> foodReview;
HashSet<String> productID;
HashSet<String> userID;
ArrayList<String> review;
int counter; //was using this to make sure I'm counting all the lines which I think I am
public Reviews(){
foodReview = new GraphType<>();
productID = new HashSet<>();
userID = new HashSet<>();
review = new ArrayList<>();
counter = 0;
}
public int numReviews(){
return review.size();
}
public int numProducts(){
return productID.size();
}
public int numUsers(){
return userID.size();
}
public void setupGraph(){
Scanner fileScanner;
String line = "";
try{
fileScanner = new Scanner (new File (fileName), "UTF-8");
String pr = "";
while(fileScanner.hasNextLine()){
line = fileScanner.nextLine();
String[] reviewInfo = line.split(": ");
String productInfo = reviewInfo[1];
System.out.println(productInfo);
}
}
catch (IOException e){
System.out.println(e);
}
}
public static void main(String[] args){
Reviews review = new Reviews();
review.setupGraph();
System.out.println("Number of Reviews:" + review.numReviews());
System.out.println("Number of Products:" + review.numProducts());
System.out.println("Number of Users:" + review.numUsers());
}
}
Whenever I run the code, looking in the array reviewInfo at 1, it only prints one set of data, but if I change it to 0 it seems to print all the information (just not the info that I need). I need to create this graph and get the info from the data but I am really just super stuck, and any tips or help would be very appreciated!
Here is a sample of the data:
product/productId: B001E4KFG0
review/userId: A3SGXH7AUHU8GW
review/profileName: delmartian
review/helpfulness: 1/1
review/score: 5.0
review/time: 1303862400
review/summary: Good Quality Dog Food
review/text: I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky and she appreciates this product better than most.
product/productId: B00813GRG4
review/userId: A1D87F6ZCVE5NK
review/profileName: dll pa
review/helpfulness: 0/0
review/score: 1.0
review/time: 1346976000
review/summary: Not as Advertised
review/text: Product arrived labeled as Jumbo Salted Peanuts...the peanuts were actually small sized unsalted. Not sure if this was an error or if the vendor intended to represent the product as "Jumbo".
product/productId: B000LQOCH0
review/userId: ABXLMWJIXXAIN
review/profileName: Natalia Corres "Natalia Corres"
review/helpfulness: 1/1
review/score: 4.0
review/time: 1219017600
review/summary: "Delight" says it all
review/text: This is a confection that has been around a few centuries. It is a light, pillowy citrus gelatin with nuts - in this case Filberts. And it is cut into tiny squares and then liberally coated with powdered sugar. And it is a tiny mouthful of heaven. Not too chewy, and very flavorful. I highly recommend this yummy treat. If you are familiar with the story of C.S. Lewis' "The Lion, The Witch, and The Wardrobe" - this is the treat that seduces Edmund into selling out his Brother and Sisters to the Witch.
product/productId: B000UA0QIQ
Initial approach of your design is right, but you should structure it a little more:
Method setupGraph should be splitted in little specific and parametrized methods:
Since the users and products are part of the class' state, I deem it better that the class' constructor receives the scanner as an input parameter. Then, after initializing the state variables, it should call setupGraph (which should be private) passing the input scanner.
setupGraph shall receive an input scanner and take the responsibility of reading lines from it, and give a proper treatment to the IOExceptions that might arise. On each line, it should merely call another private method for processing the read line. If you want to count all the read lines, this is where you should place the increment.
The processing line method shall receive an input string, and take the responsibility of deciding if it contains a product data, a user data, a score data, or none. This must be done through properly parsing its contents.
Here is where you can use String.split() to get the name and value of each line, and then evaluate the name to decide where to store the value. And if you want to count all the processed lines, this is where you should place the increment.
Last, main method shall take the responsability of instancing the scanner and passing it when constructing the Reviews object. In this way, you could receive the file name as input argument from the command line, so your program would become flexible.
Realise that the only public methods of your class should be the constructor and the getters. And state variables shuld be private.
Im trying to create a method to find the common factors of 2 given numbers but I can not get the file to compile. All of my curly brackets are closed as I'm aware thats usually almost always the cause of this error. Hopefully someone can help me out!
import java.util.Scanner;
public class E1{
public static void main (String [] args){
Scanner kb = new Scanner(System.in);
double n1,n2;
System.out.println("Enter two numbers");
n1=kb.nextDouble();
n2=kb.nextDouble();
printCommonFactors(n1,n2);
}
//call a method that prints the positive shared factors of the 2 inputed numbers
public static void printCommonFactors(int n1,int n2){
//determining the max/min of the two inputed variables
int max,min;
max=Math.max(n1,n2);
min=Math.min(n1,n2);
//setting up 2 arrays to store the factors
int [] maxFactors = new int [max];
int [] minFactors = new int [min];
int counter1;
for (inti=0;i>max;i++)
if (i%max=0)
counter1++;
maxFactors[counter1]=i;
for (int i=0;i>min;i++)
if (maxFactors[i]%min=0)
maxFactors[i]=
}
}
This is the error I receive:
The reason you are seeing the "reached end of file while parsing" is that the parser expects to find a right-hand-side operand for the equals operator but fails to do so. You end your method with maxFactors[i]=. Binary operators always require right-hand-side operands. In this case, you must place a value after the equals-sign.
Also, it looks like you are trying to apply some principles to Java that you probably pulled from another language. The most obvious one here is that you use replace explicit blocks with white-space. This works for languages like Python, but does not work in Java. Indentation is not significant in Java and only has the effect of improving readability.
This is relevant for your for statements. Because you are not actually using blocks, these statements are actually equivalent:
for (inti=0;i>max;i++)
if (i%max=0)
counter1++;
maxFactors[counter1]=i;
for (inti=0;i>max;i++) {
if (i%max=0) {
counter1++;
}
}
maxFactors[counter1]=i;
This will cause issues with i being referenced out of its scope. The other issue with this is that the for initializer (inti=0;) is missing a space and should be int i = 0.
Other issues include trying to allocate arrays with a non-integer size (must be of type int) and using bad test expressions for your for-loops (i>min will invariably remain true if it is ever true due to your incrementor until an integer overflow is reached).
I'm making a program where the user inputs values for diameter, length, width, base, height. Those values are put through some calculations for area. Area is calculated and spat back out to the user in various different units. After making it I separated it into several submodules (methods in Java).
However, when I separate my input and output modules, it won't compile, because the variables are initialized within the input method.
If I try to define the variables within the method (obviously doesn't work) because I've already defined and initialized the variables within the input method(s).
How can I enable my output method to use the variables initialized by the user in the input methods.
The idea is meant to be that my main is just:
Main
{
inputInteger();
inputReal();
outputCRT(); //CRT = Circle Rectangle Triangle
}
I thought you passed variables between methods like:
outputCRT(int diameter, double length...etc)
{
all my output
}
But (I'm pretty sure) this means that when I call it in my main I'd have to give it values:
Main
{
outputCRT(8, 32.43...etc);
}
But that defeats the whole purpose of users inputting their own values in using the scanner. How can I solve this issue?
Since this is a school projetct, it is likely that your teacher is giving you incremental information...
It appears that your teacher want you to use global variables in the class, and then make you use them. This way, the inputInteger function would set a group of variables, then inputReal would set another group and finaly outputCRT would output the result.
If I get the point you should gather the input in some way in your "input modules" (e.g. inputInteger()), then use the inputs in the "output modules" (e.g. outputCRT(...)).
You can achieve this by returning the results of your input methods and using them as arguments for your output methods. Example:
public static void main(String[] args) {
int diameter = inputInteger();
double length = inputReal();
...
outputCRT(diameter, length, ...);
}
static int inputInteger() {
int value = read input in some way;
return value;
}
static double inputReal() {
double value = read input in some way;
return value;
}
How do I pass an array from my main method to another method? I'm having an error with the parameters. Do I use the return value from main? And since the return value from main is an array, should the parameters for the call of main have brackets? Should there be a value between those brackets?
public class arraysAndMethods {
public void printArray(double[] arr) {
int x = arraysAndMethods.main(double[i] arr);//error with paremeters
for (int i = 0; i < studGrades.lenght; i++)
System.out.print(studGrades[i] + " ");
}// end of printArray method
public static double[] main(String args[]){// double array
java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
System.out.println("What is the size of the class?");
int n = input.nextInt();
double[] arr = new double[n];// declare and initialize array to have n many elements
for (int i = 0; i < arr.length;i++) {// input grades for each students
System.out.println("What is the grade of student #" + (i+1));
arr[i] = input.nextDouble();
} // end of for loop
return arr;
}// end of main method
}// end of class
Just pass the name, not the type.
int x = arraysAndMethods.main(arr);
EDIT:
Besides that, your code shows a few other problems.
main(...) is the entry point to your application. It doesn't make sense to call main(...) from the other method. It should be the other way around.
main(...) HAS TO have the following signature: public static void main(String[] args). You cannot declare it to return an array of double.
This whole thing doesn't make much sense. If you're hoping to have this as the main method of a Java program, this won't work because the main method must have a void return type. Regardless, you have a syntax error here:
int x = arraysAndMethods.main(double[i] arr);//error with paremeters
Instead it should be
int x = arraysAndMethods.main(arr);//error with paremeters
as the variable has already been declared. I'm not sure what you were trying to do with double[i], but that syntax is more like a declaration, i.e.
double[] someArrayName = new double[5];
Your main method is where the program begins execution. In other words you should be calling printArray() from within main, not the other way around
I think I see where the confusion is. Perhaps this will help.
First I think you should understand something very important about Java.
Your main method is the FIRST method that is run.
So let's give a short walk through of how a Java program is created without an IDE.
First, you write your code in a text file and rename it to arraysAndMethods.java when you're done. Next we need to take your code and put it into a form that is usable by the computer it is first compiled down to bytecode with the following from the command line:javac arraysAndMethods.java
After it is compiled you can run the program with this command: java arraysAndMethods
Your program will run if there are no problems.
You say that you want to pass variables things into the main method? Here is how you do that from the command line: java arraysAndMethods 45.6 38.2 5.5 105.3
Looking at your main method, it takes the following arguments: (String args[])
So in your case, the 45.6 38.2 5.5 105.3 would be passed into your main method as an array of strings. With the first entry being 45.6, followed by 38.2, then 5.5 and finally 105.3.
It would look like this in the array: ["45.6"],["38.2"],["5.5"],["105.3"] but they are all Strings and not doubles.
All of this is to say that if you want to pass something in to your main method, you'll either need to do it through the command line, or look up how your individual IDE (i.e. Eclipse, Netbeans, etc.) handles that.
So to recap: The parameters in the main method are coming in from the console unless other specifications are made, and in your case it is returning an array of type double.
I know this is quite verbose, but bear with me, I'm almost done.
When a Java program is run(I'm simplifying a bit here), it comes into the main method and executes the first line it sees. When it's done with that one, it goes onto the next line, and so forth until it gets to the end of the main method. Then the program is done.
So everything MUST be done in the main method. Although you can call other Classes and methods from the main method.
Now that you have the explanation, here is what I would do to fix your code:
public class arraysAndMethods {//Changed from arraysAndMethods to ArraysAndMethods because classes are always capitalized
public static void printArray(double[] arr) {//Added static so this could be used within the same class as the main method.
//int x = arraysAndMethods.main(double[i] arr); No need for this line
for (int i = 0; i < arr.length; i++)// Changed "studGrades.lenght" to arr.length
System.out.print(arr[i] + " ");//Changed "studGrades" to arr
}// end of printArray method
public static void main(String args[]){// Changed the return type to "void". No need to return the double array.
java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
System.out.println("What is the size of the class?");
int n = input.nextInt();
double[] arr = new double[n];// declare and initialize array to have n many elements
for (int i = 0; i < arr.length;i++) {// input grades for each students
System.out.println("What is the grade of student #" + (i+1));
arr[i] = input.nextDouble();
} // end of for loop
printArray(arr);
//return arr; No need for this line
}// end of main method
}// end of class
Please be sure to mark the best answer when you're ready and up-vote any answers or comments you feel helped. Not just for this question, where you are the original poster, but for other question threads as well.
I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.