Methods and declaration java - java

I am trying to make an program to determine averages for school. I am going to have all the files saved to the computer so its easy to access them for multiple uses. I stated to create multiple methods and discovered a problem. I have the user input for a subject in the startup method but in the main method, sub (the subject string) is used and its says "sub cannot be resolved to a variable" I understand why it say this but I am unsure how to fix.
Here is my code:
public class Calculator {
static int x;
static int b;
public static void startup() {
System.out.println("**Receiving User**");
String user = System.getProperty("user.home");
System.out.println("**Checking Directories**");
boolean dir = new File(user + "/Library/Application Support/Average_Calculator/Settings/").mkdirs();
if (dir) {
System.out.println("**Directory Created at:" + user + "/Library/Application Support/Average_Calculator/**");
} else {
System.out.println("**Directory Has Already Been Created at:" + user
+ "/Library/Application Support/Average_Calculator/**");
}
System.out.println("Welcome to the Average Calculator");
System.out.println("Please input the subject average you want to calculate(no caps)");
Scanner scan = new Scanner(System.in);
String sub = scan.nextLine();
// System.out.println(sub);
try {
// System.out.println("It Does!");
FileOutputStream saveFile = new FileOutputStream(
user + "/Library/Application Support/Average_Calculator/" + sub + ".sav");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
FileOutputStream SetsaveFile = new FileOutputStream(
user + "/Library/Application Support/Average_Calculator/Settings/" + "Setting" + sub + ".sav");
ObjectOutputStream setsave = new ObjectOutputStream(SetsaveFile);
// Create an ObjectOutputStream to put objects into save file.
// Close the file.
save.close();
setsave.close();// This also closes saveFile.
} catch (Exception exc) {
exc.printStackTrace(); // If there was an error, print the info.
}
}
public static void main(String[] args) {
startup();
System.out.println(sub);
try {
// Open file to read from, named SavedObj.sav.
FileInputStream saveFile = new FileInputStream(sub + ".sav");
// Create an ObjectInputStream to get objects from save file.
ObjectInputStream save = new ObjectInputStream(saveFile);
x = (Integer) save.readObject();
b = (Integer) save.readObject();
// Close the file.
save.close(); // This also closes saveFile.
} catch (Exception exc) {
// exc.printStackTrace(); // If there was an error, print the info.
}
// Print the values, to see that they've been recovered.
System.out.println(x);
System.out.println(b);
// All done.
}
}
Thanks for the help!
PS I am new to methods and classes, an explanation would be greatly appreciated!

sub is currently a local variable of startup(), so main() does not have access to it.
One solution is to have startup() return the value of sub, and to have main() use that returned value.
A second solution would be to declare sub (and any other shared variables) as a static variable of the Calculator class, which would place it within the scope of both static methods. In this case, you must no longer declare sub locally within startup(), since that would cause the method to ignore the static variable with the same name.

You are declaring sub in your startup method but trying to access it in your main method. The scope of variables declared in methods is limited to that method; that means that once you leave the method, the variable is no longer accessible. If you want to access a variable both methods one option is to make it a property of the class like you did for x and b. Another option is to return the value of sub at the end of your startup method then simply print your call to the method in main.
Here is a good explanation about classes.
Here is a good explanation about methods (you can ignore the part about functions; the explanation for methods is still good).

