Receiving an 'else' without 'if' error - java

import javax.swing.JOptionPane;
public class Cortana2 {
public static void main(String[] args) throws Exception {
//Declaring Variables (Add more commands)
String command;
// Command will always stay the same
// All strings below are commands to put in
String Steam;
String League;
League=("League");
Steam=("Steam");
command= JOptionPane.showInputDialog("Give a valid command");
if (command == null) {
JOptionPane.showMessageDialog(null, "This is not a valid command. If you have forgotten what commands are valid, please refer to Devon for assistance");
JOptionPane.getRootFrame().dispose();
} else if (command == League) {
Runtime.getRuntime().exec("\"D:/LeagueClient.exe\"");
} else if (command == Steam) {
Runtime.getRuntime().exec("\"C:/Program Files (x86)/Steam/Steam.exe\"");
}
}
}
Not 100% sure why I'm getting the error. I've seen where others said to remove the semicolons from the 'if' statements but then nothing executes when I run the program and type in commands. Sorry if anything seems poorly formatted.

if (command == null);
Don't put a ";" at the end of your if/else statements.
but then nothing executes when I run the program and type in commands
Don't use == to compare String.
Instead use the String.equals(...) method
Also variable names should NOT start with an upper case character.

You have an extraneous semicolon at the end of each test
else if (command == League); // <- remove these semicolons
You're also going to have grief using == to compare strings. Use .equals() instead.

