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
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
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.
I want to create a program that can do all the stuff from another code, depending on user input. Something like this:
import java.util.Scanner;
public class Main_Programm1 {
public static void main(String args[]) {
String something = "something";
String something2 = "something2";
Scanner userInput = new Scanner(System.in);
String action = userInput.next();
if (action.equals(something)) {
//here i want to execute all the code from class Main_Programm2
} else if (action.equals(something2)) {
//here i want to execute all the code from class Main_Programm3 and so on
}
}
}
How do i do it?
Actually, you've got it all done, only creates the Objects that you need ;-)
import java.util.Scanner;
// imports classes;
public class Main_Programm1
{
public static void main(String args[])
{
String something = "something";
String something2 = "something2";
Main_Programm main_prog;
Main_Programm2 main_prog2;
Scanner userInput = new Scanner(System.in);
String action = userInput.next();
if (action.equals(something))
{
main_prog = new Main_Programm();
//.....
}
else if (action.equals(something2))
{
main_prog2 = new Main_Programm2();
//.....
}
}
}
I have a text file which contains the list of all public method names. I require a Java program which reads each method name from the text file and create a method(template) for each public method name.
Say,
My text file contains, 3 methods
public static void A()
public static void B()
public static void C()
I need a output like this.
public class class_name
{
public void A_test()
{
System.out.println("Method A");
}
public void B_test()
{
System.out.println("Method B");
}
public void C_test()
{
System.out.println("Method C");
}
}
Kindly give your suggestions.
Following your example above the code below will generate a similar output. Note there is no package. NOTE As your example the generator strips static
public class ClassBuilder
{
public static String buildClass(String className,ArrayList<String> methods)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(String.format("public class %s \n{", className)).append("\n");
for (String method: methods)
{
stringBuilder.append(String.format(" %s \n {", method.trim().replace("static ","").replace("()","_test()"))).append("\n }\n\n");
}
stringBuilder.append("}");
return stringBuilder.toString();
}
public static void main(String[] args)
{
Scanner scanner = null;
try
{
scanner = new Scanner(new File("d:\\testFile.txt"));
ArrayList<String> methods = new ArrayList<String>();
while (scanner.hasNext())
{
methods.add(scanner.nextLine());
}
scanner.close();
String javaClass = buildClass("className", methods);
System.out.println(javaClass);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
output
public class className
{
public void A_test()
{
}
public void B_test()
{
}
public void C_test()
{
}
}
Hi and hope someone can help. I'm doing a short Java course and need to set up 3 classes that basically communicate between each other but I'm failing.
You'll spot from the code below that I'm trying to split the tasks of reading user's input and doing whatever maths is required into different classes but something's wrong
Any ideas? Thanks for your interest.
Here's the simple Main class:-
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.start();
}
}
The Calculator class (or part of it):-
public class Calculator {
private Reader reader;
public void Calculator(Reader reader) {
this.reader = reader;
System.out.println("Calculator set up.");
}
public void start() {
while (true) {
System.out.print("command: ");
String command = reader.readString(); // It fails here:
if (command.equals("end")) {
break;
}
if (command.equals("sum")) {
sum();
} else if (command.equals("difference")) {
difference();
} else if (command.equals("product")) {
product();
}
}
And finally the Reader class:-
public class Reader {
private Scanner input;
public void Reader(Scanner input) {
this.input = input;
System.out.println("Reader set up.");
}
public String readString() {
return input.nextLine();
}
public int readInteger() {
return Integer.parseInt(input.nextLine());
}
}
You have an issue with all the constructors you are using. Constructors are special methods with no return type, so in your case, public void Calculator(Reader reader) needs to be public Calculator(Reader reader) (remove void). The same applies to the other constructors.
Once you do that, you would need to make amendments on how you are instantiating your Calculator class:
Calculator calculator = new Calculator();
Should become:
Calculator calculator = new Calculator(new Reader(new Scanner(System.in)));
provide constructor not mothod.
Calculator(Reader reader) {
this.reader = reader;
System.out.println("Calculator set up.");
}
after that you can change your main method with #subhrajyoti suggested.
apart from above suggestion ,
1> your constructors (Reader and Calculator) is returning void. But constructor cannot return any value. So, remove void keyword.
you have to import Scanner class (i.e. java.util.scanner).