How to overwrite file in Java with one changed value - java

I am trying to make a program that uses JFrames and JPanels to construct a voting program. There is a file called voters.txt that is formatted like so:
1234:Herb Weaselman:false
9876:Marge Magnificent:false
4444:Ingmar Inglenook:false
8888:Hector Heroman:false
5678:Agnes Angular:false
In the beginning of my program, I have to ask the user for their voter ID and if their input does not match one of the IDs from the text file, then the program ends. I have managed to achieve this but now I need to overwrite this voters.txt file by changing the false element of whoever voted to true. For instance, if the user entered an ID of 1234, then I would need to change the word after Herb Weaselman to true instead of false. I am not sure how to do this. I know how to write to a file but am not sure how to change that one specific element. Here is the code I have currently:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Assig5 extends JFrame
{
public Assig5()
{
}
public static void main(String[] args) throws IOException
{
LoginWindow loginWindow = new LoginWindow();
loginWindow.fileReader();
if(!loginWindow.checkResult(loginWindow.result))
{
System.out.println("Invalid Voter ID");
System.exit(0);
}
System.out.println("Continue");
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class LoginWindow extends JFrame
{
static ArrayList<String> list = new ArrayList<String>();
public String result;
public LoginWindow()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
result = JOptionPane.showInputDialog(frame, "Enter voter ID:");
}
public static void fileReader() throws FileNotFoundException
{
Scanner s = new Scanner(new File("voters.txt"));
while (s.hasNextLine())
{
list.add(s.nextLine());
}
s.close();
}
public static boolean checkResult(String result)
{
for(int i = 0; i < list.size(); i++)
{
String[] retval = list.get(i).split(":");
if(retval[0].equals(result))
{
return true;
}
}
return false;
}
}
Any help would be appreciated. Thanks in advance.

Just change your array index from false to true when there is a match. Then rewrite the file with the data from the array. If there is not match, the file does not change.
Solution
if(retval[0].equals(result)){
retval[2] = true;
return true;
}

Related

How to use a string from another method

I am trying to make a plugin where when a certain block in the GUI is clicked, a command is run. The problem is, I have to transfer a string from one method to another. I don't have very much java knowledge, so if someone could teach me how to do this, I would very much appreciate it.
P.S. The string I am trying to use is called custompermscommand.
Code:
package me.eliminiquated.yugengrant;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
public class Grant implements CommandExecutor, Listener {
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("grant")){
if (sender instanceof Player){
Player player = (Player) sender;
if (player.hasPermission("yugen.grant")){
if (args.length == 1){
player.sendMessage("Incorrect Usage! </grant (username)>");
}else if (args.length == 2){
Inventory gui = Bukkit.createInventory(player, 27, ChatColor.DARK_GREEN+"Grant Menu");
ItemStack custom = new ItemStack(Material.ORANGE_GLAZED_TERRACOTTA);
ItemStack playerranks = new ItemStack(Material.LAPIS_BLOCK);
ItemStack staffpositions = new ItemStack(Material.REDSTONE_BLOCK);
ItemMeta custommeta = custom.getItemMeta();
ItemMeta playerranksmeta = playerranks.getItemMeta();
ItemMeta staffpositionsmeta = staffpositions.getItemMeta();
custommeta.setDisplayName(ChatColor.GOLD+"Custom");
ArrayList<String> custom_lore = new ArrayList<>();
custom_lore.add(ChatColor.GRAY+""+ChatColor.ITALIC+"Coming soon");
custommeta.setLore(custom_lore);
custom.setItemMeta(custommeta);
playerranksmeta.setDisplayName(ChatColor.AQUA+"Player Ranks");
playerranks.setItemMeta(playerranksmeta);
staffpositionsmeta.setDisplayName(ChatColor.RED+"Staff Positions");
staffpositions.setItemMeta(staffpositionsmeta);
gui.setItem(10, custom);
gui.setItem(12, playerranks);
gui.setItem(14, staffpositions);
player.openInventory(gui);
String custompermscommand = "grantcustomperms "+args[0]+"";
}else{
player.sendMessage("Incorrect Usage! </grant (username)>");
}
}else{
player.sendMessage(ChatColor.RED+"You do not have permission to execute this command!");
}
}
}else{
System.out.println("You must be a player to execute this command");
}
return false;
}
#EventHandler
public void onInventoryClick(InventoryClickEvent event){
Player player = (Player) event.getWhoClicked();
if (event.getClickedInventory().getTitle().equalsIgnoreCase(ChatColor.DARK_GREEN+"Grant Menu")){
if (event.getCurrentItem().getType() == Material.ORANGE_GLAZED_TERRACOTTA){
Bukkit.dispatchCommand(player, custompermscommand);
}
}
}
}
For anyone that wants to do this themselves, this is the answer:
First, declare the variable as public outside of the methods:
Example:
public String command;
Next, edit the string inside of the method that you want to grab the string from:
Example:
command = args[0];
Finally, you are able to call this string in whatever method you want:
Example:
Bukkit.dispatchCommand(player, command);

