Java Bukkit coding: cannot kick players - java

Situation and question:
I want to kick players when they type swear words (case-insensitive).
Below is my attempt, but it doesn't kick the player. What did I do wrong?
Does not display any errors at all.
Source code:
#EventHandler
public void onPlayerChat(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (muted.contains(player.getUniqueId())) {
e.setCancelled(true);
player.sendMessage(ChatColor.DARK_BLUE + "[TC]" + ChatColor.DARK_RED + "You are muted and cannot chat.");
} else {
String message = e.getMessage();
if (message.contains("(?i)fuck") || message.contains("(?i)shit") || message.contains("(?i)ass") || message.contains("(?i)porno") || message.contains("(?i)porn") || message.contains("(?i)crap") || message.contains("(?i)dumb")) {
player.kickPlayer(ChatColor.DARK_RED + "Watch your language, please!");
e.setCancelled(true);
}
message = ChatColor.translateAlternateColorCodes('§', message);
message = ChatColor.translateAlternateColorCodes('&', message);
String text = ChatColor.DARK_BLUE + "[Chat]" + ChatColor.YELLOW + player.getName() + " " + ChatColor.DARK_RED + "Says: " + ChatColor.AQUA + message;
player.playNote(player.getLocation(),Instrument.PIANO, Note.natural(1, Tone.A));
text.replace("(?i)", "");
text = text.replace("<3", "❤");
text = text.replace(":)", "☺");
text = text.replace(":-)", "☺");
text = text.replaceAll("(?i)fuck", "****");
text = text.replaceAll("(?i)ass", "***");
text = text.replaceAll("(?i)shit", "****");
text = text.replaceAll("(?i)porno", "*****");
text = text.replaceAll("(?i)porn", "****");
text = text.replaceAll("(?i)dumb", "****");
text = text.replaceAll("(?i)crap", "****");
e.setFormat(text);
e.setMessage(text);
}
}

Use String.matches to match a regexp. Also, you can add all your swear words to some array/collection and use Java 8 features to simplify your code, e.g.
public static void main(String[] args) {
String message = "hello fuck world ass shit here i am";
final String[] swearWords = {"ass", "fuck", "shit", "porno", "porn"};
final boolean hasSwearWords = Stream.of(swearWords).anyMatch(w -> message.matches("(?i).*\\s" + w + "\\s.*"));
if (hasSwearWords) {
System.out.printf("Bad user!");
}
final String cleanMessage = Stream.of(swearWords).reduce(message,
(msg, w) -> msg.replaceAll(
"(?i)(\\s)" + w + "(\\s)",
"$1" + new String(new char[w.length()]).replace("\0", "*")+ "$2"));
System.out.println(cleanMessage);
}
Here is the code that doesn't require Java 8:
#EventHandler
public void onPlayerChat(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (muted.contains(player.getUniqueId())) {
e.setCancelled(true);
player.sendMessage(ChatColor.DARK_BLUE + "[TC]" + ChatColor.DARK_RED + "You are muted and cannot chat.");
} else {
String message = e.getMessage();
String[] swearWords = {"fuck", "shit", "ass", "porno", "porn", "crap", "dumb"};
for (String word : swearWords) {
if (message.matches("(?i).*\\s" + word + "\\s.*")) {
player.kickPlayer(ChatColor.DARK_RED + "Watch your language, please!");
e.setCancelled(true);
break;
}
}
message = ChatColor.translateAlternateColorCodes('§', message);
message = ChatColor.translateAlternateColorCodes('&', message);
String text =
ChatColor.DARK_BLUE + "[Chat]" + ChatColor.YELLOW + player.getName() + " " + ChatColor.DARK_RED + "Says: " +
ChatColor.AQUA + message;
player.playNote(player.getLocation(), Instrument.PIANO, Note.natural(1, Tone.A));
text = text.replace("<3", "❤")
.replace(":)", "☺")
.replace(":-)", "☺");
for (String word : swearWords) {
text = text.replaceAll(
"(?i)(\\s)" + word + "(\\s)",
"$1" + new String(new char[word.length()]).replace("\0", "*")+ "$2");
}
e.setFormat(text);
e.setMessage(text);
}
}

