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;
}
Related
I have a method in my super class that writes data into a file, and that method is overridden in my subclasses. Problem is at run time I get prompted three different times to create a new file. Here is my code:
public class Employee
{
protected String name;
protected String employeeNum;
protected String department;
protected char type;
protected BufferedWriter printer;
}
public void writeData() throws IOException
{
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the name of the new file for next week");
String newFile = sc.nextLine();
printer = new BufferedWriter(new FileWriter(newFile + ".txt"));
String data= getData();
printer.write(data);
}
protected String getData()
{
return name + " " + employeeNum + " " + department + " " + type;
}
public class Commission extends Employee
{
private int weeksStart;
private double baseWeeklySalary;
private double salesWeekly;
private double totalSales;
private double commissionRate;
}
#Override
protected String getData()
{
return name + " " + employeeNum + " " + department + " " + type + " " + weeksStart + " " + baseWeeklySalary + " " + salesWeekly + " " + totalSales + " " + commissionRate;
}
Assume all relevent construcors are there. I have two other subclasses; Hourly, and Salary that trys to implement the same writeData() method. When I iterate through my ArrayList of employees and try to writeData(),
It creates a new file for every type of employee when I need it to create just one
Public class PayRoll
{
Private ArrayList < Employee > employees;
public class PayRoll()
{
employees = new ArrayList Employee > ();
}
public void endOfDay()
{
for (int I = 0: i < employees.size (): i++)
{
employees.get(i).writeData():
}
}
}
I'd break this method in to two parts. One part requests a file name from the user, opens it, etc. This part doesn't need to be overridden. The only part that needs to be overridden is the part that generates the data string, which can be placed in a method of its own:
public class Employee {
/* Data members, omitted for brevity's sake */
public void writeData() throws IOException {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the name of the new file");
String newFile = sc.nextLine();
printer = new BufferedWriter(new FileWriter(newFile + ".txt"));
String data = getData();
printer.write(data);
}
protected String getData() {
return name + " " + employeeNum + " " + department + " " + type;
}
}
public class Commission extends Employee {
/* Data members, omitted for brevity's sake */
#Override
protected String getData() {
return name + " " + employeeNum + " " + department + " " + type + " " + weeksStart + " " + baseWeeklySalary + " " + salesWeekly + " " + totalSales + " " + commissionRate;
}
}
Add a static variable isFileCreated, set it to true after creating file, and execute that block only if that variable is false.
I've been searching for a while, and simply can't find a way to do this. The problem is a multi-user chat client, which works fine. The issue I'm having is being able to send a message from one user to another (client-client), without printing it to the other users.
private static class Handler extends Thread {
Map<String, Socket> database_UID = new HashMap<String, Socket>();
private String name;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public int users;
private String whisper;
private String pass;
private String pass_err = "Unauthorized login attempt";
public Handler(Socket socket) {
this.socket = socket;
}
public void Append(Socket socket, String name) {
database_UID.put(name, socket);
users++;
System.out.println(ANSI_WHITE + "For reference, the Socket of " + name + " is: " + socket + ANSI_RESET);
// socket.out.println("Welcome!");
}
public void validate(String name_1) {
// With a given name, will validate Admin and TestBot passwords
if (name_1.equals("Zach")) {
out.println("What's your password, admin?");
try {
pass = in.readLine();
} catch (IOException e) {
System.out.println(e);
}
if (pass.equals("1234")) {
name = ANSI_RED + "ADMIN" + ANSI_RESET + " Zach";
Append(socket, name);
} else {
System.out.println(ANSI_WHITE + "Connection at " + socket.getInetAddress().getHostName() + ":" + socket.getPort() + " Has been terminated for:" + ANSI_RESET + " " + ANSI_RED
+ pass_err + ANSI_RESET + "\n");
Removal();
}
} else if (name_1.equals("Test")) {
out.println("What's your password, TestBot?");
try {
pass = in.readLine();
} catch (IOException e) {
System.out.println(e);
}
if (pass.equals("tester")) {
name = ANSI_RED + "TESTER" + ANSI_RESET + " TestBot";
Append(socket, name);
} else {
System.out.println("Connection at " + socket.getInetAddress().getHostName() + ":" + socket.getPort() + " Has been terminated for:" + ANSI_RESET + " " + ANSI_RED + pass_err
+ ANSI_RESET + "\n");
Removal();
}
} else {
Append(socket, name);
}
}
public void Removal() {
if (name != null) {
names.remove(name);
}
if (out != null) {
writers.remove(out);
}
try {
socket.close();
} catch (IOException e) {
}
}
public void run() {
try {
System.out.println(ANSI_WHITE + "Connection received from " + socket.getInetAddress().getHostName() + ":" + socket.getPort() + ANSI_RESET);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
out.println("What's your name?");
name = in.readLine();
if (name == null) {
return;
}
if (name.equals("Zach") || name.equals("zach")) {
validate("Zach");
} else if (name.equals("Test") || name.equals("test")) {
validate("Test");
}
System.out.println(ANSI_WHITE + "Connection at " + socket.getInetAddress().getHostName() + ":" + socket.getPort() + " Has the name " + ANSI_RESET + "'" + name + "'\n");
if (socket.getInetAddress().equals("localhost")) {
System.out.println(ANSI_WHITE + "Connection received locally" + ANSI_RESET);
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
break;
}
}
}
out.println("Your name has been accepted, " + name);
writers.add(out);
while (true) {
String input = in.readLine();
if (input == null) {
return;
}
for (PrintWriter writer : writers) {
// Allows the user to quit from the server whilst keeping
// the terminal open
if (input != null) {
writer.println("MESSAGE " + name + ": " + input);
if (input.equals("quit")) {
writer.println(ANSI_RED + "SYSTEM: " + ANSI_RESET + "USER " + name + " IS QUITING");
Removal();
// The problem is here
} else if (input.equals("whisper " + name)) {
out.println("Type the message to " + name);
whisper = in.readLine();
out.println(whisper);
} else if (input.equals("help")) {
out.println("\n\nHELP MENU\nTo QUIT: Type '" + ANSI_PURPLE + "quit" + ANSI_RESET + "'\nTo WHISPER: Type '" + ANSI_PURPLE + "whisper name_of_user" + ANSI_RESET + "'");
} else {
writer.println("MESSAGE " + name + ": " + input);
}
}
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
// Removes the user from the list of names
Removal();
}
}
}
I'm using a Thread, and when the user joins, I add both their name and their Socket to a dictionary
Map<String, Socket> database_UID = new HashMap<String, Socket>();
public void Append(Socket socket, String name) {
database_UID.put(name, socket);
users++;
System.out.println(ANSI_WHITE+"For reference, the Socket of "+name+" is: "+socket+ANSI_RESET);
//socket.out.println("Welcome!");
}
What I would like to do is, as seen in a comment there, something like socket.out.println(USER'S_MESSAGE);, which obviously doesn't work.
If it's relevant, the client's socket is being added as
public Handler(Socket socket) {
this.socket = socket;
}
The tl;dr version:
Person A to whole server: Hi!
Person B specifically to Person A: Hi!
EDIT: Included above is the entire Thread. The for(PrintWriter writer : writers) { is where it would go, under 'whisper'.
Follow these steps
Create another thread on the server to listen to the messages coming from clients.
Send message from client A to server
Check the destination client (which can be part of you message sent from client to server)
Send the message from server to the destined client.
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);
}
}
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.
I'm creating a booking system in Java to prevent double bookings i have created a for loop that should change a Boolean to booked once the booking is made however it is changing all the bookings to booked when i only want one instance of booking so no one else can make a booking.
public static boolean booked;
private void FSubmitActionPerformed(java.awt.event.ActionEvent evt) {
for ( int i = 0; i < Airplane.Fseat.length; i++)
{
String seat = FCol.getSelectedItem().toString() + FRow.getSelectedItem().toString();
String items = Snack.getSelectedItem().toString() + " " + Drink.getSelectedItem().toString();
Airplane.Fseat[i] = seat;
Airplane.item[i] = items;
if (Airplane.Fseat[i] != null)
{
System.out.println("Seat number is First class " + Airplane.Fseat[i].toString() + "\n" +"Food and drink " + " " + Airplane.item[i].toString());
i++;
}
else
{
System.out.println("Cannot book already taken");
}
}
You have not put any condition to check, how a particular seat will be set selected.
So you will need to modify your code as:
for ( int i = 0; i < Airplane.Fseat.length; i++)
{
String seat = FCol.getSelectedItem().toString() + FRow.getSelectedItem().toString();
String items = Snack.getSelectedItem().toString() + " " + Drink.getSelectedItem().toString();
if(your_condition_to_check_if_this_seat_is_selcted ){
Airplane.Fseat[i] = seat;
Airplane.item[i] = items;
}
if (Airplane.Fseat[i] != null)
{
System.out.println("Seat number is First class " + Airplane.Fseat[i].toString() + "\n" +"Food and drink " + " " + Airplane.item[i].toString());
i++;
}
else
{
System.out.println("Cannot book already taken");
}
}