Your startup function is returning a void. Change this line:
public static void startup() {
to this:
public static String startup() {
and this line:
startup();
to this:
String sub = startup();

Related

Console throws exception: java.lang.NullPointerException when I try to add and print values of array variables

I am a rookie java programmer working on an assignment. However, I am stuck with one small error which I cannot seem to figure it out. Any help would be appreciated.
In this program, I am trying to read the file and storing the data of the file in variables with the array size equal to the number of lines in the file.
For example: If there are 10 lines in the file, then the array size of the variables should also be 10. After storing them, I want to display them. (I already know how to display the data).
But I have a java.lang.NullPointerException error.
I think that the error in my code exists either in the setVariable method of the Athlete class or the readFile function in main.
The setVariable method is used to set the data extracted from the file to the array type variables (First Name, Last Name, Id Number, Citizenship, Time).
The readFile function is used to read the data from the file, store that data in a temporary variable, and send the value of the temporary variable to setVariable as a parameter.
The file contains the following values in respective order:
("FirstName LastName IdNumber Citizenship Time")
class Athlete
{
private
String[] firstName;
String[] lastName;
String[] citizen;
int[] id;
float[] time;
public
void Athlete(int s) //Setting the size of the array variables.
{
firstName = new String[s];
lastName = new String[s];
citizen = new String[s];
id = new int[s];
time = new float[s];
}
void setVariables(String fName,String lName, int idNumber, String citizenship, float t, int lineNumber)
{
firstName[lineNumber]=fName;
lastName[lineNumber]=lName;
id[lineNumber]=idNumber;
citizen[lineNumber]=citizenship;
time[lineNumber]=t;
System.out.println(firstName[lineNumber]+"\t"+lastName[lineNumber]+"\t"+id[lineNumber]+"\t"+citizen[lineNumber]+"\t"+time[lineNumber]);
}
}
//Main CLASS
public class marathon {
static Scanner console;
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//STEP-1: FILE
openFile(); //Step 1.1: Open the File
System.exit(0);
}
static void openFile()
{
try
{
console = new Scanner (new File("C:/Eclipse_Wokspace/Assignment-2/src/Marathon.txt"));
//Step 1.2: Read the File
readFile();
}
catch (Exception e)
{
System.out.println("File did not open because of "+e);
}
} static void readFile()
{
int size=0;
Athlete athlete = new Athlete();
while (console.hasNext())
{
String a,b,d; int c; float e; //Read the data in the file and store them in temporary variables.
a=console.next(); //First Name
b=console.next(); //Last Name
c=console.nextInt(); //ID-Number
d=console.next(); //Citizenship
e=console.nextFloat(); //Time
//Step 1.3: Store File Data
athlete.setVariables(a, b, c, d, e, size);
size++;
}
athlete.Athlete(size);
}
}
Marathon txt file
Error
Reason why I cant embed the images in this post
Not allowing me to upload any image on this post.
Your Athlete constructor expects a size argument. However, your first creation of an Athlete uses no arguments, so this defaults to Java's "default constructor" which does nothing but call super, basically.
So you need to use your constructor that actually allocates those arrays you are shortly going to populate. The problem is, the way the code is written, you don't know the size until after you've read your entire file and attempted to modify the Athlete.
There are many approaches you could take and a number of style and semantic fixes I could propose for this file, but I suggest starting with a single pass through your file to get the size, and then use that to call the constructor with the size as its argument. Then you can safely mutate those arrays in a second pass. This should get you started.

Java Passing variables, avoiding toString hash

I know this has been asked before, but not in a way I understood, because I am dumb.
So.
I need to take some variables into a class, compare them against something, and then return the higher of the two. In the long run, I need to compare against a running total, but for my problem, I think the issue is considerably more fundamental. I'm not understanding how to pass a variable BACK to my main class.
import java.io.*;
public class testing123 {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass();
System.out.println("Your numbers combined is " +numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
public static Integer testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
numbersCombined = numbersCombined;
}
else {
numbersCombined = 100;
}
System.out.println(numbersCombined);
return numbersCombined;
}
}
If I remove the return, this will print the numbersCombined, but that's all it does. With the return in place, it doesn't execute the print line above the return, and first prints the original numbersCombined (which it shouldn't if you use, say, 10 and 20, since that's less than 100), and then prints testClass#76046e53 rather than the actual value. I know there's a way to override it, but the answers I've found don't work for me.
I know this answer: http://www.google.com/url?q=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F29140402%2Fhow-do-i-print-my-java-object-without-getting-sometype2f92e0f4&sa=D&sntz=1&usg=AFQjCNGIzxlBSH8xIS7hurKe6_Euc7B8RQ
is the basic problem I'm encountering, but the overrides listed aren't really working for me, and I want integer anyway, rather than string.
In the end, what I'm "really" doing is taking a series of 4 numbers from a user, then using this function to compare whether THIS series of numbers is higher than the previous maximum, and if it is, that's the new maximum moving forward, with a loop until the user is done entering serieses of 4 numbers, and then finally printing the maximum.
I was able to write this without ANY functions, all inline, easy as pie. But once I send the comparison to a function, I don't understand how to send it back, and I've spent all day trying to understand the concept. ALL DAY. So, while I know it's going to be a stupid answer, that's because I'm stupid, but not because I didn't try (sorry, kind of defensive. Frustrated).
Fundamentally, I want to send two (this example is just one) variables to a class, compare them, change ONE of them, and return it to the main class. In this example, I'm just trying to send ONE variable, compare it, and the send it back.
You need to call the method within TestClass. Your code is already returning an integer from that method.
Once you instantiate the class run testClass.testClass(numbers)
The way you're throwing around pseudo-global variables between classes is probably the problem. Pass them through the calls like above, rather than implicitly.
Try to do something like this:
import java.io.*;
public class HelloWorld{
public static void main(String []args){
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass(numbersCombined); // constructor should be like this
System.out.println("Your numbers combined is " + numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
Integer numbersCombined;
// This is a constructor
public testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
this.numbersCombined = numbersCombined; // use this to represent the object
} else {
this.numbersCombined = 100;
}
System.out.println(numbersCombined);
}
// Add method toString()
public String toString() {
return this.numbersCombined.toString();
}
}

