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

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);
}

Related

JOptionPane is getting trunkcated on only one JOptionPane but not the other

I have two buttons that are supposed to open JOptionPanes. One of them does not format to the right size. The code looks the same to me. What am I doing wrong here?
This one does not display all the text in the JTextArea:
public static void listAllTransactions(){
DecimalFormat fmt = new DecimalFormat("0.00");
String message = "List All Transactions \n";
message += "Name: " + ca.getName() + "\n\n";
message += "ID\tType\tAmount\n";
for (Transaction t : ca.transactions){
message += t.getTransNumber() + "\t" +
HelperTransactionIds.getTransactionName(t.getTransIdType()) + "\t$" +
fmt.format(t.getTransAmount()) + "\n";
}
JTextArea jTextArea = new JTextArea(message);
jTextArea.setEditable(false);
jTextArea.setBackground(Color.LIGHT_GRAY);
JOptionPane.showMessageDialog(null,jTextArea);
}
The other one works as intended.
The code looks the same to me but I could be missing something:
public static void listChecks(){
DecimalFormat fmt = new DecimalFormat("0.00");
String message = "List All Checks \n";
message += "Name: " + ca.getName() + "\n\n";
message += "ID\tCheck\tAmount\n";
for (Transaction t : ca.transactions){
if (t.getTransIdType() == HelperTransactionIds.CHECK){
Check myCheck = (Check) t;
message += t.getTransNumber() + "\t" +myCheck.getNumber() + "\t$" + fmt.format(t.getTransAmount()) + "\n";
}
}
JTextArea jTextArea = new JTextArea(message);
jTextArea.setEditable(false);
jTextArea.setBackground(Color.LIGHT_GRAY);
JOptionPane.showMessageDialog(null, jTextArea);
}

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]);
}
}

Java Bukkit coding: cannot kick players

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);
}
}

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.

Regular expression in java to replace a pattern in multiple lines

I want to replace this file input to a html table:
ip add St Stat Type Mode ip only class numbers
------------------------------ -- ----- ---- ---- --------------- ------ -----
ABC_127.562.200.5/32 - up ABC - 127.562.200.5 5
ABC_127.292.200.3/32 - up ABC - 127.562.200.5 4
ABC_127.262.200.13/32 - up ABC - 127.562.200.5 3
ABC:jdnsajkds
I know this will end with "ABC" but I am not able to figure out why "/" is also coming in input
import java.util.regex.*;
interface LogExample {
public static final int NUM_FIELDS = 7;
public static final String logEntryLine = "ABC_127.562.200.5/32 **space** -- **space** up **space** ABC **space** -- **space** 127.562.200.5 **space** 5 **space** ";
}
public class LogRegExp implements LogExample {
public static void main(String argv[]) {
String logEntryPattern = "";//thats i am not getting
System.out.println("Using RE Pattern:");
System.out.println(logEntryPattern);
System.out.println("Input line is:");
System.out.println(logEntryLine);
Pattern p = Pattern.compile(logEntryPattern);
Matcher matcher = p.matcher(logEntryLine);
if (!matcher.matches() ||
NUM_FIELDS != matcher.groupCount()) {
System.err.println("Bad log entry (or problem with RE?):");
System.err.println(logEntryLine);
return;
}
System.out.println("name + IP Address: " + matcher.group(1));
System.out.println("status1: " + matcher.group(2));
System.out.println("status2: " + matcher.group(3));
System.out.println("type: " + matcher.group(4));
System.out.println("mode: " + matcher.group(5));
System.out.println("IP Address: " + matcher.group(6));
System.out.println("class: " + matcher.group(7));
System.out.println("numbers: " + matcher.group(8));
}
}
Since your class column is blank, we can't do very much to extract that information. But this regex will match the 7 columns of data that you do have:
String logEntryPattern = "(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)";
We need to escape the backslash in the Java string literal.
System.out.println("name + IP Address: " + matcher.group(1));
System.out.println("status1: " + matcher.group(2));
System.out.println("status2: " + matcher.group(3));
System.out.println("type: " + matcher.group(4));
System.out.println("mode: " + matcher.group(5));
System.out.println("IP Address: " + matcher.group(6));
System.out.println("numbers: " + matcher.group(7));
Frankly, a regular expression is a little much for what you're trying to so -- just tokenizing on spaces would work just as well -- but it gets the job done.
I got the solution:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] )
{
// String to be scanned to find the pattern.
// String line = "MSEM-E-031_TO_RVBC-R-001_T1 en up TE ingr 124.252.200.2 ELSP 0";
// String pattern = "((\\-{8})+.*?)";
String line = "ADR-SSF-1008-M008 vlan en dn 10081008";
String pattern = "((\\-{6})+.*?)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( ))
{
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
}
else
{
System.out.println("NO MATCH");
}
}
}

Categories