In the main method, I create an object cls and call its method test. This method will call two others methods (test1 and test2). Each one has its Scanner.
public static void main(String[] args) {
Class2 cls = new Class2();
cls.test();
}
the Class2 is:
public class Class2 {
public Class2() {
}
public void test()
{
test2();
test3();
}
public void test2() {
Scanner scanner = new Scanner(System.in);
System.out.println("give a String:");
String str = scanner.next();
scanner.close();
}
public void test3()
{
Scanner sc = new Scanner(System.in);
System.out.println("give another String:");
String str = sc.next();
sc.close();
}
}
After execution, I got an exception
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at Class2.test3(Class2.java:25)
at Class2.test(Class2.java:11)
at Class1.main(Class1.java:12)
How can I handle this exception please ? by keeping in each method a different scanner !
Here Is your rectified code with appropriate comments.
Class2.java
import java.util.Scanner;
public class Class2 {
/*You dont have to create multiple scanner objects*/
Scanner scan = new Scanner(System.in);
public void test() {
/*In order to run the methods in this class itself
* you have to use static keyword or create object*/
Class2 obj = new Class2();
obj.test2();
obj.test3();
scan.close();
/* As this method is run, scan.close() should be placed when you want to close InputStream
* you will learn this in Java Streams*/
}
public void test2() {
System.out.println("give a String:");
String str = scan.nextLine();
}
public void test3() {
System.out.println("give another String:");
String str = scan.nextLine();
}
}
Main.java
public class Main {
public static void main(String[] args) {
Class2 cls = new Class2();
cls.test();
}
}
Why did the error occur?
Ans: When your code executes test2() method it closes the scanner InputStream in the ending by using scan.close(), hence when the test3() is executed it can no longer read data. The solution is that you either close scanner in the test3() method or in the test() method.
Related
What's the issue here?
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
UserInput input = new UserInput();
input.name();
}
This complains:
<identifier> expected
input.name();
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
You can't call methods outside a method. Code like this cannot float around in the class.
You need something like:
public class MyClass {
UserInput input = new UserInput();
public void foo() {
input.name();
}
}
or inside a constructor:
public class MyClass {
UserInput input = new UserInput();
public MyClass() {
input.name();
}
}
input.name() needs to be inside a function; classes contain declarations, not random code.
Try it like this instead, move your myclass items inside a main method:
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
public static void main( String args[] )
{
UserInput input = new UserInput();
input.name();
}
}
I saw this error with code that WAS in a method; However, it was in a try-with-resources block.
The following code is illegal:
try (testResource r = getTestResource();
System.out.println("Hello!");
resource2 = getResource2(r)) { ...
The print statement is what makes this illegal. The 2 lines before and after the print statement are part of the resource initialization section, so they are fine. But no other code can be inside of those parentheses. Read more about "try-with-resources" here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
What's the issue here?
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
UserInput input = new UserInput();
input.name();
}
This complains:
<identifier> expected
input.name();
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
You can't call methods outside a method. Code like this cannot float around in the class.
You need something like:
public class MyClass {
UserInput input = new UserInput();
public void foo() {
input.name();
}
}
or inside a constructor:
public class MyClass {
UserInput input = new UserInput();
public MyClass() {
input.name();
}
}
input.name() needs to be inside a function; classes contain declarations, not random code.
Try it like this instead, move your myclass items inside a main method:
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
public static void main( String args[] )
{
UserInput input = new UserInput();
input.name();
}
}
I saw this error with code that WAS in a method; However, it was in a try-with-resources block.
The following code is illegal:
try (testResource r = getTestResource();
System.out.println("Hello!");
resource2 = getResource2(r)) { ...
The print statement is what makes this illegal. The 2 lines before and after the print statement are part of the resource initialization section, so they are fine. But no other code can be inside of those parentheses. Read more about "try-with-resources" here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
I have two classes. Class A, prompts the user to input a number 9 times using Scanner(System.in). Class B implements class A.
How can I automate responses for class A when running class B. For example, when I run class B, how would I get the computer to respond the number "3" every time class A prompts me to enter a number?
public class A {
private Scanner scan;
public A() throws FileNotFoundException{
scan = new Scanner(System.in);
for(int i=1;i<=9;i++){
System.out.println("Enter #");
int num = scan.nextInt();
}
}
}
public class B{
public B(){
A runA = new A();
}
public static void main(String[] args) {
B runB = new B();
}
}
I would recommend using a function in Class A to get the inputs one by one. Then, from Class B, print the line before the method is called. As such:
public class A {
private Scanner scan;
public A() throws FileNotFoundException {
scan = new Scanner(System.in);
}
public void getInput() {
System.out.println("Enter #");
int num = scan.nextInt();
}
}
public class B {
public B() {
A runA = new A();
for(int i=1;i<=9;i++) {
System.out.println("3");
runA.getInput();
}
}
public static void main(String[] args) {
B runB = new B();
}
}
This should be what you want.
Either that or you can print the line above where it says scan.nextInt(); in your code.
i tried to declare a new scanner, it works fine but only at the main.
when i write methods (out of the main of course) it wont recognize the scanner.
import java.util.Scanner;
public class Exe1GenericSort {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
start();
int i = input.nextInt();
}//end main
here it works fine, but at the method "start" it wont let me use "input.next....
tried to write the "Scanner input = new Scanner.... above the main and still wont work...
You need to declare the Scanner as an object outside the main function and then you can use it in other functions.
import java.util.Scanner;
class ScannerTest {
private static Scanner scanner;
public static void main(String[] args){
scanner = new Scanner(System.in);
start();
}
private static void start(){
String input = scanner.nextLine();
System.out.println("Input: " + input);
}
}
NOTE: The scanner object as well as the start function need to be static in order for you to access them inside the main function.
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int x= start(input);
System.out.println("enter another number");
int i = input.nextInt();
System.out.println("a number:"+x);
System.out.println("another number"+i);
}
public static int start(Scanner scan)
{
System.out.println("Please enter a number");
int x = scan.nextInt();
return x;
}
to use Scanner in another method
accept a parameter in the method start() and then return x to test the value then print the value in the main method
solved:
import java.util.Scanner;
public class Exe1GenericSort {
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
this one works great !
thank for help ppl.
problem solved ! :)
Suppose i have a class named Invoked, to which i want to call using reflection from Invoker class. but i want to give input from array declared in Invoker class whenever it gets code for input from keyboard.
class Invoked {
public static void main(String ar[]) {
java.util.Scanner s = new java.util.Scanner();
// here i want to give input stored in array except of console from Invoker class.
System.out.println("input given from keyboard is : " + s.next());
}
}
class Invoker {
public static void main(String ar[]) {
// i want to pass array here for keyboard input values like
Class<?> cl = loader.loadClass("Invoked");
Method m = cl.getDeclaredMethod("main", new Class[] {String[].class });
m.setAccessible(true);
m.invoke(null, new Object[] {null });
}
}
java.util.Scanner() reads by default from System.in [stop: there is no default constructor in Scanner, your code won't compile]. You can set it to eg a StringInputStream right before invoking of main (System.setIn()).
class Invoked{
public static void main(String ar[])
{
java.util.Scanner s=new java.util.Scanner(System.in);
//here i want to give input stored in array except of console from Invoker class.
System.out.println("input given from keyboard is : "+s.next());
}
}
class Invoker
{
public static void main(String ar[])
{
//i want to pass array here for keyboard input values like
Class<?> cl = loader.loadClass("Invoked");
Method m=cl.getDeclaredMethod("main", new Class[] { String[].class });
m.setAccessible(true);
System.setIn(new StringBufferInputStream("a b 100"));
m.invoke(null, new Object[] { null });
}
}
Use an ArrayList to make a dynamic array based off how many lines the user inputs.
class Invoked {
public static void main(String[] args) {
java.util.Scanner s = new java.util.Scanner(System.in);
List<String> input = new ArrayList<>;
while(s.hasNext()) {
input.add(s.next());
for(String i : input)
System.out.println("input given from keyboard is : " + i);
}
}
To convert the ArrayList to an array, use
String inArray = input.toArray();
I got the exact code for my problem. Here is the code given below.
import java.io.ByteArrayInputStream;
import java.lang.reflect.Method;
class Invoked{
public static void main(String ar[])
{
java.util.Scanner s=new java.util.Scanner(System.in);
System.out.println("input given from keyboard is : "+s.next());
int i=s.nextInt()+s.nextInt();
System.out.println("input given from keyboard is : "+i);
}
}
class Invoker
{
public static void main(String ar[])throws Exception
{
Class<?> cl = Class.forName("Invoked");
Method m=cl.getDeclaredMethod("main", new Class[] { String[].class });
m.setAccessible(true);
String inputString="ashish 15 16";
System.setIn(new ByteArrayInputStream(inputString.getBytes()));
m.invoke(null, new Object[] { null });
}
}