Java - How do I call a class's method with a string? - java

I'm trying to use my input from the console to pick which class's main method I want to run.
package run;
import java.lang.reflect.Method;
import java.util.Scanner;
import testing.*;
public class run {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException{
Scanner input = new Scanner(System.in);
String name = "testing."+input.nextLine();
Class Program = Class.forName(name);
//Try 1
Program obj = new Program();
//Got error "Program cannot be resolved to a type" on program and program
//Try 2
Program.main();
//Got error "The method main() is undefined for the type Class" on main
//Try 3
Class.forName(name).main();
//Got error "The method main() is undefined for the type Class<capture#2-of ?>" on main
}
}

Class program = Class.forName(name);
program.getDeclaredMethod("main", String[].class).invoke(null, new Object[]{args});
provide your main method is public static void main(String[] args)

This problem can be solved easily using Reflection. Check out the code below:
package run;
import java.lang.reflect.Method;
import java.util.Scanner;
import testing.*;
public class run {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, NegativeArraySizeException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Scanner input = new Scanner(System.in);
String name = "testing."+input.nextLine();
Class program = Class.forName(name);
program.getMethod("main", String[].class).invoke(null, Array.newInstance(String.class, 0));
}
}

Related

Getting and error when using Scanner in Java

I am trying to pull an input from the user for this program to start on some more complicated stuff. However no matter what I try I get this error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Main.main(Main.java:8)
I am running this code here:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner test = new Scanner(System.in);
String x = test.nextLine();
System.out.println(x);
}
}
Any help is greatly appreciated!
You have to check before if nextLine() exists. Try this:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner test = new Scanner(System.in);
while (test.hasNextLine()) {
string = test.nextLine();
System.out.println(string);
}
}
}

java.lang.ClassNotFoundException, PATH is corrent

I'm trying to create a simple program, but of course JAVA thinks otherwise: it's not that simple.
I need to dynamically instantiate a class, meaning that the user gives a class name from keyboard, and then an object of the class type with that name is created.
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.*;
public class NimMain {
public static void main(String[] args) throws IOException {
BufferedReader Olvaso = new BufferedReader(new InputStreamReader(System.in));
String be = Olvaso.readLine();
String[] kapcsolo = be.split(" ");
switch (kapcsolo[0]) {
case "uj": uj(kapcsolo);
case "lep":
case "listaz":
case "ment":
case "tolt":
}}
public static void uj(String[] s) {
try {
int b = 2;
String nev = s[1];
Class NimJatek = Class.forName(nev);
Constructor con = NimJatek.getConstructor(String[].class, int.class);
Object xyz = con.newInstance(s,b);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The class which fails to instantiate is NimJatek, which is in the same directory, in the same (unnamed) package.
When I try to run this program, it gives the java.lang.ClassNotFoundException error.
I think you baffle yourself by your not very clear constructs. At the end you use the second value of your input string to be loaded as class. If you provide the correct string there it will be laoded correctly. The input string:
"uj NimJatek"
will lead to a correctly found class NimJatek - provided NimJatek is in your root package AND this root package is on your classpath.

error: cannot find symbol: class FileNotFoundException

I'm receiving the following error:
printfile.java:6: error: cannot find symbol
throws FileNotFoundException {
^
symbol: class FileNotFoundException
location: class printfile
for the following code:
import java.io.File;
import java.util.Scanner;
public class printfile {
public static void main(String[]args)
throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println (" What file are you looking for? ");
String searchedfile = keyboard.next();
File file = new File(searchedfile);
if (file.exists()) {
System.out.println(" Okay, the file exists... ");
System.out.print(" Do you want to print the contents of " + file + "?");
String response = keyboard.next();
if (response.startsWith("y")) {
Scanner filescan = new Scanner(file);
while (filescan.hasNext()) {
System.out.print(filescan.next());
}
}
else {
System.out.print(" Okay, Have a good day.");
}
}
}
}
How can this error be resolved?
To use a class that is not in the "scope" of your program, (i.e. FileNotFoundException), you have to:
Call it's fully qualified name:
// Note you have to do it for every reference.
public void methodA throws java.io.FileNotFoundException{...}
public void methodB throws java.io.FileNotFoundException{...}
OR
Import the class from it's package:
// After import you no longer have to fully qualify.
import java.io.FileNotFoundException;
...
public void methodA throws FileNotFoundException{...}
public void methodB throws FileNotFoundException{...}
Suggest also taking a look in this question, explains pretty much everything you might want to know about Java's acess control modifiers.

In Java I need to run a local method (code below)

Hey I have been trying to get the main to run the methods but I don't remember how to do it.
It is a simple program so far because I just started on it 15 minutes ago.
`
import java.awt.Robot;
import javax.swing.JFrame;
import java.lang.*;
import java.io.*;
public class sweetRevenge {
public static void main(String[] args) {
//call local static classes browserjacker and wallpaperjacker
start(browserJacker(1));
}
public static void browserJacker(int i)throws IOException{
try
{
//include bad things along with self made video of hacking linked to youtube
Process p=Runtime.getRuntime().exec("cmd /c start http://www.google.com");
}
catch(IOException e1) {System.out.println(e1);}
}
public static void wallpaperJacker (String args []) throws IOException {
Process p=Runtime.getRuntime().exec("cmd /c start");
}}
`
since your method is throwing an exception so the place where you will call it MUST have an exception handling mechanism, and your code needs to be modified.
import java.awt.Robot;
import javax.swing.JFrame;
import java.lang.*;
import java.io.*;
public class sweetRevenge {
public static void main(String[] args) {
//call local static classes browserjacker and wallpaperjacker
try{
browserJacker(); // will start method browserJacker
// since the method is static so it can be easily accessed from static method
}catch{IOException ex}{
}
}
public static void browserJacker()throws IOException{
//include bad things along with self made video of hacking linked to youtube
Process p=Runtime.getRuntime().exec("cmd /c start http://www.google.com");
}
public static void wallpaperJacker () throws IOException {
Process p=Runtime.getRuntime().exec("cmd /c start");
}
}

FIleNotFoundException - illegal start of expression - NetBeans

I get the following error message 'llegal start of expression' at line
throws FileNotFoundException
I have done some research but wasn't able to fix it. Can you help? Many thanks, zan
import java.io.FileNotFoundException;
import java.io.File;
import java.util.Scanner;
import static java.lang.System.out;
public class training{
public static void main(String[]args){
throws FileNotFoundException{
Scanner diskScanner = new Scanner(new File("occupancy"));
out.println("Room\tGuests");
for(int roomNum = 0; roomNum < 10; roomNum ++){
out.print(roomNum);
out.print("\t");
out.println(diskScanner.nextInt());
}
}
}
}
You shouldn't have a curly brace before the throws keyword :
public static void main(String[]args) throws FileNotFoundException {
^-- no curly brace
Note that a class should always start with an uppercase letter.
Improper use of throws.
public static void main(String[]args) throws FileNotFoundException
{
..
}
It is better to use try..catch
public static void main(String[]args)
{
try
{
..
}catch(FileNotFoundException ex)
{
//
}
}
Your syntax is wrong. Check your source and/or the language specification.

Categories

Resources