How do I call a list from other classes? [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 7 years ago.
Improve this question
Okay so I am building a program that will sort grades and records of students. It is a command-line program and when run it will start by asking for user input. there are several commands such as exit(exits program), load [file name](loads a file name), student [student name] (loads student records), etc. the others are not important. Well basically what I am wondering and what I am stuck on is all those functions will be in separate classes and will be called when the user inputs a specific command, but if I put the "load" command in its own class, then how do I get it to share its information with the other classes? I know I have to use BufferReader to read in the files, but how would I go implementing my load class, or if there is a better way feel free to say so. here is my code so far. there isn't much on my other classes because I feel like I need to figure out how to read in and share the file with the other classes first.
import java.util.*;
import java.io.*;
public class program7
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Grade Stats by ");
System.out.print(">");
while(scan.hasNextLine())
{
String input = scan.nextLine();
if(input.equals("exit"))
{
System.exit(0);
}
else if(input.equals("help"))
{
System.out.println("exit - program closes.");
System.out.println("load [filename] - loads a class database specified in [filename].");
System.out.println("students - prints out a list of students from the class, along ");
System.out.println(" with total points, and final grades for each student.");
System.out.println("assignments - prints out a list of assignments from the file, along with points possible");
System.out.println("student [student name] - Prints report for the student");
System.out.print(">");
}
else if(input.contains("load"))
{
String[] split = input.split(" ");
LoadStudents loadStudents = new LoadStudents(split[1]);
loadStudents.getFromFile();
System.out.print(">");
}
else if(input.equals("students"))
{
Students students = new Students();
students.printer();
System.out.print(">");
}
else if(input.equals("assignments"))
{
System.out.print(">");
}
else if(input.contains("student"))
{
String[] split = input.split(" ");
Student student = new Student(split[1]);
System.out.print(">");
}
else if(input.contains("assignment"))
{
}
else if(input.equals("grades"))
{
}
else
{
System.out.println("exit - program closes.");
System.out.println("load [filename] - loads a class database specified in [filename].");
System.out.println("students - prints out a list of students from the class, along ");
System.out.println(" with total points, and final grades for each student.");
System.out.println("assignments - prints out a list of assignments from the file, along with points possible");
System.out.println("student [student name] - Prints report for the student");
System.out.print(">");
}
}
}
}
That is my main class, but here is my Load and Students class.
import java.util.*;
import java.io.*;
public class LoadStudents
{
public String inputFile;
public List<Object> info = new ArrayList<Object>();
public LoadStudents(String inputFile)
{
this.inputFile = inputFile;
}
public List<Object> getFromFile()
{
try
{
BufferedReader in = new BufferedReader(new FileReader(inputFile));
try
{
String line = "";
while(in.readLine() != null)
{
line = in.readLine();
info.add(line);
}
}
catch(IOException e)
{
System.err.println("Exception, man");
}
finally
{
in.close();
}
}
catch(FileNotFoundException e)
{
System.err.println("File wasnt found ");
}
catch(IOException e)
{
System.err.println("Exception, man");
}
return info;
}
}
import java.util.*;
public class Students
{
public Students()
{
}
public void printer()
{
List<Object> info = (new LoadStudents()).getFromFile();
for (int x = 0; x<info.size(); x++)
{
System.out.println(info.get(x));
}
}
}
the Students class isnt finished but I am trying to figure out how to read the list from other classes. I have done research and have seen 3 similar problems, but they there is still something I'm missing because I keep getting the error
.\Students.java:11: error: constructor Load in class Load cannot be applied to g
iven types;
List<Object> info = (new LoadStudents()).getFromFile();
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
I understand it wants input, but I want it to use the previous input the user gives it when he inputs the command "input [whateverfile]".
Can anyone tell me how I can call that list my Load class produces to any other class?
There are many ways to do this. My suggestion is that your Load class should be a factory that actually creates a list of Student from the file, and not a list of strings.
Here are more suggestions:
Load class could have all methods statics and it could be non-instantiable. The fields you have in this class are useless after the file is read, you can just pass them to the static method as parameters.
Load is not a nice name for that class. LoadStudents is more meaningful, or even better StudentFactory.
Load and Student probably don't need to be public, package-private are be enough. Same for all the methods in these classes. Always use the lowest visibility possible.
data() is not a nice name for that method either. Something like getStudents(), or if you follow above advice, getFromFile(), is more meaningful.
Always print/log the stacktrace of the exceptions, otherwise you won't even know what/where it happened.
Instead of making the user type the whole commands, put a number on each option and let user select by number, that's faster to type and you avoid typo errors as well.
Only import the classes you're actually working with and not the whole package, that will make the compilation faster (unless you're importing a lot of classes from that package, which is not the case here).
EDIT: since you still don't understand what I mean, here's an example:
class StudentFactory {
private static List<Student> listCache = new ArrayList<>();
static List<Student> getStudents(final String filePath) {
if (listCache.isEmpty() {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(filePath));
String line;
while((line = in.readLine()) != null) {
// Parse the line and create a Student instance from it, then add it to the list
listCache.add(student);
}
} catch(IOException e) {
System.err.println("Exception, man");
e.printStackTrace();
} catch(FileNotFoundException e) {
System.err.println("File wasnt found ");
e.printStackTrace();
} finally {
if (in != null) in.close();
}
}
return listCache;
}
private StudentFactory() {
// Avoid instantiation
}
}
Then you can just do
final List<Student> listOfStudents = StudentFactory.getStudents(filePath);
from anywhere in your code to get a list of students. filePath can be null if you already passed it previously.

