How do I use a scanner across multiple classes? - java

How can I use my Scanner user_input across multiple classes? I have read a few articles, but apparently I am missing something. I even tried following a few other stackoverflow questions, and the result is below:
import java.util.Scanner;
public class HelloWorld{
public static final Scanner user_input = new Scanner(System.in);
public static void main(String []args){
String test1 = user_input.next();
System.out.println("Test 1: " + test1);
}
}
class TestClass{
public static void test_method(){
String test2 = HelloWord.user_input.next();
System.out.println("Test 2: " + test2);
}
}
If someone could help me, I would truly appreciate it.
P.S. I am new to Java, have background in Python.

From #ferdz comment, something like this would be better:
import java.util.Scanner;
public class HelloWorld {
public static final Scanner user_input = new Scanner(System.in);
public static void main(String[] args) {
String test1 = user_input.next();
System.out.println("Test 1: " + test1);
// These two lines actually instantiate the TestClass below,
// we pass in the Scanner as a parameter (user_input), and
// then it gets used in the test_method internally.
TestClass testClass = new TestClass(user_input);
testClass.test_method();
}
private static class TestClass {
public void test_method(Scanner scanner) {
String test2 = scanner.next();
System.out.println("Test 2: " + test2);
}
}
}

Your only problem is you have missed spelt the word world in your second class.
So change:
String test2 = HelloWord.user_input.next();
to:
String test2 = HelloWorld.user_input.next();
and it should work

Related

Is there a way for me to assign variable numA inside a method defined by scanner class and use it in different methods?