Remove Semicolon From If, Else If An Use equals Method After Your Code Looks Like This..
command= JOptionPane.showInputDialog("Give a valid command")
{
if (command.equals(null)
{
JOptionPane.showMessageDialog(null, "This is not a valid command. If you have forgotten what commands are valid, please refer to Devon for assistance");
JOptionPane.getRootFrame().dispose();
}else if (command.equals(League))
{
Runtime.getRuntime().exec("\"D:/LeagueClient.exe\"");
}else if (command.equals(Steam))
{
Runtime.getRuntime().exec("\"C:/Program Files (x86)/Steam/Steam.exe\"");
}
System.exit(0);
}

Related

How to stop while loop from reading each line of a file if condition becomes true?

I have this particular code somewhere in my program.
while(scanner.hasNext()){
contents = scanner.nextLine();
if((contents.contains(username))&&(contents.contains(password))){
call.fileManager();
}
if((!contents.contains(username))&&(!contents.contains(password))){
JOptionPane.showMessageDialog(null, "Invalid username/password! Check your spelling/capitalization.", "Error!", JOptionPane.ERROR_MESSAGE);
call.loginFrame();
}
}
I'd like the loop to quit once the condition is satisfied. For example, if a specific content is found in the file, it would go to the first if, then call the file manager and exit. If the content is not found, it will go to the second if statement instead.
UPDATE:
It seems like I have forgotten break. I'm sorry for this stupid question :)
UPDATE:
No, break did not solve my problem. Something more of that did. I used counter to read each line and a counter to decrement and increment. After that I subtracted the counter decremented/incremented from the counter which reads the line. Of course if nothing was read, it would return a 0.
Use break like below
while (obj != null) {
if (obj == null) {
break;
}
}
For your code it would be something like this
while (scanner.hasNext()) {
contents = scanner.nextLine();
if ((contents.contains(username)) && (contents.contains(password))) {
call.fileManager();
break;
}
if ((!contents.contains(username)) && (!contents.contains(password))) {
JOptionPane.showMessageDialog(null, "Invalid username/password! Check your spelling/capitalization.", "Error!", JOptionPane.ERROR_MESSAGE);
call.loginFrame();
break;
}
}
You can use break to terminate the while loop. Also, at a given point, only one of the condition will be satisfied. So use if...else construction for better performance (though, the difference won't be clearly visible in this case!).
But it definitely reduces the work of the compiler internally.
while(scanner.hasNext())
{
contents = scanner.nextLine();
if((contents.contains(username))&&(contents.contains(password)))
{
call.fileManager();
break;
}
else
{
JOptionPane.showMessageDialog(null, "Invalid username/password! Check your spelling/capitalization.", "Error!", JOptionPane.ERROR_MESSAGE);
call.loginFrame();
break;
}
}

Why is my code in Java giving me so much trouble with if else statements in this specific line of code in Jgrasp?

Learning Java, now I do not know why but this code keeps giving me issues with else if statements.
public class Sherlock
{
public static void main(String[] args)
{
String answer = "Watson";
String response = "";
int tries = 0;
Scanner input = new Scanner(System.in);
while (tries <=3);
{
System.out.print("Enter the name of Sherlock's partner, and dear friend. ");
response = input.nextLine();
tries++;
if (response.equals ("Watson"))
while (tries<= 3)
{
System.out.println("Yes, that is right, Barrel Rider.");
break;
}
else if (tries == 3)
{
System.out.println("Ooooh, sorry kid but it looks like you are S.O.L.");
break;
}
else
while (tries <= 3)
{
System.out.println("Sorry, try again!");
}
}
}
}
The if else statement error has been more or less solved, but now I'm getting a different error:
Sherlock.java:24: error: break outside switch or loop
break;
^
1 error
Why does it keep insisting I put break outside the switch or loop?
remove the semi-colons from the if statement
if (response.equals ("Watson"))
And the while loop
while (tries <=3)
These semi-colons are messing up the parsing of your control statements. The reason why the semi-colon after the if-statement messes things up is that the parser doesn't expect there to be a body due to the presence of the semi-colon, and therefore it doesn't expect there to be an else statement after an if-statement with no body.
In the future, I suggest that you make sure that you have checked your code for valid semantics and syntax. You will learn the basics about control statements from any good tutorial on YouTube.

manipulating an arraylist of type String

I've got a problem here that's been giving me some real trouble and I really cant even get an idea of what to do. here's the assignment and my code so far.
Create a system using an ArrayList which stores and manipulates names.
Using standard input constantly prompt user for the following ..
Enter command or quit: (if they enter quit -- quit program)
Commands:
add <name>: add the String <name> to ArrayList;
change <name> <newName>: change all items in ArrayList which
have <name> to <newName>;
delete <name>: delete all items in Arraylist which are <name>;
print: print the ArrayList;
amount: display the amount of items in ArrayList.
System must work... and have proper error messages..
import java.util.*;
public class NameManipulation {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("enter a command, or quit!");
ArrayList<String> names = new ArrayList<String>();
String command = console.next();
int size = names.size();
for (String x = null; size; x++) {
if (command == "add") {
String assignment = console.next();
names.add(assignment);
}
if (command == "change") {
String newname = console.next();
names.set(names.size, newname);
}
if (command == "delete") {
String delete = console.next();
if (delete == names)
;
names.remove();
}
if (command == "print") {
System.out.println(names);
}
if (command == "amount") {
amount = (names.size - 1);
System.out.println(amount);
}
if (command == "quit") {
System.out.println("You just quit!");
break;
} else
System.out.println("command not found!");
System.out.println(names);
}
}
}
Don't use == (in Java that tests reference equality); you want to test for object value equality (and I suggest case-insensitivity) so you want to use String.equalsIgnoreCase and you should probably use else if for the other tests - for one example,
if(command.equalsIgnoreCase("add")) {
String assignment = console.next();
names.add(assignment);
} else if // ...
Also, this is just wrong;
for (String x = null; size; x++) // null++ is going to give you a bad time.
I think you wanted
for (int x = 0; x < size; x++)
Just looking at this it seems like it has a lot of problems...
In the for loop you're initializing a String to null and then trying to increment it (x++). I don't think that's legal syntax. Also, your for loop condition is set to size, which will initially be equal to 0. I'd have to test it, but the 0 may evaluate to false, which means the loop would never execute.
You don't want a for loop anyway, probably a do-while loop that runs until the command is equal to "quit" do{}while(!command.equals("quit"));
You should be using .equals() instead of '==' as was mentioned by Elliot Frisch. Also ignoring case is good, and you should be using else ifs.
In the change command you should be parsing out two parameters -- both the name to replace and the new name, and then perform the replacement. Right now you have the first parameter as names.size, which I think will be outside the bounds of the list (names.size() - 1 should be the last element). Instead you should get the index of the name you're replacing.
Depending on Java's toString implementation of ArrayList it may print out names nicely or it might be something like "#ArrayList Object" - I think Java has a nice ArrayList toString method though so that may work.
On the print amount, you should be using names.size() instead of names.size() - 1 (because names.size() - 1 will give you one less item than what is actually in the list)
you could try and use a switch block that could stream line your control statements. As stated above learn when to use == and when to use the .equals(). One compares a reference (==) the other compares the memory location, the important thing to take away from this, is that a String is an object and when you create a new String, it compares the address rather than a value (forgive me if i am wrong).
switch(command){
case "add": names.add(assignment);
break;
case "change": ..... etc.
}
If I were trying to accomplish this task I would use a List, not an ArrayList. I hope this method helps! This is C# code. I don't know the exact Java syntax but it seemed as if a lot of it was similar. I hope this methodology helps!
static void Main(string[] args)
{
string statement = "";
bool executed_command_properly;
while (statement != "quit")
{
executed_command_properly = false;
statement = Console.ReadLine();
string[] my_statement_elements = statement.Split(' ');
string command = my_statement_elements[0];
//could possibly use an array for inputs
string input1 = my_statement_elements[1];
string input2 = my_statement_elements[2];
switch(command)
{
case "add":
// do stuff
executed_command_properly = true;
break;
//other cases
}
if (executed_command_properly != true)
{
//error messages
}
}
}

Making a command line, if statements not working

I want to make a command line, just to run basic commands. So far, I've made it so that people can tell the program their name. When I don't enter a name, however, it treats it as if I did. Here is my class:
public static void main(String args[])
throws IOException
{
int a = 1;
do
{
System.out.print("$$: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String wtt = null; // wtt = what they typed!
wtt = br.readLine();
if(wtt == null)
{
System.out.println("Why wont you tell me your name!");
}
else
{
System.out.println("Thanks for the name, " + wtt);
}
}
while(a == 1);
}
Here is the output
$$: well
Thanks for the name, well
$$: hole
Thanks for the name, hole
$$:
Thanks for the name,
Why does it not work?
Calling readLine() on a BufferedReader will only return null on end of input. Here, the input hasn't ended, you've just entered an empty line, so "" (the empty string) is the result.
You will need to end the input stream, usually with Ctrl-C. Then you'll get "Why wont you tell me your name!". But then you'll need to break out of your infinite loop.
use this
if (wtt == null || wtt.trim().length() == 0)
Try
wtt.length()==0
instead of checking for null
It's because although you set the string to null at first, you are then setting it to br.readLine() which will have a line to read even though the user didn't type anything before hitting enter, so it will set the string to an empty string.
You should also (or instead) compare your string to "" (an empty string) to see if they entered anything.
You should compare wtt to "" as well to make sure the line isn't empty.
if (wtt == null) {
becomes
if (wtt == null && !!("".equals(wtt))) {
Instead of comparing wtt to null, compare it to empty string:
if ("".equals(wtt))
{
System.out.....
}
readLine method doesn't give you end of line characters (e.g. \n, \r). So, you cannot expect the loop to exit when you press just enter without entering anything. You can use read method instead to read characters and determine if there was a new line character or use Scanner class which seems to me better suitable in your situation.

Control program from command line arguments

How do I pick the methods in my program to run using command line arguments? For example, if I want my program to process an image called Moon.jpg, how do I make it work so that -S Moon.jpg in the command line would invoke the Scale method? Or -HI Moon.jpg would flip the image Horizontally and Invert it? I have some methods written and they work when I run the program normally.
You can parse arguments with a function like this:
private void parseArguments(String[] args)
{
int i = 0;
String curArg;
while (i < args.length && args[i].startsWith("-"))
{
curArg = args[i++];
if ("-S".compareTo(curArg) == 0)
{
if (i < args.length)
{
String image = args[i++];
processImage()
}
else
{
// ERROR
}
}
}
}
Your main method should always have String[] args which contains arguments split on the space character. There are also plenty of libraries you can use to parse command line arguments. This method is quite similar to what the Apaches CLI library uses (Of course there's a lot more that comes with that library but the parser uses this logic).
http://commons.apache.org/cli/
This should help. and here's how to use it:
http://commons.apache.org/cli/usage.html
You may need to write different methods for each purpose and have if/else conditions based on command input.
why not read the arguments passed and read subsequent value to do the required stuff
ie,
java yourprogram -a1 something -a2 somethingelse
and in your program
public static void main(String[] args){
for(int i=0;i<args.length;i++){
switch(args[i]){//you can use if-else to deal with string...
case "-a1":read args[i+1] to get value to do somethng
case "-a2": read args[i+1] to get value to do something else
}
}

Categories