How to send values through methods - java

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);

Related

Using Scanner to scan through a predefined list of strings in another class, and parse them to Ints in java

Quite a few labs have passed since my previous request for some advice and we are nearing midterms quite quickly! I am currently working on another lab right now and have ran into some slight difficulty that a little advice or guidance might help! Anyways here is whats going on!
I must have 3 classes in total:
(StationRecordMain, StationRecord, and TemperatureData)
He gave us the TemperatureData class pre-written and not able to modify it in anyway. This class holds a huge array of Strings all looking like this
"14762 20180829 89 70 80 9.6" . These are some junk number in the beginning we must throw away, the year month and day, the high temp, the low temp, avg, and difference.
This prewritten class also holds 2 methods in it, (hasNextTempRecord, getNextTempRecord).
My StationRecord class holds the following instance variables:
private int yearMonthDay = 0;
private int max = 0;
private int min = 0;
private int avg = 0;
private double dif = 0;
Finally, my MainStationRecord class holds the Scanner Object:
Scanner scan = new Scanner(tempdata.getNextTempRecord());
, an attempt to use the scanner to read through the predefined strings in the other class.
Anyways, I can supply more code that I have written but didnt want to flood this page with all of it, but those are the basics. I believe I am at a points where I know what I need to do, just need some guidance.
I need to use the Scanner to scan through all of those Strings on the other class (there are like 100 of them, so i'm assuming some sort of loop somewhere)
Then, I need to piece out each one of those strings and store their values in those private instance variables. Finally parsing them to ints and printing them out in the main class. That is where I am lost. Ive never used a scanner in such a way to do a preset of defined strings in a different class, moreover I have no experience on how to chop them up or parse them really.
Thus, if anyone could guide me in the right direction, It would be greatly appreciated! As I said before I can post the rest of my code I have written to make things easier if need be!
Until then thank you for looking!
I think if I understand it, You can easily do something like this: (I don't have complete code of yours, so this is just a suggestion)
class StationRecord {
private int yearMonthDay = 0;
private int max = 0;
private int min = 0;
private int avg = 0;
private double dif = 0;
public StationRecord(int yearMonthDay, int max, int min, int avg, double dif) {
this.yearMonthDay = yearMonthDay;
this.max = max;
this.min = min;
this.avg = avg;
this.dif = dif;
}
// rest of your code
}
public class Main
{
public static void main(String[] args) {
// rest of your codes
while (tempdata.hasNextTempRecord()) {
Scanner scan = new Scanner(tempdata.getNextTempRecord());
scan.next(); // read until a space and I don't save it for throw it away
new StationRecord(scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextDouble());
}
// rest of your codes
}
}
Thanks Andreas for comments too. This is what I understand and write it.

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

Printing to file rather than terminal [duplicate]

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!

Extend below program for acute and obtuse angle triangle | using Sine cos functions

so I want to know how to make a program that will ask multiple questions and lead to multiple values or other questions to build on.
So I was building a "missing side of right triangle" program. Successful after a couple tries I wondered why not make the program solve obtuse or acute triangles. Well, I could program the law of sines and cosines. The problem is I don't know how. I learned the basics of java through 2-3 videos off youtube. I tried to make an if-else nested inside an if-else statement. But this is my code I tried to build upon:
import java.util.*;
import java.lang.Math;
public class MissingSide {
static java.util.Scanner userInput = new Scanner(System.in);
public static void main(String[] args){
int firstSideGiven = 0;
int hypotenuseGiven = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Are you trying to figure out a missing side given the hypotenuse and another side?");
System.out.println("Then this is the place :)");
System.out.print("What is the value of the first side, other than the hypotenuse?");
if (userInput.hasNextInt()) {
firstSideGiven = userInput.nextInt();
}else{
System.out.println("Give me somthing else to work with!");
}
System.out.println("What is your hypotenuse?");
if (userInput.hasNextInt()){
hypotenuseGiven = userInput.nextInt();
}else{
System.out.print("Wait, I want you to think about what you are doing with your life.");
}
System.out.println("Your missing side is: " + (Math.sqrt((Math.pow(hypotenuseGiven, 2)-Math.pow(firstSideGiven, 2)))));
}
}
And now I want to know what to do next, when I attempted to nest everything inside another if statement, it gave me an error I did not understand.
Well It would be great if you can share the problem and/or errors faced during the change.
Here is a basic logic to solve your issue -
You can use Math.cos and Math.sin functions to calculate function value.
These values can be used to calculate the missing side.
Note - Above functions accept value in radian, So change your degree value to radian before usage. i.e. -
double angleInDegree = 354;
double angleInRadian = Math.toRadians(angleInDegree);
double cos = Math.cos(angleInRadian);
Hope it helps. :)

Obtain the largest number in an array of numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is my first time doing java and I am am trying to get the largest number from an array of x numbers using a method called bigNum(). Can anyone tell me why this doesn't work?
class project3
{
public static void main(String args[])
{
int total =0;
int b;
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for (int i=0; i < maxItems; i++)
{
b = EasyIn.getInt();
}
bigNum(b);
}
public static void bigNum(int maxItems)
{
for (int i = 1; i >= maxItems; i++)
{
if (bigNum(b) >= maxItems)
bigNum(b) = maxItems;
}
return bigNum(b);
}
}
You're probably getting compiler errors at this point due to unmatched braces. You want your program to have matched braces, and you also want to avoid having methods inside of other methods.
You want to have something that has the following form
class project3
{
public static void main(String args[])
{
...
}
public static int bigNum(int maxItems[])
{
...
return someInt;
}
}
// capital letter for the class (convention)
public class Project3 {
public static void main(String args[]) {
//int total = 0; // you never used this number
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for(int i = 0; i < maxItems; ++i) {
int newNumber = EasyIn.getInt();
/* you want to put the numbers into an array,
so don't call "bigNum" but put them there: */
numbers[i] = newNumber;
}
// now find the big number:
int bigNumber = bigNum(numbers);
System.out.println("The biggest number: " + bigNumber);
}
// first: change the return type to get the biggest number
// second: pass the reference to the array, not a single number
// public static void bigNum(int maxItems) {
public static int bigNum(int[] items) {
// create big number, assume it's very small:
int bigNumber = Integer.MIN_VALUE;
// this for loop will never run, change it a bit:
//for(int i = 1; i >= maxItems; i++) {
for(int i = 0; i < items.length; i++) {
// your idea is correct, but you can not use the
// method here, see explanations below
// Also don't check for the number of Items, but for
if(items[i] > bigNumber) {
bigNumber = items[i];
}
}
return bigNumber;
}
}
Explanations and further readings
Class name: Java has lots of different naming conventions, but the most common rules are: ClassNames/Types in CamelCase with a Capital at the beginning, variableNames following a similar convention but with a leading small letter. This makes it much easier to read code.
Indentation: Try to use a more consistent indentation. Also supports readability. Actually some other programming languages even rely on correct indentation.
Try to understand what variables and what methods are and how to use them (and return from them, you can not assign values to a method in Java. While you read the latter tutorial focus on return types and how to call methods correctly, you can not return an int when your method is of type void. Also the parameters need to be exactly defined.
Apart from that try to compile your code before you post it. As your code went, it should have thrown lots of compile errors, e.g. bigNum(b) = maxItems; should tell you that the left-hand side of an assignment needs to be a variable. This can help you a lot while tracking down mistakes.
Another error is that for most people EasyIn will not be defined (as it is for me, so the code I posted above might actually not be working, I didn't try). I suppose it's a learning library (we had our AlgoTools back in our first Java lectures). Still it would be nice to tell us what it is and what other imports you use (common mistake when I let my IDE decide my imports for me: java.util.Date and java.sql.Date).
Also try to make clear to yourself what you want to achieve with your program and how. Your algorithm actually looks like you didn't think too much about it: You try to find a biggest number and always check "a big number" against the number of expected items, which then might become "the big number" as well. Or something like that.
Programming is being concise and exact, so make a plan before. If it's too hard for you to think about a solution directly, you can maybe draw it on paper.
And if you then have problems, after compiling, asking your program, asking google, asking stack overflow: provide us with as many details as you can and we will be able to help you without just posting some code.
Good luck!

Categories

Resources