import java.util.Scanner;
public class A {
static void aValue1(){
Scanner scan = new Scanner(System.in);
System.out.print("Enter value of a: ");
double numA = scan.nextDouble();
static void aValue2(){
System.out.println(numA);}
public static void main(String[] args) {
aValue1();
aValue2();
}
}
I understand that numA is a local variable and can not be used again in a different method, but is there any way I declare numA as static outside of the method and still be able to get the user input for it?
I want the user to type what numA is and I want to use it in every method.
Yes you can, you could have numA as a static field
import java.util.Scanner;
public class A {
static double numA;
static void aValue1(){
Scanner scan = new Scanner(System.in);
System.out.print("Enter value of a: ");
numA = scan.nextDouble();
static void aValue2(){
System.out.println(numA);}
public static void main(String[] args) {
aValue1();
aValue2();
}
}

Program won't run scanner cannot be resolved

This is the code I have so far and this is only one file of multiple ones that all belong to the same program.
As soon as I want to compile and check my errors eclipse tells me that it cannot resolve the scanner and I have no idea how to fix this problem nor what it exactly means.
import java.util.Scanner;
public class PieShop {
static FoodItem foodItem = new FoodItem();
public static void main(String[] args) {
Scanner_in.consoleLine("Enter Food item File name:");
foodItem.foodItemFile=new File(Scanner_in.getConsole());
foodItem.addFoodItem();
foodItem.displayAll();
foodItem.choices();
}
}
Below code should work fine provided that you pass right value to scanner source
import java.util.Scanner;
public class PieShop {
static FoodItem foodItem = new FoodItem();
public static void main(String[] args) {
Scanner Scanner_in = new Scanner(source);
Scanner_in.consoleLine("Enter Food item File name:");
foodItem.foodItemFile=new File(Scanner_in.getConsole());
foodItem.addFoodItem();
foodItem.displayAll();
foodItem.choices();
}
}
This would be the correct way if you wan to read the input from the console:
import java.util.Scanner;
public class PieShop {
private static FoodItem foodItem = new FoodItem();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Initialize scanner
System.out.println("Enter Food item File name:"); // Print yourtext
foodItem.foodItemFile = new File(scanner.nextLine()); // Read from scanner
foodItem.addFoodItem();
foodItem.displayAll();
foodItem.choices();
}
}

Java Supplier/Consumer/Runnable? How to invoke method when it is supplied as a a string argument

I need a help. User supplying method with its arguments as a string. My code need to run this method.
How we can we achieve this using Supplier/Consumer/Runnable. This can be done using reflection but I want to avoid it.
import java.util.Scanner;
public class InvokeStringArgument{
public static Supplier<String> invokeMe(String returnStr){
return new Supplier<String>(){
public String get(){
System.out.println("Success");
return returnStr;
}
};
}
public static void main(String[] args){
//invokeMe("MyValue").get();
System.out.println("Please enter method to invoke:");
Scanner sc = new Scanner(System.in);
String methodName = sc.next();
//Need a code which will run the method when passed as a string
//For example user input it as invokeMe("MyValue")
}
}
Ok, got some time today to look into these pending things. Achieved solution which at this time confirms to my requirement. Used BeanShell and reflection to get this done as below
package beanshell;
import java.util.Scanner;
import java.util.function.Supplier;
import bsh.EvalError;
import bsh.Interpreter;
public class InvokeStringArgument{
public static Supplier<String> invokeMe(String returnStr){
return new Supplier<String>(){
public String get(){
System.out.println("Success: Received string '"+returnStr+"'");
return returnStr;
}
};
}
public static void main(String[] args) throws EvalError {
//invokeMe("MyValue").get();
System.out.println("Please enter string to evaluate:");
Scanner sc = new Scanner(System.in);
String userInput = sc.next();
Interpreter i = new Interpreter();
Object evalSource = i.eval("public class EvalUserInput extends beanshell.InvokeStringArgument{"
+ "public void evaluserInput(){"
+ userInput+""
+ "}"
+ "}");
try{
Class<?> noparams[] = {};
Class<?> cls = (Class) evalSource;
Object obj = cls.newInstance();
cls.getDeclaredMethod("evaluserInput", noparams).invoke(obj, null);
} catch(Exception e){
}
}
}
From the console:
Please enter string to evaluate:
invokeMe("MyValue").get();
Success: Received string 'MyValue'

Scanner input string appearing as null java

My code is here:
package test1;
import java.util.*;
public class Test1 {
public static String input;
public Test1(){
Scanner answer = new Scanner(System.in);
String test = answer.next();
}
public static void initializeConstructor(){
Test1 input = new Test1();
}
public static void begin () {
System.out.println("type:");
initializeConstructor();
System.out.println(input);
}
public static void main(String[] args) {
begin();
}
}
I am really new to learning java, my idea is that I can call the constructor to to start the scanner and it will spit back at me what I just typed. I am doing this so I can understand more about constructors in java. However when I run the following program, it just gives me "null". Like I said, i am preety new, so it may be a dumb question but any response would be very appreciated. Thank you in advance.
Because input is null (never assigned), change
String test = answer.next();
to
input = answer.next();
and your code will work. But input is static (it shouldn't be in real code, not if you're setting it in a constructor).

How to call a method with parameter from a diffrent class

Possible noob question but I cant get my method with parameters in one class to call in the other ?
FirstClass
public class Firstclass {
public static void main(String[] args) {
Test1 test = new Test1();
test.Passingvalue();
test.myMethod();
}
}
SecondClass
import java.util.Scanner;
public class Test1 {
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
String txtFile = Scan.next();
}
public void myMethod(String txtFile){
System.out.print("Scan this file" + txtFile);
}
}
You can provide the parameters as a comma separated list in the brackets after the method's name:
public static void main(String[] args) {
Test1 test = new Test1();
test.myMethod("my_file.txt");
}
Don't forget to add a parameter like this :
test.myMethod("txtFile");
declare your string txtfile as a public static variable outside the two methods (at the beginning of class test1) .
public class Firstclass {
public static void main(String[] args) {
Test1 test = new Test1();
test.Passingvalue();
test.myMethod();
}
}
import java.util.Scanner;
public class Test1 {
String txtFile;
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
txtFile = Scan.next();
}
public void myMethod(){
System.out.print("Scan this file" + txtFile);
}
}
I think you have a misconception here:
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
String txtFile = Scan.next(); //method scope only
}
Here the local variable txtFile only exists until the method Passingvalue (check naming conventions btw) is finished, i.e. it has method scope. Thus when calling myMethod(String txtFile) the parameter has the same name but is a different reference in a different scope.
So you'd either have to pass the file name to your method as the others already suggested or change the scope of txtFile, e.g. make it an instance variable:
public class Test1 {
private String txtFile; //the scope of this variable is the instance, i.e. it exists as long as the instance of Test1 exists.
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
txtFile = Scan.next();
}
public void myMethod(){
System.out.print("Scan this file" + txtFile);
}
}
Please note that this is just meant to illustrate the immediate problem. There are other issues, e.g. with the general design, which are not addressed. The purpose of your code seems to be learning anyways, so design is not that big an issue for now.
Just as a hint: I'd probably pass the name from outside the method or pass/read it in a constructor.
when you are calling a parameterize method you should have to pass a parameter to calling method other wise jvm will not understand to whom method you are calling becuase on the basis of parameters we can over load the methods .
so the final answer of your question is
public static void main(String[] args) {
Test1 test = new Test1();
test.myMethod("place your file name here");
}

Categories