hi, i'm making a simple program where it when you type a name of soemthing from a video game it will give you a brief description, i'll be using if and else statements, here is what i have so far.

import java.util.Scanner;
public class WoW
{
public static void main(String[] args)
{
String classname;
String rogue;
Scanner inputDevice = new Scanner(System.in);
System.out.println("Welcome");
System.out.println("Please enter a WoW class");
classname = inputDevice.nextLine();
if(classname == rogue)
{
System.out.println("A rogue uses stealth and daggers to destroy it's opponent.");
}
else
{
System.out.println("bye bye");
}
}
}

the rogue string is what im having trouble with, i believe im declaring rogue wrongly im not sure how i would go about declaring it. I want rogue to be what the person will type in in a literal sense.

Dani AI

Generated

The compile error happened for two reasons. Declaring String rogue; without assigning a value leaves a local variable uninitialized, so using it in if(classname == rogue) causes a compile-time error. Also, == checks object identity, not text content, so it is the wrong operator for string comparison in Java. As pointed out, using the String API to compare contents (case-insensitively if needed) is the correct approach.

Quick fixes and safeguards:

  • Initialize the variable if a separate named variable is really needed, or drop the extra variable and compare the input to the literal.
  • Prefer calling the comparison on the literal (for example, literal.equalsIgnoreCase(userInput)) to avoid a NullPointerException if the input is ever null. Trim the input first to remove stray whitespace. The String API docs explain the behavior of these methods String.equalsIgnoreCase javadoc.

If the program will support many class names, switch-style chains get unwieldy. A simple Map driven lookup is clearer and scales well:

import java.util.*;
import java.util.Locale;

public class WoWMap {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Map<String,String> descriptions = new HashMap<>();
    descriptions.put("rogue", "A rogue uses stealth and daggers to destroy its opponent.");
    descriptions.put("mage", "A mage uses spells to control the battlefield.");

    System.out.print("Please enter a WoW class: ");
    String input = in.nextLine().trim().toLowerCase(Locale.ROOT);
    String desc = descriptions.get(input);
    System.out.println(desc != null ? desc : "bye bye");
  }
}

For stronger typing and compile-time safety consider an enum of classes with descriptions or, if using Java 7+, a switch on normalized input.

Recommended Answers

All 2 Replies

You can just use

if(classname.equalsIgnoreCase("rogue")){

it worked, thank you :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.