Java, after using FileDialog, compilation does not end

I have simple java code to select the file and return array.
When I use dedicated method (whole code below), my compilation (in IntelliJ) does not end -> it gets to the last lane of public static void main(String[] arg), it executes last lane System.out.println("Program ends."); but I don't get information from compilator:
Process finished with exit code -1
Instead I need to stop it manually and if I want to run it again I get information that I can't run the code in parallel, would I like to stop it and rerun now.
Whole code:
import java.util.HashMap; //import the HashMap class
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import java.awt.FileDialog;
import java.awt.Frame;
public class Project1
{
public static void main(String[] arg)
{
HashMap<Integer, int[][]> dicUsedFuncs = new HashMap<Integer, int[][]>();
//import textfile with haskell code
String[] arrString=SelectFile();
System.out.println(arrString[0]);
System.out.println(arrString[1]);
//scan load
System.out.println("End");
}
private static String[] SelectFile()
{
String[] arrReturn = new String[2];
String strDefaultPath=System.getProperty("user.dir"); //default location to open
Frame frame = null;
FileDialog fd = new FileDialog(frame, "Please choose a text file with code.", FileDialog.LOAD);
fd.setDirectory(strDefaultPath);
fd.setFile("*.txt");
fd.setVisible(true);
String filename = fd.getFile(); //get just the selected file name
if (filename == null) {
arrReturn[0] = "NotSelected";
}else {
filename= new File(fd.getFile()).getAbsolutePath(); //get full file path of selected file
arrReturn[0] = "Selected";
arrReturn[1] = filename;
}
return arrReturn;
}
}
I added following:
library
import java.awt.Window;
loop to close all windows in method private static String[] SelectFile()
for (Window window : Window.getWindows()) { window.dispose(); }

How do I check to see if a dialog box is left blank? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I'm in the process of writing a program, and I get to the part(which I've commented below) and I try to do
if(userInput.get() != "")
It still executes the code inside the if statement if I leave the dialog box blank and press "ok" or enter. So it would say:
"You did not enter numeric information"
instead of
"You did not enter any information"
like in the outer else statement.
I tried with null and it didn't work either. What am I doing wrong here?
import java.util.Optional;
import javafx.application.*;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
import javafx.stage.*;
import javafx.stage.Stage;
public class QuizDialogBox extends Application {
public void start(Stage primaryStage) {
TextInputDialog inputDialog = new TextInputDialog();
inputDialog.setHeaderText(null);
inputDialog.setTitle("Grams to Ounces");
inputDialog.setContentText("Enter number of Grams: ");
Alert errorAlert = new Alert(AlertType.ERROR);
Optional<String> userInput = inputDialog.showAndWait();
if((userInput.get() != "") && userInput.isPresent()) //the part thats not working
{
String userInputString = userInput.get();
System.out.println("{" + userInputString + "}");
if(isNumeric(userInputString))
{
int userNumber = Integer.parseInt(userInputString);
System.out.println(userNumber);
}
else
{
errorAlert.setContentText("You did not enter numeric information");
errorAlert.showAndWait();
}
}
else
{
errorAlert.setContentText("You did not enter any information");
errorAlert.showAndWait();
}
}
public static void main(String args[]) {
launch(args);
}
public static boolean isNumeric(String string) {
boolean isNumber = false;
try
{
Integer.parseInt(string);
isNumber = true;
}
catch(NumberFormatException ex) {
}
return isNumber;
}
}
modify if(userInput.get() != "") to if(!userInput.get().isEmpty())
== compares the reference only.
Or you can use if(!userInput.get().equals("")) to compare two String
Be careful of checking null if userInput.get() is Nullable

java value recieved from client-server program used in another program

