Java 1.6: Public variable won't work - java

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

Related

How to correctly write the extends functionality instead of import statement? [duplicate]

This question already has answers here:
What's the difference between importing and extending a class?
(10 answers)
Closed 3 years ago.
Instead of import statement , I am using extends attribute for java.util.Scanner class.I am getting error with below code snippet.How to correct it?
class test extends java.util.Scanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value from keyboard:");
int ans = sc.nextInt();
System.out.println("The value entered through keyboard ::"+ans);
}
}
Short answer: you can't because java.util.Scanner is final and you cannot extend it.
But, you can using encapsulation as follow, in same package create a new class MyScanner:
import java.io.InputStream;
import java.util.Scanner;
public class MyScanner implements Iterator<String>, Closeable {
private Scanner scanner;
public MyScanner(InputStream in) {
this.scanner = new Scanner(in);
}
//Override classes you need
}
and use it in your class:
import java.io.InputStream;
import java.util.Scanner;
public class MyScanner {
private Scanner scanner;
public MyScanner(InputStream in) {
this.scanner = new Scanner(in);
}
public int nextInt() {
return scanner.nextInt();
}
}
Be aware that solution here is to declare two classes in same package
You can't extend the Scanner class since it's final.
Even if it was possible, extending Scanner doesn't allow you to eliminate the import statement when you refer to the Scanner class without the package name.
It makes no sense to extend Scanner for the given code. If you want to avoid the import statement, use the full class name:
class test
{
public static void main(String[] args)
{
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.println("Enter the value from keyboard:");
int ans = sc.nextInt();
System.out.println("The value entered through keyboard ::"+ans);
}
}
Scanner is a final class and can therefore not be extended.
If you want to use the scanner without importing it explicitely, you could try the following:
class Test
{
public static void main(String[] args)
{
java.util.Scanner sc = new java.util.Scanner(System.in); // Specify full class path over here
System.out.println("Enter the value from keyboard:");
int ans = sc.nextInt();
System.out.println("The value entered through keyboard ::"+ans);
}
}
Keep in mind the naming conventions: a class name should start with an uppercase letter.

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

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

class constants and file imports for 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.

Is this program recursive? If not, how do I make it recursive?

For my programming class, I was told to make a program that uses recursion. I was confused and went to see my friend who was already in the class and he showed me this program. I thought recursion had to use things like r1(x-1), etc. Is it actually recursive? If it's not, how do you make it recursive?
import java.util.*;
import java.io.*;
class ReverseFile
{
private static Scanner infile;
public static void main(String[] args) throws IOException
{
infile= new Scanner(new File("hw_1.txt"));
r1();
}
public static void r1()
{
String s;
if (infile.hasNextLine())
{
s = infile.nextLine();
r1();
System.out.println(s);
}
}
}
It is recursive as r1 calls itself. The fact that no arguments are passed to r1 doesn't matter.

Categories

Resources