class constants and file imports for java - java

I'm pretty much trying to use a class constant to declare as a file but get an error.
import java.awt.*;
import java.util.*;
import java.io.*;
public class BabyNames {
public static final Scanner NAME=new Scanner(new File("names.txt")); //specifically this part
public static final int YEAR=1900; //generates the error
public static final int LS=11;
public static final int WIDTH=50;
public static void main(String[] args) throws FileNotFoundException{
intro();
personName();
graph();
}
// Error contained:
// BabyNames.java:6: error: unreported exception FileNotFoundException; must be caught or
// declared to be thrown
// public static final Scanner NAME=new Scanner(new File("names.txt"));
^
//1 error
this is not all of the program but dont think the rest is required.
sorry if my method of asking was funky, first time. thanks much.

Technically you can use a static initializer block to set your staic final Scanner variable. Inside the initializer block you can use try/catch:
public static final Scanner NAME;
static {
// Be sure scanner is initialized even in the case of an exception
Scanner scanner = null;
try {
new Scanner(new File("names.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
NAME = scanner;
}
BUT: It is bad style to hold an instance of a class like Scanner as a static constant. A Scanner is a one way object. You are about to consume the file content and that's it. It doesn't make sense to hold such an object as a constant and much less if it is public.
A static variable will be intialized as soon as the class is loaded and lives as long as your program. In most cases this is not what you want.
A better approach would be to make it an instance variable and initilize it in the constructor. And make it private to the class. You can hold the file name as a constant and create the constructor to accept any file name. The methods intro(), personName() and graph() can be made instance methods, too.
public class BabyNames {
public static final String NAMES_FILE_NAME = "names.txt";
public static final int YEAR=1900;
public static final int LS=11;
public static final int WIDTH=50;
private final Scanner name;
public BabyNames(String fileName) throws FileNotFoundException {
name = new Scanner(new File(fileName));
}
public static void main(String[] args) throws FileNotFoundException {
BabyNames babyNames = new BabyNames(NAMES_FILE_NAME);
babyNames.intro();
babyNames.personName();
babyNames.graph();
}
public void graph() {
// ...
}
public void personName() {
// ...
}
public void intro() {
// ...
}
// ...
}
As a consequence the Scanner variable is only known to the BabyNames class and lives as long as the particular BabyNames instance. This is more modular, better to maintain and easier to test. E.g. you can write a unit test and initialize your class with a test file.

You need a try catch around that code.
That's what "must be caught or declared to be thrown" means.
Read this : doc oracle

There are two types of Exception :
1) checked Exception: those should be handle at compile time (by using try,catch,throws)
2) unchecked Exception: No compiler error for these exception but at run time exception may occurs.
Your case is first one FileNotFoundException is checked exception so either you have to write that line inside try catch block or you have to use keyword throws. to pass exception handling to calling method.

Related

Calling scanner parameter

Ive created two classes, Method and ActionClass. in Mehod class i created passingParameters method with Scanner parameter and in ActionClass i created an object and called passingParameters method as you see below. but i dont know how to call Scanner parameter. it looks like there is difference between calling Scanner and other parameters. or im wrong? how can i call Scanner in ActionClass?
public class Method{
public void passingParameters(Scanner input){
int numInput=input.nextInt();
System.out.println(numInput);
}
}
public class ActionClass {
public static void main(String[] args) {
Method newObject=new Method(how to call Scanner? );
newObject.passingParameters();
}
It could go something like this:
If you want to utilize a Scanner object as you have indicated within your example main() method of the ActionClass class then you would need to create a Constructor within the Method Class that accepts a Scanner object:
package whateverpackage;
import java.util.Scanner;
public class Method {
// Declare a Scanner Object field.
// This will make the Object global
// to the entire Class.
private Scanner scannerInput;
// Class Constructor
public Method (Scanner input) {
this.scannerInput = input;
}
public void passingParameters(){
System.out.println("Enter a integer value for Parameter: ");
int numInput = scannerInput.nextInt();
input.nextLine(); // Empty scanner buffer
System.out.println("Supplied value was: " + numInput);
}
}
And then your ActionClass:
package whateverpackage;
import java.util.Scanner;
public class ActionClass {
public static void main(String[] args) {
Method newObject = new Method(new Scanner(System.in));
newObject.passingParameters();
}
}
This is particularly handy if you intend to extensively use the Scanner object within the Method class for various methods. If however you only intend to sporadically use a Scanner object within the Method class then I think the way #user7 has described to do it in comment may be the way to go in which case a Constructor is not required to carry out the task:
package whateverpackage;
import java.util.Scanner;
public class Method {
// Method accepts a Scanner Object as an argument.
public void passingParameters(Scanner input){
System.out.println("Enter a integer value for Parameter: ");
int numInput = input.nextInt();
input.nextLine(); // Empty scanner buffer
System.out.println("Supplied value was: " + numInput);
}
}
And then your ActionClass:
package whateverpackage;
import java.util.Scanner;
public class ActionClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Method newObject = new Method();
newObject.passingParameters(scanner);
}
}
The Scanner object can also be declared as a Class field and be global within the ActionClass class and then be utilized from any methods within that class without the need to always declare a new instance of Scanner. However the the Object would need to be declared as static since the main() method is a static method. Any method within the ActionClass class using this Scanner object would then also need to be declared as static. Not a big deal in this case but there will come a time when it can be (here's some interesting reading about static). To get around this don't use the object within the main() method, use a different method altogether:
package whateverpackage;
import java.util.Scanner;
public class ActionClass {
private Scanner scanner = new Scanner(System.in);
// *****************************************
public static void main(String[] args) {
new ActionClass().startApp(args);
}
// *****************************************
private void startApp(String[] args) {
Method newObject = new Method();
newObject.passingParameters(scanner);
justAnotherMethod();
}
private void justAnotherMethod () {
System.out.println("What's your name: ");
String name = scanner.nextLine();
System.out.println("Your Name is: " + name);
}
}

How to handle Exception from Singleton java?

I have a singleton class
public class SingletonText {
private static final CompositeText text = new CompositeText(new TextReader("text/text.txt").readFile());
public SingletonText() {}
public static CompositeText getInstance() {
return text;
}}
And TextReader constructor that could throw FileNameEception
public TextReader(String filename) throws FileNameException{
if(!filename.matches("[A-Za-z0-9]*\\.txt"))
throw new FileNameException("Wrong file name!");
file = new File(filename);
}
How can I rethrow it to main and catch it there?
Main class
public class TextRunner {
public static void main(String[] args) {
// write your code here
SingletonText.getInstance().parse();
System.out.println("Parsed text:\n");
SingletonText.getInstance().print();
System.out.println("\n\n(Var8)Task1:");
SortWords.sortWords(SingletonText.getInstance().getText().toString(), "^[AEIOUaeiou].*", new FirstLetterComparator());
System.out.println("\n\n(Var9)Task2:");
SortWords.sortWords(SingletonText.getInstance().getText().toString(), "^[A-Za-z].*", new LetterColComparator());
System.out.println("\n\n(Var16)Task3:");
String result = SubStringReplace.replace(SingletonText.getInstance()
.searchSentence(".*IfElseDemo.*"), 3, "EPAM");
System.out.println(result);
}}
Static block is executed only when class is loaded for the first time, so you can have something as below which will allow you to re-throw the exception. In you main method, you will surround getInstance() invocation in a try-catch block and then in catch you can do whatever you are looking for.
In case of exception, this exception will be thrown and re-thrown (from you static block) only once, at time of class loading. What #Alexander Pogrebnyak has said is also true.
Looking at the code you have provided, since you are always reading text/text.txt files so below approach will work. In case you are looking to read different files and then re-throwing exception then that becomes all together a different story, and you hadn't asked that part neither the code you have provided shows the same. In any case, if that's what you are looking for then:
you need to create a singleton object of your CompositeText class.
create a setter method will create an object TextReader class using the file name string passed.
that setter method will have the try-catch block, and in the catch block you will re-throw the exception so that you can catch again in main method.
P.S.: since static blocks are executed only once when class is loaded and class is loaded only once per JVM (until you have custom class loaders and overriding the behavior) so this ensures that this singleton is thread-safe.
Code:
public class SingletonText {
private static CompositeText text = null;
static{
try {
text = new CompositeText(new TextReader("text/text.txt").readFile());
} catch (FileNameException e) {
// TODO: re-throw whatever you want
}
}
public SingletonText() {}
public static CompositeText getInstance() {
return text;
}
}
try to lazy initialze the singleton.
something like this:
public class SingletonText {
private static CompositeText text;
public SingletonText() {
}
public static CompositeText getInstance() {
if (text ==null) {
text = new CompositeText(new TextReader("text/text.txt").readFile());
}
return text;
}
}
Also, you need to declare the constructor private, and if it multi-threaded application you need to synchronized the new statement with double check locking. see this in wiki:
https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
Enjoy..
You will get java.lang.ExceptionInInitializerError when your singleton static initializer will fail.
As a cause it will have your FileNameException.
If you don't do anything, default exception handler will print the whole stack trace to standard error.

Scanner Object Error

I don't understand why I always get an error whenever I create a new object from the Scanner class.
I have JDK 1.8.0.25
import java.util.Scanner;
public static Scanner input = new Scanner (System.in);
public class NewClass {
public static void main(String args[]) {
System.out.print("Hello");
}
}
You can't define variable outside the class, so define your scanner within your class like:
public class NewClass {
public static Scanner input = new Scanner (System.in);
..
}
Static is a class variable and details about the variables are here
It seems to me you are trying to write java using a Text editor. My suggestion is to use an IDE (NetBeans is my favorite, but Eclipse is a very common choice) and to follow Oracle lessons on the site. As for your problem : curly braces denote the start and end of a class, fields are declared inside of a class, so they must go after the first open braces.
Also : try to avoid using the static and public modifiers in fields.
You can't just define a variable, even if it is a static variable in the middle of nowhere - it should be defined inside a class. E.g.:
import java.util.Scanner;
public class NewClass {
// Moved inside the class
public static Scanner input = new Scanner (System.in);
public static void main(String args[]) {
System.out.print("Hello");
}
}

Java 1.6: Public variable won't work

I'm very new to java (about 1 week), and i'm stuck on a bit of code. I've looked everywhere, but nothing works. I'm trying to send a string from a MainProgram class to a FileWriter class.
MainProgram:
import java.util.*;
public class MainProgram {
public static void main(String[] args){
static answer;
Scanner Input = new Scanner(System.in);
System.out.println("Enter something so I can write it to a file");
String answer = Input.nextLine();
System.out.print("You said ");
System.out.print(answer);
}
}
FileWriter:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class FileWriter{
public static void SaveList() throws FileNotFoundException{
PrintWriter writer = new PrintWriter("OMGIMAFILELOLZ.txt");
writer.println(answer);
writer.close();
}
}
No matter what I do, I can't pass the answer string onto the FIleWriter class. Please help!
BTW Please don't make the answer too complex. I just came from QBASIC, and i'm only 12, so keep it simple please!
In this line static answer; you have not mentioned the
data type of answer.
main is already a static block,so you can not declare static
variables inside main method
declare answer in the class level like this public static String
answer;
class level syntax
public class MainProgram {
public static String answer;//class level declaration
public static void main(String args[])
{
//some codes
}
static answer;
First of all data type is missing for that.
And you cannot declare fields in methods.
That should be
static String answer;
public static void main(String[] args) {
// answer = Input.nextLine();
Then in FileWriter class,
writer.println(MainProgram.answer);

NullPointerException when accessing a static field

As they say System is final class which have out of type PrintStream as a field member and println is method in PrintStream class.
I created a class UseNumber with static field no of type Number and just wanted to access a method of Number class but it is throwing NullPointerException
public class Number {
private int first;
private int second;
public int getFirst() {
return first;
}
public void setFirst(int first) {
this.first = first;
}
public int getSecond() {
return second;
}
public void setSecond(int second) {
this.second = second;
}
}
and for UseNumber Class
public class UseNumber {
private static Number no;
public static void main(String[] args) {
UseNumber.no.setFirst(12); //throwing nullpointer exception here
UseNumber.no.setSecond(22);
System.out.println(UseNumber.no.getFirst()+UseNumber.no.getSecond());
}
}
Re: NullPointerException
setFirst is not a static method and it requires an instance of Number. You didn't create one. You just declared a Number variable called no. Since it's initialized to null by default, you're getting a NullPointerException.
One way to fix it:
private static Number no = new Number();
The variable no being declared as static inside UseNumber simply means you will be able to access this object without an instance of UseNumber. But this static declaration won't cascade down to the methods of no. They will still require an instance, as emphasized by the error you're getting.
Re: System.out
out is a static member of System - but it's an instantiated object already.
In fact, if you view the code of System, you'll find this line:
out = com.ibm.jvm.io.ConsolePrintStream.localize(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)), true);
So when you say:
System.out
System will give you the its initialized PrintStream object called out. In essence, System.out.println is just a shortcut for this:
PrintStream p = System.out;
p.println();
A nullpointerException is thrown when you attempt to access a null object by the "." operator.
In the line you indicated the exception is thrown, the no object is null and you are trying to access its setFirst method which will of course throw a nullpointer exception.
to fix the error, initialize your no object, maybe like this :
public class UseNumber {
private static Number no;
public static void main(String[] args) {
UseNumber.no = new Number(); // Initialize here your no object
UseNumber.no.setFirst(12); //This line will no longer throw an exception.
UseNumber.no.setSecond(22);
System.out.println(UseNumber.no.getFirst()+UseNumber.no.getSecond());
}
}
Maybe you can write a interface method to get the instance of no. In the method you can check if it's null, similar to the way we do with Singleton pattern.
public class UseNumber {
private static Number no;
public static getNumberInstance() {
if(no == NULL) {
no = new Number(); //This will get executed only once, for first call.
}
return no;
}
public static void main(String[] args) {
UseNumber.getNumberInstance().setFirst(12);
UseNumber.getNumberInstance().setSecond(22);
System.out.println(UseNumber.getNumberInstance().getFirst()
+UseNumber.getNumberInstance().getSecond());
}
}

Categories

Resources