Java.lang.nullpointer exception in a sourcecode

Okay, here is the sourcecode -
The program should be able to run a) if no arguments are given, ask for a file name with args
b) if there are args, get these args as parameters for method 'parametr'
The problem is, program works fine with the file input, but if the args are given from CMD or Eclipse. From my point of view, the code is totally fine, but IDK...
//block of a code, thats creates a output file + that should hand
//over a Integer to method 'parametr' from the args array
else if (args.length > 0) {
try {
PrintStream ps = new PrintStream("vystup.txt");
for (int i = 0; i < args.length; i++) {
parametr(Integer.parseInt(args[i]));
}
ps.close();
}
catch (Exception g) {
g.printStackTrace();
System.exit(1);
}
}
}
this points at a Method 'parametr' >>
// this method should just create an array named 'pseudoposloupnost'via method //'Posloupnost' and then copy this array into a new array named 'serazenaPosloupnost'
// rest of the code is not important
public static void parametr (int n) {
Posloupnost(n); //Another method to count array 'pseudo...'
serazenaPosloupnost = new int [pseudoposloupnost.length];
for (int k = 0; k < pseudoposloupnost.length; k++) {
serazenaPosloupnost[k] = pseudoposloupnost[k];
}
serazeniPosloupnosti(serazenaPosloupnost);
ps.println(pseudoposloupnost.length + " " + Arrays.toString(pseudoposloupnost));
ps.println(serazenaPosloupnost.length + " " + Arrays.toString(serazenaPosloupnost));
ps.println();
drawPosloupnost();
}
Java points at these two blocks as a nullpointer exception when I try to run the code from CMD with arguments given.
I think you have two variables called ps. One of them is local to your try block, and the other is (probably) a static class variable. "Probably" because you don't show us its declaration.
Simplified down:
public class myClass {
private static PrintStream ps; // we'll refer to this as "ps1"
public static void parametr(int n) {
...
ps.println("foo");
}
public static void myMethod() {
try {
PrintStream ps =
new PrintStream("x.txt"); // we'll refer to this as "ps2"
parametr(1);
ps.close();
} catch (...) {
}
}
}
This is a matter of scope.
ps1 and ps2 are two different variables.
ps1 is defined but never initialised, so it has a value of null throughout the program.
ps2 is local to the try block surrounding it. It is not passed to parametr(), therefore parametr() doesn't see it.
When parametr() executes ps.println(), it looks at ps1, which is null, hence the NullPointerException.
One way you could fix this is to not create ps1, and pass ps2 into parametr():
public class myClass {
public static void parametr(int n, PrintStream printStream) {
...
printStream.println("foo");
}
public static void myMethod() {
try {
PrintStream ps =
new PrintStream("x.txt"); // we'll refer to this as "ps2"
parametr(1, ps);
ps.close();
} catch (...) {
}
}
}
It's generally good to do this kind of thing, because you can see exactly what variables your methods need and can touch.
Another way you could fix it is by removing the PrintStream from the ps = ... statement in the try block, so you assign to the class variable. This is often not such a good idea, because you're hiding the management of that PrintStream from the reader of the code.
One other tip: you call a method posloupnost(n) (I changed its first letter to lowercase, because Java programmers prefer that). I can guess that either:
this method is a waste of time (because its only parameter is an integer, so the method can't change it)
this method has side effects on a class variable or a global variable.
It's almost always better to pass in the objects that will be affected by the method, so that it's clear what effects it will have. Even if you're going to be printing to the screen, it's better to do:
System.out.println(posloupnost(n));
... or ...
posloupnost(n, System.out);

Need to print boss names from text file recursively

In my Java class, we're just now learning about recursion and this is the problem that I'm asked to do. In a text file, there are several lines of employees in this format: Name,Hours,Wage,Boss.
I have a scanner set up and everything works well, except the thing is there is one main boss ("N/A" is what is under his boss field) and then it trees off into different people (in the text file they are not in order.) The task is to print them in order of ranking, ie:
BossName : Wage
--2nd Employee : Wage
----3rd Employee : Wage
-- 4th Employee : Wage
This has to be done recursively, and I'm completely stumped. I just can't find out what to put as the "base case" or how to even start it.
Thanks for any help, it's greatly appreciated.
You need to write a method which finds all employees with a given boss. Then write another method which, given a boss name and a level, finds the boss and pretty prints him/her, then finds all its employees (by calling the 1st method) and recursively calls itself for each employee.
Call this second method from main with "N/A" as the boss name and 1 as level.
well check this simple source code, maybe it will get you started...
import java.io.*;
class test
{
//main method
public static void main (String[] args) throws java.io.IOException
{
String filename = "input.txt";
// Initialize the reader
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
//recursive call
myRecursion(reader);
} //end main
//method using recursion to read a file
static void myRecursion(BufferedReader br)
{
String s1 = "";
try {
s1 = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
if(s1 == null)
return;
else
{
System.out.println (s1);
myRecursion(br);
return;
}
} //end method
} //end class
The input.txt is:
one
two
three

Categories

Resources