Related

I want to use 3 args The command should be like this: /event pop on

as I said in the title I want to make the following 2 commands: /event pvp on
and /event pop off
it is not working. Help me pls.
btw I'm new in Coding Java
this is my code:
public boolean onCommand(CommandSender sender, Command command, String label, String[] args, String arg2) {
Player player = (Player) sender;
if(label.equalsIgnoreCase("event")) {
if(args.length == 0) {
player.sendMessage("Syntax: /event (Event) on/off");
return true;
} else if(args.length == 1) {
String mode = args[0];
if(mode.equalsIgnoreCase("pvp")) {
if(arg2.length() == 1) {
String Modus = arg2;
if(Modus.equalsIgnoreCase("on")) {
new PlayerRDEvent(this);
for(Player onps : Bukkit.getOnlinePlayers()){
onps.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "PvP" + ChatColor.YELLOW + "Event" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + "Das PvP Event hat begonnen!");
onps.playSound(onps.getLocation(), Sound.ARROW_HIT, 2, 0);
}}}
return true;
} else if(mode.equalsIgnoreCase("off")) {
for(Player onps2 : Bukkit.getOnlinePlayers()){
onps2.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "PvP" + ChatColor.YELLOW + "Event" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + "Das PvP Event ist zu ende!");
onps2.playSound(onps2.getLocation(), Sound.ARROW_HIT, 2, 0);}
HandlerList.unregisterAll();
return true;
} else {
player.sendMessage("Use: /event (event) on/off");
}
}
}
return false;
}
You were using mode as a variable for args[0] and didn't use it to check if it was on. To check for the off/on string, equate mode to args[1] (Second element in array, because the first one would be pvp) and check before the conditions if args[0] is equal to pvp
Also, you cannot add the parameter String arg2 if you are overriding the method from JavaPlugin - so just use the default parameters of the method onCommand,
see: OnCommand Bukkit method
Code:
Player player = (Player) sender;
if (label.equalsIgnoreCase("event")) {
if (args[0].equals("pvp")) { //check if args[0] is pvp, you can add an else statement to send an error message if it is not pvp, or manipulate it differently
if (args.length != 2) { //if it does not contain both [pvp] and [off/on]
player.sendMessage("Syntax: /event (Event) on/off");
return true;
} else { //if args length = 2
String mode = args[1]; //[off/on]
if (mode.equalsIgnoreCase("on")) { //if args[1] is "on"
for (Player onps : Bukkit.getOnlinePlayers()) {
onps.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "PvP" + ChatColor.YELLOW + "Event" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + "Das PvP Event hat begonnen!");
onps.playSound(onps.getLocation(), Sound.ARROW_HIT, 2, 0);
}
return true;
} else if (mode.equalsIgnoreCase("off")) { //if args[1] is "off"
for (Player onps2 : Bukkit.getOnlinePlayers()) {
onps2.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "PvP" + ChatColor.YELLOW + "Event" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + "Das PvP Event ist zu ende!");
onps2.playSound(onps2.getLocation(), Sound.ARROW_HIT, 2, 0);
}
HandlerList.unregisterAll();
return true;
} else {
player.sendMessage("Use: /event (event) on/off");
}
}
}
}
return false;
}
}
I really suggest you implement some sort of command listener in the near future instead of checking for each command on the onCommand method as it makes your code cleaner and easier to read

Adding all lines of output to one JOptionPane window after while loop

