Printing to file rather than terminal [duplicate] - java

This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 5 years ago.
I've made a program for determining the time of a murder. The code I have right now prints exactly what it should to the terminal. I want it printed to a file. However, I'm not supposed to use System.setOut() for this assignment. I'm supposed to print to a file instead of to the terminal.
I know how to write a simple String into a file, the problem here is I already have methods for printing my results to the terminal, and I'm not sure how I "convert" those methods into printing into a file instead.
This is my two printing methods and main method:
Printing 2d array method:
public static void printArray2d(String[][] array2d){
for(int i = 0; i < array2d.length; i++){
for(int j = 0; j < array2d[i].length; j++){
System.out.print(array2d[i][j]);
}
System.out.print("\n");
}
}
Printing full report method:
public static void printReport(String[][] array2d, double arrayMin, double arrayMax){
System.out.println("Time since death probability distribution");
double hours = (arrayMax-arrayMin)/(array2d.length-1);
System.out.printf("Each line corresponds to approximately %.2f hours\n", hours);
System.out.printf("%.2f hours\n", arrayMin);
printArray2d(array2d);
System.out.printf("%.2f hours\n", arrayMax);
}
Main method:
public static void main(String args[]) {
double[] array = cooldownSamples(27, 1000);
double[] counts = countsFromArray(array, 20);
String[][] array2d = array2dFromCounts(counts);
printReport(array2d, minFromArray(array), maxFromArray(array));
}
I can post the entire code if needed.
I am aware that there are similar questions asked earlier, but none of them gave me the help I needed. I also do not have enough reputation to ask follow-up questions to any of the answers given on those threads, so I was forced to ask a new question.
Thanks in advance for any help given!
Additional information:
Even though I said I'm not supposed to use System.setOut(), I have tried using the method and answers given in this thread, without any luck. If the best and most efficient way of doing this is via System.setOut(), I do appreciate answers that make me understand how I can implement this and make it work in my code, even though I'm looking for an alternative method.