My project looks like: I have a bike speedometer attached to simple bike and connected to Raspberry Pi, which is connected over ethernet cable to laptop.
What I want to do is: Raspberry measure the speed of bike wheel and send this value over ethernet cable to laptop. Laptop now uses recieved value and speed up a video, which is played in VLC.
I have working java program on RPi to measure speed of a wheel, I have a working client (on laptop)-server (on RPi) java program to send values from RPi to laptop, and I have a working java program to control speed of video playing in VLC on laptop.
But my problem is, that I don't know how to use values, recieved from RPi over client-server program, in my program, which control speed of video, playing in VLC.
Down are my codes for client and to control speed of video.
Client code:
package player;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static int inputPlayer = 0;
public static void main(String[] args) throws UnknownHostException, IOException {
String accept;
int input;
DataInputStream inC = null;
Scanner sc1 = null;
Socket s = null;
try {
s = new Socket ("169.254.218.194", 1342);
Scanner sc = new Scanner (System.in);
System.out.println("Accept connection!");
accept = sc.next();
PrintStream p = new PrintStream (s.getOutputStream());
p.println(accept);
//inC = new DataInputStream(s.getInputStream());
}
catch (Exception e) {
e.printStackTrace();
}
while (true) {
sc1 = new Scanner (s.getInputStream());
input = sc1.nextInt();
if (input > 0) {
inputPlayer = input;
}
System.out.println("I" + input);
//System.out.println("IP" + inputPlayer);
}
}
public int getInputPlayer () {
return this.inputPlayer;
}
}
Player code:
package player;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
public class Player {
private final JFrame frame;
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
public static void main(final String[] args) {
new NativeDiscovery().discover();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Player(args);
}
});
}
public Player(String[] args) {
frame = new JFrame("My First Media Player");
frame.setBounds(100, 100, 600, 400);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
Scanner in = new Scanner (System.in);
frame.setContentPane(contentPane);
frame.setVisible(true);
mediaPlayerComponent.getMediaPlayer().playMedia("file:URL");
mediaPlayerComponent.getMediaPlayer().skip(1000);
client c = new client();
float i = c.getInputPlayer();
while (true) {
//float i = in.nextFloat();
//System.out.println(i);
mediaPlayerComponent.getMediaPlayer().setRate(i);
}
}
}
Everything I want to do is to use variable inputPlayer from client class as variable i in Player class.
As I have done, Eclipse return me error: "[000000001ade9eb0] core input error: input control fifo overflow, trashing type=2"
Thanks for your help.
Jan
There are several problems here:
the code in the client class (btw, class names should begin with uppercase) is never run. You've put all the code in that class in a main method, which only gets executed if you run the application by choosing that class. Essentially, you have two separate applications here. Even if you were to run them at the same time, it wouldn't help you since one would not have direct access to instances of classes in the other.
i is set only once and never updated inside the loop
you could turn that main method of the client class into an ordinary method, but even then you can't have two while(true) loops run at the same time if they are on the same thread.
If handling thread is a bit much for you at this stage, you could try simply combining both classes in one. One loop would scan for incoming data and set the players speed as it came. This might or might not work, depending on how the player itself is implemented, but you could give it a try.

How to integrate Metaphone to the spellchecker program in java-lucene?

While browsing i came up with a spellchecking program in lucene.I was interested in adding the phonetix add-on(specifically metaphone) from tangentum. Is there a way i can integrate metaphone into my program? How to integrate it?
package com.lucene.spellcheck;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.spell.Dictionary;
import org.apache.lucene.search.spell.PlainTextDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
public class SimpleSuggestionService {
private static final String F_WORD = null;
public static void main(String[] args) throws Exception {
File dir = new File("e:/spellchecker/");
Directory directory = FSDirectory.open(dir);
SpellChecker spellChecker1 = new SpellChecker(directory);
spellChecker1.indexDictionary(
new PlainTextDictionary(new File("c:/fulldictionary00.txt")));
String wordForSuggestions = "noveil";
int suggestionsNumber = 5;
String[] suggestions = spellChecker1.
suggestSimilar(wordForSuggestions, suggestionsNumber);
if (suggestions!=null && suggestions.length>0) {
for (String word : suggestions) {
System.out.println("Did you mean:" + word);
}
}
else {
System.out.println("No suggestions found for word:"+wordForSuggestions);
}
}
}
You can pass in a custom StringDistance implementation that utilizes desired phonetic algorithms, or combines it is some way with other similarity algorithms (such as the standard LevensteinDistance. You'll just need to implement the getDistance(String, String) method in you StringDistance implementation. Perhaps something like:
public MetaphoneDistance() {
Metaphone metaphone = new Metaphone();
}
//I'm not really familiar with the library you mentioned, but I assume generateKeys performs a double metaphone?
public float getDistance(String str1, ,String str2) {
String[] keys1 = metaphone.getKeys(str1);
String[] keys2 = metaphone.getKeys(str2);
float result = 0;
if (key1[0] == key2[0] || key1[0] == key2[1]) result += .5
if (key1[1] == key2[0] || key1[1] == key2[1]) result += .5
return result;
}

Categories

Resources