Scanner Object Error - java

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

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

Using a instance of a method

I was wondering if someone could help explain how to call a instance of a class.
For example originally I had a file called "Driver"
Then it has a main method that has all the instances needed for a file to run.
Then in that main file it access another file called with a "Games".
So when I run the program "Driver" which has the following code:
import java.util.*;
public class Driver
{
public static void main (String[] args)
{
GameRunner roul = new GameRunner ();
}
}
Then to call an instance of that other file I have something like. Also to make the code work I should have the main method like:
import java.util.*;
public class Driver
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int number = 3;
int userChoice = 0;
GameRunner roul = new GameRunner ();
}
}
Then my other file has something like:
import java.util.*;
class GameRunner
{
public static void roul(Scanner in, int number, int userChoice)
{
Guessing this is still wrong because the driver class should only have :
GameRunner roul = new GameRunner ();
I know it's kinda hard to explain what I'm asking. I hope someone understands.
Thanks.
I strongly recommend reading this (official) tutorial from the people who made Java: https://docs.oracle.com/javase/tutorial/java/concepts/index.html
(No, seriously. Read that tutorial. I linked to the section specifically on object-oriented programming, which explains what you are asking about. It's very useful).
Now to answer your question more directly.
Your roul method is a "class method" (rather than an "instance method") because it has the keyword static in front of its definition. This means that you invoke it using the name of the class, rather than by using a specific object (instance) that you created.
So in order to call the roul method of GameRunner, do the following in your main:
GameRunner.roul(in, number, userChoice);
It is not necessary to instantiate GameRunner unless it has a non-static method that you need to invoke. So unless that's the case, don't do the following:
GameRunner roul = new GameRunner ();
Finally, note that the names of your arguments do not have to be the same as the names of your parameters, as long as their types are the same. The "parameters" are the variables you used when you defined the method. The "arguments" the actual variables you pass to the method.
For example, a method definition has parameters:
public static void myMethod(int parameter1, int parameter2) {
/* do stuff */
}
Whereas a method invocation has arguments that can have a different name:
MyClass.myMethod(number1, number2);
public class Driver {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int number = 3;
int userChoice = 0;
GameRunner runner = new GameRunner ();
// The following line will invoke the target method of your game runner instance.
runner.roul(in, number, userChoice);
}
}
Declare the class and method static then call like this:
GameRunner.roul(); // pass in arguments if needed
public static void run() is the entry point into your application you don't need another one. it looks like you need to brush up on Object Oriented basics.
if you're trying to make a game perhaps you could start with a tutorial? i would suggest using a game library like Lightweight Java Game Library. go ahead and google for some tutorials.

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.

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

Categories

Resources