I have a problem when I am loading a String with :
public void loadGameDataFromFile() {
try
{
FileInputStream saveFile = new FileInputStream("SaveObj.sav");
ObjectInputStream objectStream = new ObjectInputStream(saveFile);
place = (String) objectStream.readObject(); // place is a string //defined at the start of my class
objectStream.close();
saveFile.close();
System.out.println(place);
}catch(Exception e)
{
e.printStackTrace(System.out);
}
}
After loading the String like this i try to use a case with it and there shows up the problem.It seems to me that it doesn't compares them like it should.
That is the code of the switch statment:
public enum Places
{
Anfang,
Strand,
Wald, Waldex, Berg, Höhle, Höhlet, Haus1, Haus2, Haus3, Haus4, Strandex, Höhlett, Kampf, Lichtung, Wald2, Fuß, Bergm, Spitze, Keller, Strand2, Strandx2, Gespräch,Höhlettt //this are the Strings which my String "place" can be...
}
public void actionPerformed( ActionEvent evt)
{
Places replace = Places.valueOf(place);
switch(replace)
{
case Anfang: //do my stuff
break;
case Strand: //do my stuff
break;
case Wald: //do my stuff
break;
}
}
This problem only appears when I use the String after it was loaded.When I start it without loading the String it just works fine.
When I remove the enum and use just my String in the switch statment it has the same problem that it doesnt seem to understand that the String equals one of the cases.
Update:
The problem still exists and I could change my case to if else but this would be retreating from solving the problem.
Whats the problem with this method:
public String loadGameDataFromFile() {
try
{
FileInputStream saveFile = new FileInputStream("SaveObj.sav");
ObjectInputStream objectStream = new ObjectInputStream(saveFile);
String place = (String) objectStream.readObject();
objectStream.close();
saveFile.close();
return place; // return the string
}catch(Exception e)
{
e.printStackTrace(System.out);
return "";
}
}
public void main(String arg[]){
String place = loadGameDataFromFile();
// instead of unnecessary switch case...
if(place.equals("something")){
}else if(place.equals("something else")){
...
}else if(...){
...
}
}
Another method for Java SE 7:
String string = loadGameDataFromFile();;
switch(string){
case "A":
case "B":
break;
}
Related
I have this account creation program I'm working on, and would love to save the persons name, last name, email and password to a text file. The following snippet should do just that, but the error message I'm getting when I put a String variable in the .write method is, "no suitable method found for write(JTextFeild)".
private void signupActionPerformed(java.awt.event.ActionEvent evt) {
fname.getText();
lname.getText();
email.getText();
reemail.getText();
password.getText();
repassword.getText();
if(male.equals(true)) {
males = true;
}
if(female.equals(true)) {
females = true;
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter("UserPass.txt"));
writer.write(fname);
}
catch ( IOException e) {
}
finally {
try {
if ( writer != null) {
writer.close( );
}
}
catch ( IOException e) {
}
}
}
Any ideas on how to fix this?
From the documentation of getText() in javax.swing.text.JTextComponent:
public String getText()
JTextField is just the GUI element, getText() doesn't change it.
You should store the result in a String variable and then use it to write().
So I'm Serializing an ArrayList of ArrayLists essentially but I'm running into an issue. To be honest I'm still pretty new to Java, I've tried so many different methods to fix this as well as searched relentlessly on this site and have not been successful. I know that the way I word things may be hard to follow along or is confusing so I'll post my code here to see. Sorry in advance for all the code. SuperUsers has an arraylist of LoginInfo, PasswordKeeper has an Arraylist of SuperUsers, and the SuperUser arraylist gets serialized in PasswordKeeper. but any changes made to the LoginInfo arraylist do not save and i cannot figure out why. If anyone can help I would really Appreciate it. Thanks
public class PasswordKeeper{
private ArrayList<SuperUser> users;
private static Scanner keyboard = new Scanner(System.in);
public PasswordKeeper() {
users = new ArrayList();
}
public void login() {
try {
// reads in SuperUser arraylist
get();
} catch (EOFException a) {
System.out.println("You are the First User!");
} catch (IOException b) {
System.out.println(b);
} catch (ClassNotFoundException c) {
System.out.println(c);
}
boolean loopDisplay = true;
while (loopDisplay) {
existingUser = keyboard.next();
existingPass = keyboard.next();
SuperUser temp = new SuperUser(existingUser, existingPass);
System.out.println();
if (users.contains(temp)) {
// viewing superUser method
temp.display();
//saves after method call is over
try {
System.out.println("Saving.");
save(users);
} catch (IOException e) {
System.out.println(e);
}
}
}
//This happens if there is a new user
if(answer == 2){
SuperUser tempNew = null;
boolean cont = true;
String newUser;
String pass;
while(cont){
newUser = keyboard.nextLine();
System.out.println();
//System.out.println(users.size());
tempNew = new SuperUser(newUser, pass);
if(passValid(pass) == true){
if(makeSure(tempNew) == true){
System.out.println("Login Created!");
tempNew = new SuperUser(newUser, pass);
//actually being added to the arraylist
users.add(tempNew);
cont = false;
}
}
}
//SuperUser.display method
tempNew.display();
try{
System.out.println("Saving.");
save(users);
}catch(IOException e){
System.out.println(e);
}
}
}
}
//makeSure and passValid methods
public boolean makeSure(SuperUser user){
if(users.contains(user)){
return false;
}
return true;
}
public boolean passValid(String pass){
boolean passes = false;
String upper = "(.*[A-Z].*)";
String lower = "(.*[a-z].*)";
String numbers = "(.*[0-9].*)";
String special = "(.*[,~,!,#,#,$,%,^,&,*,(,),-,_,=,+,[,{,],},|,;,:,<,>,/,?].*$)";
if((pass.length()>15) || (pass.length() < 8)){
System.out.println("Entry must contain over 8 characters\n" +
"and less than 15.");
passes = false;
}if(!pass.matches(upper) || !pass.matches(lower)){
System.out.println("Entry must contain at least one uppercase and lowercase");
passes = false;
}if(!pass.matches(numbers)){
System.out.println("Password should contain atleast one number.");
passes = false;
}if(!pass.matches(special)){
System.out.println("Password should contain atleast one special character");
passes = false;
}else{
passes = true;
}
return passes;
//serializable methods
public void save(ArrayList<SuperUser> obj) throws IOException {
File file = new File("userInformation.dat");
FileOutputStream fileOut = new FileOutputStream(file, false);
BufferedOutputStream buffedOutput = new BufferedOutputStream(fileOut);
ObjectOutputStream out = new ObjectOutputStream(buffedOutput);
out.writeObject(obj);
out.close();
fileOut.close();
}
public ArrayList<SuperUser> get() throws IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream("userInformation.dat");
BufferedInputStream buffedInput = new BufferedInputStream(fileIn);
ObjectInputStream in = new ObjectInputStream(buffedInput);
users = (ArrayList<SuperUser>) in.readObject();
in.close();
fileIn.close();
return users;
}
public class SuperUser implements Serializable {
private String userName;
private String password;
private static Scanner keyboard = new Scanner(System.in);
private ArrayList<LoginInfo> info = new ArrayList();
public SuperUser(String name, String pass) {
userName = name;
password = pass;
}
public String getUser() {
return userName;
}
public void display() {
String next = keyboard.next();
//want to add data to LoginInfo arraylist
if (next.equalsIgnoreCase("add")) {
add();
} else if (next.equalsIgnoreCase("delete")) {
delete();
} else if (numberCheck(next)) {
int choice = (int) Integer.parseInt(next) - 1;
edit(choice);
//!!!! this: after doing this i lose whatever data i added
//to the LoginInfo arraylist, right after this the
//SuperUser arraylist gets saved. but the added data to
//loginInfo does not
} else if (next.equalsIgnoreCase("logout")) {
System.out.println(info.size());
}
}
public boolean numberCheck(String in) {
try {
Integer.parseInt(in);
} catch (NumberFormatException e) {
return false;
}
return true;
}
//method to add to the Arraylist
public void add() {
System.out.println("What is the website name?:");
String trash = keyboard.nextLine();
String webName = keyboard.nextLine();
System.out.println("The Username?:");
String webUsername = keyboard.nextLine();
System.out.println("The Password?:");
String webPass = keyboard.nextLine();
info.add(new LoginInfo(webUsername, webPass, webName));
System.out.println(info.size());
//method goes back to display
display();
}
}
}
Your problem is here
SuperUser temp = new SuperUser(existingUser, existingPass);
System.out.println();
if (users.contains(temp)) {
// viewing superUser method
temp.display();
You create a temporary object which with the username and password.
Your 'users.contains()' method returns true because '.equals()' is based on the username, however the 'temp' object is a different instance to that in the list.
So when you call 'temp.display()' it is not calling on an object in the list, so no data changes will save.
You need to find the existing object from the list for that user. I would suggest that you swap your list for a map keyed on username.
You have a list named users. Once you created new SuperUser instance (temp), you are checking that it belongs to this list (users.contains(temp), which is false of course - from where it will occur there?). If it have belonged, the method display would be called, which in turn would add LoginInfo to that SuperUser (add() call), but I bet in reality it doesn't happened.
Also, I see where you read from users (check whether new SuperUser instances belong there), I see where you overwrite it (during desealization) but I don't see adding any instance to there, which makes me think that it is always empty.
Are you sure that SuperUser contains any LoginInfo in its array list?
rather new to programming, trying to solve this for several days, read multiple tutorials and questions here, still cannot make this work.
Task - read wordpress RSS feed into ListView.
Problem - i've managed to successfully count number or titles, or get the last one. When trying to write all titles to array or array list, i fail. Simple String array gives endless cycle, String ArrayList gives empty values.
Here's the code I'm trying to write to ArrayList. Removed connection part, which seems to be working.
public class HandleXML{
private String title = "title";
ArrayList<String> listAdapterValues = new ArrayList<String>();
public ArrayList<String> parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text = null;
ArrayList<String> allTitles = new ArrayList<String>();
.....
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equals("title")) {
title = text;
allTitles.add(title);
}
else if (name.equals("link")) {
}
else if (name.equals("pubDate")) {
}
break;
}
event = myParser.next();
}
}
catch (Exception e) {
e.printStackTrace();
}
return allTitles;
}
....
public class NewsPage extends Activity {
ArrayList<String> allTitles = new ArrayList<String>();
....
obj = new HandleXML(finalUrl);
allTitles = obj.fetchXML();
....
I'm not getting any errors on logcat, seems i'm doing something wrong but don't understand what is it.
Any help would be appreciated,
thank you!
I try to parse simple xml file with XmlPullParser.
<?xml version="1.0" encoding="utf-8"?>
<tests>
<test>
<name>Jack</name>
</test>
<test>
<name>Brad</name>
</test>
<test>
<name>Tom</name>
</test>
</tests>
This is the MainActivity code:
public class MainActivity extends ActionBarActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
ArrayList<Quote> quotes;
ArrayList<Pers> persons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InputStream inputStream = getResources().openRawResource(R.xml.test);
Fetcher fetcher = new Fetcher();
persons = fetcher.parse(inputStream);
String str = new String();
for(int i = 0; i < persons.size(); i++) {
str += persons.get(i).getName();
}
Log.d("1", str);
}
}
This is the Fetcher class code:
public class Fetcher {
private ArrayList<Pers> persons;
private Pers person;
private String text;
public Fetcher() {
persons = new ArrayList<Pers>();
}
public ArrayList<Pers> parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch(eventType) {
case XmlPullParser.START_TAG:
if(tagname.equalsIgnoreCase("test")) {
person = new Pers();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if(tagname.equalsIgnoreCase("test")) {
persons.add(person);
} else if(tagname.equalsIgnoreCase("name")) {
person.setName(text);
}
break;
default:
break;
}
eventType = parser.next();
}
} catch(XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return persons;
}
}
Why does XmlPullParserException exception occurs?
org.xmlpull.v1.XmlPullParserException: unterminated entity ref (position:TEXT ��������������������...#1:49 in java.io.InputStreamReader#405534d8)
I changed code, now it works. Thank those who tried to help me.
public class Fetcher {
private ArrayList<Pers> persons;
private Pers person;
private String text;
public Fetcher() {
persons = new ArrayList<Pers>();
}
public ArrayList<Quote> parse(Activity activity) throws XmlPullParserException, IOException {
Resources resources = activity.getResources();
XmlResourceParser xmlResourceParser = resources.getXml(R.xml.quotes);
person = new Pers();
xmlResourceParser.next();
int eventType = xmlResourceParser.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT) {
String tagName = xmlResourceParser.getName();
switch(eventType) {
case XmlPullParser.START_TAG: {
if(tagName.equalsIgnoreCase("test")) {
person = new Pers();
}
break;
}
case XmlPullParser.TEXT: {
text = xmlResourceParser.getText();
break;
}
case XmlPullParser.END_TAG: {
if(tagName.equalsIgnoreCase("test")) {
persons.add(person);
} else if(tagName.equalsIgnoreCase("name")) {
person.setId(Integer.parseInt(text));
}
break;
}
default:
break;
}
eventType = xmlResourceParser.next();
}
return persons;
}
}
I imagine it's this line: parser.setInput(is, null);
Because the xml encoding is UTF-8, I believe you have to change it to parser.setInput(is,"UTF-8");
I think that the problem is in different input to what you have shown us. Or maybe the source code is different.
The error message seems to refer to a position that does not exist - line 1, character position 49 (or vice versa).
The error message seems to indicate some garbled characters (or a string of NULs), but there is nothing problematic in the sample XML.
A bit late but, in case it helps anyone else, check:
There are no characters that need escaping in the XML file e.g. & which should be &#amp;
Make sure the attributes are correctly enclosed in quotes (in my case, eclipse had been helpful putting close quotes in, so when I added the close quotes at the end of my text, it gave an error
I checked through my XML by starting with the outermost tags, deleting the content and re-adding in bits, running each time, to find where the errors were. Debugging XML files is a real pain!
I'm using java.util.resourcebundle to format my JSTL messages and this works fine:
I use the class MessageFormat you can see here. Now I want to encapsulate this to a method that is just getParametrizedMessage(String key, String[]parameters) but I'm not sure how to do it. Now there is quite a lot of work to display just one or two messages with parameters:
UserMessage um = null;
ResourceBundle messages = ResourceBundle.getBundle("messages");
String str = messages.getString("PF1");
Object[] messageArguments = new String[]{nyreg.getNummer()};
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString("PI14"));
String outputPI14 = formatter.format(messageArguments);
formatter.applyPattern(messages.getString("PI15"));
String outputPI15 = formatter.format(messageArguments)
if(ipeaSisFlag)
if(checkIfPCTExistInDB && nyreg.isExistInDB()) {
//um = new ExtendedUserMessage(MessageHandler.getParameterizedMessage("PI15", new String[]{nyreg.getNummer()}) , UserMessage.TYPE_INFORMATION, "Info");
um = new ExtendedUserMessage(outputPI15 , UserMessage.TYPE_INFORMATION, "Info");
…and so on. Now can I move this logic to a static class MessageHandler.getParameterizedMessage that now is not working and looking like this:
private final static String dictionaryFileName="messages.properties";
public static String getParameterizedMessage(String key, String [] params){
if (dictionary==null){
loadDictionary();
}
return getParameterizedMessage(dictionary,key,params);
}
private static void loadDictionary(){
String fileName = dictionaryFileName;
try {
dictionary=new Properties();
InputStream fileInput = MessageHandler.class.getClassLoader().getResourceAsStream(fileName);
dictionary.load(fileInput);
fileInput.close();
}
catch(Exception e) {
System.err.println("Exception reading propertiesfile in init "+e);
e.printStackTrace();
dictionary=null;
}
}
How can I make using my parametrized messages as easy as calling a method with key and parameter?
Thanks for any help
Update
The logic comes from an inherited method that in in the abstract class that this extends. The method looks like:
protected static String getParameterizedMessage(Properties dictionary,String key,String []params){
if (dictionary==null){
return "ERROR";
}
String msg = dictionary.getProperty(key);
if (msg==null){
return "?!Meddelande " +key + " saknas!?";
}
if (params==null){
return msg;
}
StringBuffer buff = new StringBuffer(msg);
for (int i=0;i<params.length;i++){
String placeHolder = "<<"+(i+1)+">>";
if (buff.indexOf(placeHolder)!=-1){
replace(buff,placeHolder,params[i]);
}
else {
remove(buff,placeHolder);
}
}
return buff.toString();
}
I think I must rewrite the above method in order to make it work like a resourcebundle rather than just a dictionary.
Update 2
The code that seems to work is here
public static String getParameterizedMessage(String key, Object [] params){
ResourceBundle messages = ResourceBundle.getBundle("messages");
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString(key));
return formatter.format(params);
}
I'm not really sure what you're trying to achive, here's what I did in the past:
public static final String localize(final Locale locale, final String key, final Object... param) {
final String name = "message";
final ResourceBundle rb;
/* Resource bundles are cached internally,
never saw a need to implement another caching level
*/
try {
rb = ResourceBundle.getBundle(name, locale, Thread.currentThread()
.getContextClassLoader());
} catch (MissingResourceException e) {
throw new RuntimeException("Bundle not found:" + name);
}
String keyValue = null;
try {
keyValue = rb.getString(key);
} catch (MissingResourceException e) {
// LOG.severe("Key not found: " + key);
keyValue = "???" + key + "???";
}
/* Message formating is expensive, try to avoid it */
if (param != null && param.length > 0) {
return MessageFormat.format(keyValue, param);
} else {
return keyValue;
}
}