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");
}
Related
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 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.
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.
This question already has answers here:
Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args) [duplicate]
(5 answers)
Closed 8 years ago.
Error: Main method not found in class MovieDatabase, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
import java.io.FileInputStream;
import java.util.Scanner;
import java.util.Arrays;
public class MovieDatabase {
private int[] analysis;
//creating the contructor
public MovieDatabase(String file){
analysis = new int[2015];
this.load(file);
}
//uses the load(String file) method from downstairs to do all of the work
public void load(String file){
Scanner theScanner = null;
try{
//inputing the into the scanner
theScanner = new Scanner(new FileInputStream(file));
}
catch(Exception ex){
ex.printStackTrace();
}
// as long as the scanner has another line
while(theScanner.hasNextLine())
{
String Line = theScanner.nextLine();
//make an array called split and allocated different elements based on a seperation of ##
String split[] = Line.split("##");
int year = Integer.valueOf(split[1]);
analysis[year] ++;
}
}
//print out the array in the synchronous format
public void print(){
System.out.printf("%1$-30s %2$10s %3$10s %4$10s ", "Year", "Occurances", "", "");
//go through the array
for (int i =0;i < analysis.length ;i++ ) {
if(analysis[i] >0){
for (int j =i;j < analysis.length ;i++ ){
System.out.printf("%1$-30s %2$10s %3$10s %4$10s ", j, analysis[j], "", "");
}
}
}
}
}
How do I fix this error message?
Ive read other similar questions but just say to make the classes public. Mine are public.
main() method in Java is an standard method which is used by JVM to start execution of any Java program. main method is referred as entry point of Java application which is true in case of core java application
You have missed it. Add following main() method
public static void main(String[] args) {
MovieDatabase db = new MovieDatabase("file/path/goes/here");
db.print();
}
In the Java programming language, every application must contain a
main method whose signature is:
public static void main(String[] args)
As the error suggests, if its non FX project, just define something like:
public static void main(String args[]) {
...
}
Or else change you class definition so it extends Application, something like:
public class MovieDatabase extends Application
To invoke any application JVM need main() method, and which should have following access specifiers and modifiers,
public static void main(String args[])
public - It should be accessible to all
static - JVM not able to create instance of your class so method should be static
void - method not returning anything
For each java application main method is entry point, so your application should have atleast one main method to start execution of application.
It's because you have forgot to add the main method. The error clearly says:
please define the main method as: public static void main(String[]
args)
So add the main:
public static void main(String[] args) {
MovieDatabase m = new MovieDatabase("Your File Path");
m.print();
}
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);
}