I am trying to add all of the output records from a regex parsed txt file to one JOptionPane window. I have created a string to capture, but mine continues to print individual windows. Any ideas? Thanks
while ((line = br.readLine()) != null) {
if (Pattern.matches(titlePattern, line)) {
String name = "", price="";
String patternName = "title=\".*?(\")";
Pattern r = Pattern.compile(patternName);
Matcher m = r.matcher(line);
if (m.find( )) {
name = m.group(0);
//System.out.println("Title: " + name.substring(7, name.length()-1));
}
String patternPrice = "Suggested Retail Price:.*?\"";
String strOutput;
r = Pattern.compile(patternPrice);
m = r.matcher(line);
if (m.find( )) {
price = m.group(0);
//System.out.println("Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1));
//JOptionPane.showMessageDialog(null, "Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1));
final_list.addElement("Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1));
strOutput = "Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1);
JOptionPane.showMessageDialog(null, strOutput);
}
}
}
Try to use java.swing.TextArea to build message and JOptionPane to display it. Here is short demo:
public static void main(String[] args) {
TextArea textView = new TextArea();
textView.append("dsddd");
textView.append("jsdjsd");
textView.append("qwoqwo");
JOptionPane.showMessageDialog(null, textView);
}

Java beginner troubles; calling from methods. hopefully small issue,

I'm working on this little project, I was given the driver and had to write the helper class for it.
Driver:
public class MyBookDriver {
private static final Scanner KBD = new Scanner(System.in);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Constructors
MyBookAccount bbSheldon = new MyBookAccount("Sheldon", true);
MyBookAccount bbPenny = new MyBookAccount("Penny", false);
MyBookAccount bbAmy = new MyBookAccount("Amy", "Montreal", true);
MyBookAccount bbLeonard = new MyBookAccount("Leonard");
System.out.println("\n" + MyBookAccount.getNumAccounts()
+ " MyBook accounts have been created.");
// Mybook ID
System.out.println("\nMyBook Accounts:");
System.out.println(" Sheldon's ID: " + bbSheldon.ID);
System.out.println(" Penny's ID: " + bbPenny.ID);
System.out.println(" Amy's ID: " + bbAmy.ID);
System.out.println(" Leonard's ID: " + bbLeonard.ID);
pause();
// logged in
System.out.println("\nMyBook Accounts:");
System.out.println(" Sheldon is "
+ (bbSheldon.isLoggedIn() ? "" : "not ") + "logged in");
System.out.println(" Penny is "
+ (bbPenny.isLoggedIn() ? "" : "not ") + "logged in");
System.out.println(" Amy is "
+ (bbAmy.isLoggedIn() ? "" : "not ") + "logged in");
System.out.println(" Leonard is "
+ (bbLeonard.isLoggedIn() ? "" : "not ") + "logged in");
pause();
//post a wall message
System.out.println("\nPosting wall update:");
bbSheldon.setWallPost("I like flags!");
bbPenny.setWallPost("Looking for a job.");
bbLeonard.setWallPost("I'm just hoping I can date a girl "
+ "from next door.");
System.out.println(" Sheldon's: " + bbSheldon.getWallPost() + "\n"
+ " Penny's: " + bbPenny.getWallPost() + "\n"
+ " Amy's: " + bbAmy.getWallPost() + "\n"
+ " Leonard's: " + bbLeonard.getWallPost() + "\n");
pause();
//Sending messages
System.out.println("\nSending messages:");
bbLeonard.sendMessage(bbPenny, "Will you go out with me tonight?");
bbAmy.sendMessage(bbSheldon, "Neuroscience is a real science.");
bbPenny.sendMessage(bbAmy, "What a nice picture.");
checkMessages(bbSheldon);
checkMessages(bbPenny);
checkMessages(bbAmy);
checkMessages(bbLeonard);
pause();
//toString
System.out.println("\nDisplaying info:");
System.out.println(bbSheldon);
System.out.println(bbPenny);
System.out.println(bbAmy);
System.out.println(bbLeonard);
pause();
}
private static void checkMessages(MyBookAccount user) {
MyBookAccount aFriend;
aFriend = user.getFriend();
if (aFriend != null) {
System.out.println(" " + user.getName() + "'s message from "
+ aFriend.getName()
+ " is " + user.getMessage());
} else {
System.out.println(" " + user.getName() + " has no messages");
}
}
private static void pause() {
System.out.print("\n...press enter...");
KBD.nextLine();
}
}
And my (messy unfinished) code:
public class MyBookAccount {
public final int MAX_CHAR = 20;
public final int ID;
public static int nextId = 1;
private String name;
private String location;
private Boolean loggedIn;
private String wallPost = "(none)";
private String latestMessage = "(none)";
private MyBookAccount friend = null;
private static int numberOfAccounts = 0;
MyBookAccount(String n, String l, Boolean i) {
name = n;
location = l;
loggedIn = i;
ID = nextId;
nextId++;
numberOfAccounts++;
}
MyBookAccount(String n, Boolean i) {
name = n;
location = "Halifax";
loggedIn = i;
ID = nextId;
nextId++;
numberOfAccounts++;
}
MyBookAccount(String n) {
name = n;
location = "Halifax";
loggedIn = false;
ID = nextId;
nextId++;
numberOfAccounts++;
}
public static int getNumAccounts() {
return numberOfAccounts;
}
public void setLoggedIn(boolean log) {
loggedIn = !log;
}
boolean isLoggedIn() {
return loggedIn;
}
public void setWallPost(String newPost) {
if (newPost.length() > MAX_CHAR) {
System.out.println("Cannot update wall post for " + name
+ ". Post must be 20 characters or less.");
} else {
wallPost = newPost;
}
}
public String getWallPost() {
return wallPost;
}
public String getMessage() {
return this.latestMessage;
}
public void sendMessage(MyBookAccount to, String message) {
friend = to;
if (to.loggedIn != true) {
System.out.println("Could not post message from " + name
+ ". " + to.name + " is not logged in!");
latestMessage = "(none)";
} else if (to.loggedIn == true) {
latestMessage = message;
}
}
public MyBookAccount getFriend() {
return friend;
}
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
#Override
public String toString() {
if (friend == null) {
return "MyBookAccount #" + ID + "{\n "
+ name + " in " + location + "\n "
+ "About me: " + wallPost + "\n "
+ "Logged In:" + loggedIn + "\n ";
} else {
return "MyBookAccount #" + ID + "{\n "
+ name + " in " + location + "\n "
+ "About me: " + wallPost + "\n "
+ "Logged In:" + loggedIn + "\n "
+ "Message from " + friend.name + ": "
+ latestMessage + ".\n";
}
}
}
I just can't figure out one thing.
In the messages part, I' getting the from and to people mixed up.
For example; It should say
Sending messages:
Could not post message from Leonard. Penny is not logged in!
Sheldon's message from Amy is Neuroscience is a real science.
Penny has no messages
Amy's message from Penny is What a nice picture.
Leonard has no messages
and I get:
Sending messages:
Could not post message from Leonard. Penny is not logged in!
Sheldon has no messages
Penny's message from Amy is What a nice picture.
Amy's message from Sheldon is Neuroscience is a real science.
Leonard has no messages
Any ideas on how to remedy this?
Thanks a bundle.
I'm not trying to debug your code here, but let me just make a remark on this:
public void sendMessage(MyBookAccount to, String message) {
friend = to;
if (to.loggedIn != true) {
System.out.println("Could not post message from " + name
+ ". " + to.name + " is not logged in!");
latestMessage = "(none)";
} else if (to.loggedIn == true) {
latestMessage = message;
}
}
This code smells, because it will not send any message, but just alter the state of this (the sender's) object ( friend = to, latestMessage = ...). Plus it checks the conditions of the receiver, while the message should just send a message and react on any bad outcome. Rather imagine something like this:
class MyBookAccount {
//....
public void sendMessage(MyBookAccount receiver, String message) {
try{
receiver.accept(this, message);
}catch(MessageRejectedException e){
//maybe put in queue to try again later, or log the date, time and reason of failure.
}
}
}
where:
class MyBookAccount {
private final List<String> receivedMessages = new ArrayList<>();
...
public void accept(MyBookAccount sender, String message){
if(!loggedIn){
throw new MessageRejectedException("not online");
}
receivedMessages.add(message);
//you can also have a list of Objects that are like
//class Message{String senderName; String message; Date reveived; /*...*/}
//trigger UI update or fire property changed event that announces the list of messages has changed
}
public Optional<String> getLastMessage(){
return receivedMessages.isEmpty() ? Optional.empty()
: Optional.of(receivedMessages.get(receivedMessages.size()-1));
}
This way the receiver of the message has full control over the conditions that it needs to receive a message, or how many messages it likes to keep, or if it likes to record a date with the message (when the message was received). The sender does not care, whether the receiver is just a proxy, the receiver itself or what conditions have to be met to send the message, it just has to handle the possible error conditions (which can be many) - and it is free to ignore or log them as well.
I think that the start of the method sendMessage(MyBookAccount to, String message) { got a problem. Since you send a message to someone, the friend should be setted to the receiver ?
So it would rather be:
public void sendMessage(MyBookAccount to, String message) {
to.setFriend(this);
Then in the MyBookAccount you add a method like this:
public void setFriend(MyBookAccount friend) {
this.friend = friend;
}

Why my method don't read all of my File? ... Java?

I have to display all of records in my blocks (text files), and do a split to "cover" the Fields Separators, but only the first record of my blocks are diplayed. What am I doing wrong?
enter code here
public static void listAllStudents() throws IOException {
File path = new File(Descriptor.getBlockPath());
for (int i = 0; i < path.listFiles().length; i++) {
try {
FileInputStream file = new FileInputStream(Descriptor.getBlockPath() + "BLK" + i + ".txt");
InputStreamReader entrada = new InputStreamReader(file);
BufferedReader buf= new BufferedReader(entrada);
String piece = " ";
System.out.println("\nBLOCO " + i + " ------------------------------------------------------ +");
do {
if (buf.ready()) {
piece = buf.readLine();
System.out.println("\n¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨");
String string = " ", field[] = piece.split(Descriptor.getFieldSeparator());
string = " ";
System.out.println("CPF: " + field[0]);
System.out.println("Name: " + field[1]);
System.out.println("Course: " + field[2]);
System.out.println("Age: " + field[3]);
System.out.println("Phone: " + field[4]);
System.out.println("Active: " + field[5]);
string = " ";
}
} while (buf.ready());
buf.close();
} catch (IOException e) {
System.out.println();
}
}
}
See the documentation for the BufferedReader.readLine() method:
or null if the end of the stream has been reached
Then change your code to read the file line by line:
while ((piece = buf.readLine()) != null) {
String field[] = piece.split(Descriptor.getFieldSeparator());
if (field.length >= 6) {
System.out.println("CPF: " + field[0]);
System.out.println("Name: " + field[1]);
System.out.println("Course: " + field[2]);
System.out.println("Age: " + field[3]);
System.out.println("Phone: " + field[4]);
System.out.println("Active: " + field[5]);
}
}

How can I use a while to continuously ask for input from a user and exit the program when "quit" is typed without using system.exit()?

I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
next();
}
public static void next() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
next3(expression);
}
public static void next3(String expression) {
while (!expression.equals("quit")) {
next2(expression);
next();
}
}
public static void next2(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static boolean QuitFunction(String expression) {
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return false;
}
else {
return true;
}
}
}
Take a look at this code. I think this might help you in the right direction. It's similar to what you have already written except it eliminates the need for method calls in your while loop.
Scanner input = new Scanner(System.in);
while (!input.hasNext("quit")) {
String expression = input.nextLine(); // gets the next line from the Scanner
next2(expression); // process the input
}
// once the value "quit" has been entered, the while loop terminates
System.out.println("Goodbye");
Writing it this way drastically cleans up your code and prevents a new declaration of Scanner kb = new Scanner(System.in); each time an input is processed.

Categories