Passing String from one class to another - java

How can I pass string variable or String object from one class to another?
I've 2 days on this problem.
One class get data from keyboard and second one should print it in console.

Take some help from the below code:-
public class ReadFrom {
private String stringToShow; // String in this class, which other class will read
public void setStringToShow(String stringToShow) {
this.stringToShow = stringToShow;
}
public String getStringToShow() {
return this.stringToShow;
}
}
class ReadIn {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // for taking Keyboard input
ReadFrom rf = new ReadFrom();
rf.setStringToShow(sc.nextLine()); // Setting in ReadFrom string
System.out.println(rf.getStringToShow()); // Reading in this class
}
}

There are two ways:
create an instance of your printer class and evoke the method on the printer object:
public class MyPrinter
{
public void printString( String string )
{
System.out.println( string );
}
}
in your main:
MyPrinter myPrinter = new MyPrinter();
myPrinter.printString( input );
or 2. you create a static method in your printer class and evoke it in your main:
public class MyPrinter
{
public static void printStringWithStaticMethod(String string)
{
System.out.println(string);
}
}
in your main:
MyPrinter.printStringWithStaticMethod( input );

Write a method inside your second class with System.out.println(parameter);
Make the method static and then invoke this in first method like
ClassName.methodName(parameter)

Inside class that accepts Scanner input
variableName ClassName = new Classname();
variablename.methodToPrintString(string);
A textbook can always help in this situation.

Related

Cannot resolve symbol 'execute' when executing AsyncTask [duplicate]

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

How can i access an object from another method in java?

I have the object numberlist that i created in create() method and i want to access it so i can use it in the question() method.
Is there another way to do this that I probably missed? Am I messing something up? If not, how should I do this to get the same functionality as below?
private static void create() {
Scanner input = new Scanner(System.in);
int length,offset;
System.out.print("Input the size of the numbers : ");
length = input.nextInt();
System.out.print("Input the Offset : ");
offset = input.nextInt();
NumberList numberlist= new NumberList(length, offset);
}
private static void question(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a command or type ?: ");
String c = input.nextLine();
if (c.equals("a")){
create();
}else if(c.equals("b")){
numberlist.flip(); \\ error
}else if(c.equals("c")){
numberlist.shuffle(); \\ error
}else if(c.equals("d")){
numberlist.printInfo(); \\ error
}
}
While interesting, both of the answers listed ignored that fact that the questioner is using static methods. Thus, any class or member variable will not be accessible to the method unless they are also declared static, or referenced statically.
This example:
public class MyClass {
public static String xThing;
private static void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
private static void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
makeThing();
makeOtherThing();
}
}
Will work, however, it would be better if it was more like this...
public class MyClass {
private String xThing;
public void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
public void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
MyClass myObject = new MyClass();
myObject.makeThing();
myObject.makeOtherThing();
}
}
You would have to make it a class variable. Instead of defining and initializing it in the create() function, define it in the class and initialize it in the create() function.
public class SomeClass {
NumberList numberlist; // Definition
....
Then in your create() function just say:
numberlist= new NumberList(length, offset); // Initialization
Declare numberList outside your methods like this:
NumberList numberList;
Then inside create() use this to initialise it:
numberList = new NumberList(length, offset);
This means you can access it from any methods in this class.

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

Java: Identifier expected

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

how do I pass a variable from a class that uses Scanner to the main class?

how do I get the read txt file into the main class?
//main class
public class mainClass {
public static void main(String[]args) {
load method = new load("Monster");
}
}
//scanner class
public class load {
public static void loader(String... aArgs) throws FileNotFoundException {
load parser = new load("resources/monsters/human/humanSerf.txt");
parser.processLineByLine();
log("Done.");
}
public load(String aFileName){
fFile = new File(aFileName);
}
public final void processLineByLine() throws FileNotFoundException {
//Note that FileReader is used, not File, since File is not Closeable
Scanner scanner = new Scanner(new FileReader(fFile));
try {
//first use a Scanner to get each line
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
}
}
finally {
scanner.close();
}
}
public void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("=");
if ( scanner.hasNext() ){
String name = scanner.next();
String value = scanner.next();
log("Stat is : " + quote(name.trim()) + ", and the value is : " + quote(value.trim()) );
}
else {
log("Empty or invalid line. Unable to process.");
}
}
public final File fFile;
public static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
public String quote(String aText){
String QUOTE = "'";
return QUOTE + aText + QUOTE;
}
}
Which method do I call from the main class and what variables do I return from that method if I want the text from the file. If anyone has a website that can help me learn scanner(got this source code of the internet and only sort of understand it from JavaPractises and the sun tutorials) that would be great. thanks
First, you probably want to follow standard Java naming conventions - use public class MainClass instead of mainClass.
Second, for your methods, the public has a specific purpose. See here and here. You generally want to label methods as public only as necessary (in jargon, this is known as encapsulation).
For your question - in the Load class, you can append all the text from the file to a String, and add a public getter method in Load which will return that when called.
Add this at the start of Load:
public class Load {
private String fileText;
// ... rest of class
And add this getter method to the Load class. Yes, you could simply mark fileText as public, but that defeats the purpose of Object-Oriented Programming.
public getFileText(String aFileName){
return fileText;
}
Finally, use this new method for log. Note that there is no need to use Object.
private static void log(String line) {
System.out.println(line);
fileText += aObject;
}
You can now get the read file into the main class by calling method.getFileText()
Code was TL;DR
If you want to get all of the data from the load class's .txt file, then you need to write a method in load to get the lines. Something like this would work:
public String[] getFileAsArray() {
ArrayList<String> lines = new ArrayList<String>();
Scanner in = new Scanner(fFile);
while(in.hasNextLine())
lines.add(in.nextLine();
String[] retArr = new String[lines.size()];
return lines.toArray(retArr);
}

Categories