Here is a small sample:
public class LocalClassSample {
public static void main(String[] args) {
class Utils {
public void printHello(String name) {
System.out.println("Hello " + name);
}
public String outHello(String name) {
return "hello " + name;
}
}
Utils util = new Utils();
util.printHello("World");
}
}
I put a break point at the last line. I am able to view util in the Variables window...
I try to view the same variable in the expressions window...it is unable to evaluate:
Update:
Even tried inspecting the variable in the Display View...it does not evaluate:
Expression eval a java expression like 'util.printHello("World")'
and return the result ("Hello World"). 'util' is not an 'expression' but just a variable name, if you want to inspect it, use the Variables view or the Inspect command.
Related
I am learning Java and currently attempting to combine if statements and multiple class files.
It is a simple I/O program with a twist, if userName = JDoe I want the program to say something other than the standard saying.
From main.java:
import java.util.Scanner;
import java.lang.String;
class main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
UInput uInput = new UInput();
System.out.println("What is your name: ");
uInput.setName(input.nextLine());
uInput.saying();
}
}
class ifMain {
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
From UInput.java:
public class UInput {
private String userName;
public void setName(String name){
userName = name;
}
public String getName(){
return userName;
}
public void saying(){
System.out.printf("Hello %s", getName());
}
}
However, in class ifMain{}, IntelliJ is saying "Variable userName never used", what am I missing?
See comments:
class ifMain {
public static void main(String[] args){
String userName = "JDoe"; // <=== Declared here
if (test.matches("JDoe")) { // <=== Not used here
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
The local variable userName is never used in the main method of the ifMain class.
You probably meant:
if (test.matches(userName)) {
Side note: The overwhelming convention in Java is that class names start with an uppercase character. So IfMain, not ifMain.
Your program wouldn't even compile in first place. I believe that you are new to Java. But still, look at this code.
class ifMain {//Please change the class name to CamelCase convention
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {// Compile error. Variable test is not declared.
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
Are you trying in a notepad and executing it? You can try using eclipse/NetBeans/IntelliJ IDEs in that case to help you better.
i'm totally new to java. i 'm try to create my first program & i get this error.
E:\java>javac Robot.java
Robot.java:16: error: illegal start of expression
public String CreateNew (); {
^
Robot.java:16: error: ';' expected
public String CreateNew (); {
^
2 errors
below is my program.
public class Robot {
public static void main(String args[]){
String model;
/*int year;*/
String status;
public String CreateNew () {
Robot optimus;
optimus = new Robot();
optimus.model="Autobot";
/*optimus.year="2008";*/
optimus.status="active";
return (optimus.model);
}
}
}
You're trying to define a method (CreateNew) within a method (main), which you cannot do in Java. Move it out of the main; and as model and status appear to be instance variables (not method variables), move them as well:
public class Robot {
// Member variables
String model;
/*int year;*/
String status;
// main method
public static void main(String args[]){
// Presumably more stuff here
}
// Further method
public String CreateNew () {
Robot optimus;
optimus = new Robot();
optimus.model="Autobot";
/*optimus.year="2008";*/
optimus.status="active";
return (optimus.model);
}
}
Based on its content, you may want CreateNew to be static (so it can be called via Robot.CreateNew rather than via a Robot instance). Like this:
public class Robot {
// Member variables
String model;
/*int year;*/
String status;
// main method
public static void main(String args[]){
// Presumably more stuff here
}
// Further method
public static String CreateNew () {
// ^----------------------------- here's the change
Robot optimus;
optimus = new Robot();
optimus.model="Autobot";
/*optimus.year="2008";*/
optimus.status="active";
return (optimus.model);
}
}
Used as
String theModel = Robot.CreateNew();
...although it's unclear to me why you want to create a Robot instance and then throw it away and just return the model instance member's value.
Somewhat off-topic, but the overwhelming convention in Java is that method names (static or instance) start with a lower-case letter, e.g. createNew rather than CreateNew.
You didn't close your main method before you create the CreateNew() one. In fact I don't think you meant to have a main method in your Robot class, you should have only one main method for your whole program. And your CreateNew should be a constructor:
public class Robot {
String model;
/*int year;*/
String status;
public Robot () {
this.model="Autobot";
this.status="active";
}
}
}
and then in another class that contains your main method (or it could be in the same class too):
public class OtherClass {
public static void main(String[] args) {
Robot optimus = new Robot(); // here you create an instance of your robot.
}
}
then you can have a second constructor that takes in parameter the model and status like that:
public Robot (String m, Status s) {
this.model=m;
this.status=s;
}
and finally in your main:
Robot prime = new Robot("aName", "aStatus");
Not sure if the title makes sense, but I am trying to return a Success message from a class that receives a linkedhashmap, however eclipse is giving me error when I try to compile the files, offering
Remove arguments to match 'logFile()'
Create constructor 'logFile(Map<String, String>)'
How do set it up to send a Map and revieve a String?
thx
Art
Code corrected as per #Jeff Storey below with error suppression for eclipse
calling class
eventLog.put(stringA,stringB);
logFile logStuff = new logFile();
successRtn = logFile.Process(eventLog);
// Do Stuff with SuccessRtn
logFile class
public class logFile {
static String Success = "Fail";
public static String Process(Map<String, String> eventlog){
// Do Stuff
Success = "Yeh!"
return Success;
}
public static void main(String[] args){
#SuppressWarnings("static-access")
String result = new logFile().Procces(eventLog);
System.out.println("result = " + result);
}
The main method is a special method whose signature must public static void main(String[] args) when being used as an entry point to your application. Create a second method that does the actual work, like this:
public class LogFile {
public String process(Map<String,String> eventLog) {
// do stuff
return success;
}
public void main(String[] args) {
// eventLog will probably be read from a filepath passed into the args
String result = new LogFile().process(eventLog);
System.out.println("result = " + result);
}
}
Note that a lot of your naming conventions are also non standard. Classes should begin with a capital letter and variables should begin with a lower case.
I am a beginner programmer and this is my first question on this forum.
I am writing a simple text adventure game using BlueJ as a compiler, and I am on a Mac. The problem I ran into is that I would like to make my code more self automated, but I cannot call a class with a string. The reason I want call the class and not have it all in an if function is so that I may incorporate more methods.
Here is how it will run currently:
public class textadventure {
public method(String room){
if(room==street){street.enterRoom();}
}
}
public class street{
public enterRoom(){
//do stuff and call other methods
}
}
The if statement tests for every class/room I create. What I would like the code to do is automatically make the string room into a class name that can be called. So it may act like so:
Public method(string room){
Class Room = room;
Room.enterRoom();
}
I have already looked into using Class.forName, but all the examples were too general for me to understand how to use the function. Any help would be greatly appreciated, and if there is any other necessary information (such as more example code) I am happy to provide it.
-Sebastien
Here is the full code:
import java.awt.*;
import javax.swing.*;
public class Player extends JApplet{
public String textOnScreen;
public void start(){
room("street1");
}
public void room(String room){
if(room=="street1"){
textOnScreen=street1.enterRoom();
repaint();
}
if(room=="street2"){
textOnScreen=street2.enterRoom();
repaint();
}
}
public void paint(Graphics g){
g.drawString(textOnScreen,5,15);
}
}
public abstract class street1
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on a street running from North to South.";
return textToScreen;
}
}
public abstract class street2
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on another street.";
return textToScreen;
}
}
Seeing as you are rather new to programming, I would recommend starting with some programs that are simpler than a full-fledged adventure game. You still haven't fully grasped some of the fundamentals of the Java syntax. Take, for example, the HelloWorld program:
public class HelloWorld {
public static void main(String[] args) {
String output = "Hello World!"
System.out.println(output);
}
}
Notice that public is lowercased. Public with a capital P is not the same as public.
Also notice that the String class has a capital S.* Again, capitalization matters, so string is not the same as String.
In addition, note that I didn't have to use String string = new String("string"). You can use String string = "string". This syntax runs faster and is easier to read.
When testing for string equality, you need to use String.equals instead of ==. This is because a == b checks for object equality (i.e. a and b occupy the same spot in memory) and stringOne.equals(stringTwo) checks to see if stringOne has the same characters in the same order as stringTwo regardless of where they are in memory.
Now, as for your question, I would recommend using either an Enum or a Map to keep track of which object to use.
For example:
public class Tester {
public enum Location {
ROOM_A("Room A", "You are going into Room A"),
ROOM_B("Room B", "You are going into Room B"),
OUTSIDE("Outside", "You are going outside");
private final String name;
private final String actionText;
private Location(String name, String actionText) {
this.name = name;
this.actionText = actionText;
}
public String getActionText() {
return this.actionText;
}
public String getName() {
return this.name;
}
public static Location findByName(String name) {
name = name.toUpperCase().replaceAll("\\s+", "_");
try {
return Enum.valueOf(Location.class, name);
} catch (IllegalArgumentException e) {
return null;
}
}
}
private Location currentLocation;
public void changeLocation(String locationName) {
Location location = Location.findByName(locationName);
if (location == null) {
System.out.println("Unknown room: " + locationName);
} else if (currentLocation != null && currentLocation.equals(location)) {
System.out.println("Already in room " + location.getName());
} else {
System.out.println(location.getActionText());
currentLocation = location;
}
}
public static void main(String[] args) {
Tester tester = new Tester();
tester.changeLocation("room a");
tester.changeLocation("room b");
tester.changeLocation("room c");
tester.changeLocation("room b");
tester.changeLocation("outside");
}
}
*This is the standard way of formating Java code. Class names are PascalCased while variable names are camelCased.
String className=getClassName();//Get class name from user here
String fnName=getMethodName();//Get function name from user here
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(className);// get the Class
Object inst = thisClass.newInstance();// get an instance
// get the method
Method fn = thisClass.getDeclaredMethod(fnName, params);
// call the method
fn.invoke(inst, paramsObj);
The comments below your question are true - your code is very rough.
Anyway, if you have a method like
public void doSomething(String str) {
if (str.equals("whatever")) {
// do something
}
}
Then call it like
doSomething("whatever");
In Java, many classes have attributes, and you can and will often have multiple instances from the same class.
How would you identify which is which by name?
For example
class Room {
List<Monster> monsters = new ArrayList <Monster> ();
public Room (int monstercount) {
for (int i = 0; i < monstercount; ++i)
monsters.add (new Monster ());
}
// ...
}
Monsters can have attributes, and if one of them is dead, you can identify it more easily if you don't handle everything in Strings.
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);
}