It is really simple: right now, you are using a (static) object System.out to do all printing. This object has methods to print, println, and so on.
Instead of using System.out, you create an instance of say PrintWriter and call method on that object, like
PrintWriter writer = new PrintWriter("whatever.txt");
writer.println("whatever");
writer.close();
That is all there is to this. Or even simpler, you could instantiate a PrintStream object. You could then do things such as:
PrintStream out = System.out // or new PrintStream("filename");
doStuff(out);
... with:
public void doStuff(PrintStream out) {
out.println...
And now you have one central place where you decided if you want to print to System.out - or somewhere else!

Related

How to send values through methods

I am stumped trying to send a value through some methods as part of a question which reads
Write the following method: computeDiameter: This method accepts the radius (r) of a circle, and returns it's diameter (2*r)
It's under the "Passing values through different methods", so instead of asking me for a simple variable/formula like
double r;
double diameter = r*2; //along with Scanner and some System out prints
It's asking me to send the value of r through another method, then return the method and print out the new value for r. This is what I have so far
import java.util.*;
public class UserSquares
{
public static void main(String[] args)
{
int r = 2;
int result=0; //I set result=0 hoping to initialize it properly.
computeDiameter(r);
System.out.println(result);
}
public static int computeDiameter(int r)
{
int result = r * 2;
return result;
}
}
This question seemed very simple which is why i tried to tackle it. I know the basics of sending values through a method, but i don't know how to return them. I don't really have money for actual text books (so i settle for quizlet questions and stuff like that), and youtube videos don't help at all so I like coming to the forums to get help when I am really stumped but want to move on with other topics.
(this question is part of a java self test, just thought I should share that as I've asked a number of questions on this site and each time someone responds with something negatively as if I am trying to get you guys to complete my homework for me. I am not taking any Java classes, these questions are just self testing my skills so that when I do major in java programming after i finish highschool, I can have a pretty nice understanding of it. Again, this is not for a test, I am welcome to all types of explanations, as long as it is in the realm of comprehension for a beginner Java student. Please and thank you in advance)
EDIT: Thanks Guys. Immediately after I submitted this I worked on it some more and found a solution so i'll share it
new code
import java.util.*;
public class UserSquares
{
public static void main(String[] args)
{
int total, r = 2;
total = computeDiameter(r);
System.out.println(total);
}
public static int computeDiameter(int value1)
{
int result;
result = value1 * 2;
return result;
}
}
EDIT #2: Holy crap I didn't expect to receive so many solutions so quick. Was about to answer it myself so that it would appear to be done. Sorry for the waste of your time guys, I will read every one of them to see the different solutions you guys offered and learn them so that your time isn't totally wasted. Thanks so much.
EDIT #3: Had a redundant line remaining from my first code that I forgot to take out that went through the compilation and didn't affect the outcome in anyway, but still decided to take it out. Thanks CodeMatrix!
As I said in the comment section.
Go ahead and change this
int result = 0;
computeDiameter(r);
System.out.println(result);
to this
int result = 0; //or you use int result = computeDiameter(r);
result = computeDiameter(r);
System.out.println(result);
its very simple:
int result = computeDiameter(r);
or just
System.out.println(coputeDiameter(r));
You have to assign the value which is being returned from computeDiameter(r) method to the result variable in order to print that.
result = computeDiameter(r);
System.out.println(result);

Problems with calling a method using an array

I'm relevantly new to Java and just started my first semi serious assignment. I'm confident most of my code is working, the only problem is because I've been using classes I can't seem to call a method which uses an array into my main class. Every other method I want to call seems to work. I wonder if anyone has any explanation or easy solution to this?
Thanks in advance for taking time looking into, really appreciate it!
import java.util.Scanner;
public class GeographyQuizMain
{
public static void main(String[] args)
{
takeQuiz();
}
public static void takeQuiz(Question[][] questions)
{
int score = 0;
RandomNumber randomQuestion = new RandomNumber();
//user chooses catergory
int cat = pickCatergory();
//ask 10 questions
for(int i = 0; i < 10;)
{
Scanner answerChoice = new Scanner(System.in);
randomQuestion.dice();
int q = (randomQuestion.dice() - 1);
//checks to see if question as been asked before
if (!questions[cat][q].beenAsked)
{
questions[cat][q].beenAsked = true; //changes question status to beenAsked
System.out.println(questions[cat][q].promt);
String answer = answerChoice.nextLine();
System.out.println("\nYou picked: " + answer + "\nThe correct answer was: " + questions[cat][q].answer + "\n");
if(answer.equals(questions[cat][q].answer))
{
score++;
}
i++;
}
}
System.out.println("That is the end of the quiz!\n"
+ "You got " + score + "/10");
}
Your problem is with the call itself,
This line public static void takeQuiz(Question[][] questions) states that the method will accept a two dimensional array ([][]) of an object named Question.
On the other hand, your call - takeQuiz(); passes no array of such.
You should initialise an array of such to make this compile and pass it to the function. i.e.
Question[][] questionArray = GenerateQuestionArray(); //you should write this method
takeQuiz(questionArray);
Like you stated, it's clearly you're new to Java and I strongly suggest you to read the instructions and the information provided to you in class about that. I bet the details of Object initialisation, methods and arrays are covered there.
It seems that problem with your method call, in your method takeQuiz(); is taking 2 dimensional array for questions but at the calling time you are not providing that parameter so, compiler not able to found the method.
That's the problem.
try to use like this, this is simple an example for you. replace this with your actual values.
String[][] questions= new String[3][3];
takeQuiz(questions);
this will work.
You have called your method takeQuiz() without actually supplying its arguments Question[][] questions

Possible to count amount of outputs from System.out.println, Java?

due to a complex issue which I do not want to enter here, I am not able to count a number of created objects(let's say apples) in a complex Java class, using a simple counter as soon as an apple is created. Therefore I was thinking of an alternativ but do not know how to realize it; if it is at all an option:
A for-loop connected to System.out.println("Apples:" + apples) gives me as many outputs as there are apples. - Which is fine. Now I have to store the number of outputs in a variable - how would you do this - is it possible at all, as the output is displayed in the console?
Thanks in advance!
you can wrap System.out.println() with your own println method that in addition to printing will count, and use that one instead of println in your loop:
private static int counter = 0;
public static void myPrintln(String str) {
counter++;
System.out.println(str);
}

Beginner Java Scope Issue [duplicate]

This question already has an answer here:
Beginner Java: Variable Scope Issue
(1 answer)
Closed 7 years ago.
I'm new to programming and seem to be running into issues with when a variable, class, etc can and can't be referenced. Below is an example, hoping one of you can fix the specific issue but also help me understand it more broadly so I don't run into it again and again.
to try and avoid posting a bunch of code please note that a Question class is defined as well as a setText, setAnswer, checkAnswer, and display method are all defined elsewhere (all public).
The relevant code is below and I have two questions:
Why is the variable first not recognized in the method presentQuestion()?
At the very end there, why can't I just call the method checkAnswer() on first, i.e. why can't I just do first.checkAnswer(response);? Why do I have to define it in a new variable: boolean outcome = first.checkAnswer(response);?
Code:
/**
* This program shows a simple quiz with two questions.
*/
public class QuestionDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Question first = new Question();
first.setText("Who was the inventor of Java?");
first.setAnswer("James Gosling");
Question second = new Question();
second.setText("Who was the founder of Udacity?");
second.setAnswer("Sebastian Thrun");
int score = 0;
score = score + presentQuestion(first, in);
// Present the second question
score = score + presentQuestion(second, in);
System.out.println("Your score: " + score);
}
/**
* Presents a question to the user and obtains a response.
* #param q the question to present
* #param in the scanner from which to read the user input
* #return the score (1 if correct, 0 if incorrect);
*/
public static int presentQuestion(Question q, Scanner in) {
// Display the first question
first.display();
System.out.println("Your answer:");
String response = in.nextLine();
// Check whether the response was correct
// If so, print "true" and return 1
// Otherwise, print "false" and return 0
boolean outcome = first.checkAnswer(response);
System.out.println(outcome);
if (outcome) {
return 1;
}
else {
return 0;
}
}
}
The reason you can't use the variable first inside presentQuestion is because it's defined in main, and therefore not visible outside of main. Isn't this precisely why you gave presentQuestion its Question q parameter, however?
It seems to me that this is what you want to do:
public static int presentQuestion(Question q, Scanner in)
{
// Display the first question
q.display();
System.out.println("Your answer:");
String response = in.nextLine();
// Check whether the response was correct
// If so, print "true" and return 1
// Otherwise, print "false" and return 0
boolean outcome = q.checkAnswer(response);
System.out.println(outcome);
if (outcome) {
return 1;
} else {
return 0;
}
}
Note that references to first have been replaced by references to q.
To try and clear up what I imagine your confusion may consist in, imagine if presentQuestion were called from another method than main, in which case no first variable would be declared at all. What would then happen to the references to first inside of presentQuestion, now not referring to anything at all? This is why you need to explicitly pass the data you want as parameters. Different methods are independent blocks of code, and you can't intermingle variable references between them even if they happen to call each other.
As for question 2, there should indeed be no problem with checking if(q.checkAnswer(response)) directly, without using the outcome variable. I'm guessing you were simply confused by the error emitted by the compiler when first wasn't recognized again.
first is a local variable, that means it can only be accessed inside the method in which it is defined.
You don't have to put the result of checkAnswer() into a boolean before using it. Actually, if (checkAnswer(response)) { ... } is valid.
presentQuestion takes a question as a parameter. In main, you're calling it on the first question, and then on the second question; it looks like the intent is that you use presentQuestion on the first question, and then on the second question. So far, so good.
The problem is that in presentQuestion, you're referring to the question (which could be the first or the second question) as q in the parameter list. All you need to do is use q instead of first in the rest of the method.
When I was new to programming, I had this problem as well! Then I found out it is very simple.
For your first question, first is declared in the main method and you want to use it in presentQuestion method. But presentQuestion and main are different methods! So you can't get to first in presentQuestion. As you can see, there is a Question-typed parameter in the presentQuestion method. This is like you telling first, "Come here, man! And then change your name to q." When you do pass the argument first to presentQuestion,
presentQuestion (first, in);
first comes to the pressentQuestion method with its name being as q. So you should use q instead of first in the presentQuestion method.
Now the second question, using a variable in this context is not needed. But to increase efficiency, use a boolean variable to store the result of checkAnswer. Let's imagine what happens if you don't use a boolean variable.
System.out.println(q.checkAnswer(response));
if (q.checkAnswer(response)) {
return 1;
} else {
return 0;
}
See? you called q.checkAnswer twice! This would slow down your program so you should use a boolean variable.

Java text analysis program

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.

Categories

Resources