I'm doing a train ticket program. I want to convert certain text in the string array to a certain price using JOptionPane.
ex.
String[] option_1 = {"location1","location2", "location3","location4","location5"};
where location1 = $10, location2 = $23, etc.
all I know is I could use Interger.parseInt or double, but I don't know where to go next. Should I go with a loop or make a whole new array and make it equal to the string array. I'm wondering if there is a more easier method to execute this.
code :
public static void main (String [] args) {
String name;
String[] option_1 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
String[] option_2 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
name = JOptionPane.showInputDialog("Welcome to DME Ticketing System!\n\nEnter your name:");
String leave = (String)JOptionPane.showInputDialog(null, "Leaving from",
"Train Station", JOptionPane.QUESTION_MESSAGE, null, option_1, option_1[0]);
String going = (String)JOptionPane.showInputDialog(null, "Leaving from",
"Train Station", JOptionPane.QUESTION_MESSAGE, null, option_2, option_2[0]);
// int pay = (Integer)JOptionPane.showInputDialog(null, "From: "+leave+"\nTo: "+going+"\nFare Price: "+"\n\nEnter your payment amount:",
// null, JOptionPane.PLAIN_MESSAGE, null, null,null);
// int op1 = Integer.parseInt(going);
// int op2 = Integer.parseInt(leave);
JOptionPane.showMessageDialog(null, "DME Ticketing System\nMalolos, Bulacan\n\n"
+ "Name: "+name
+"\nLocation: "+leave
+"\nDestination: "+going
+"\nFare: "
+"\nPayment: "//+pay
+"\nChange: "
, "RECEIPT",JOptionPane.INFORMATION_MESSAGE);
}
-The codes I turned into comments are giving me errors
showInputDialog always returns the input of the user as a String object, except from a variation where it returns the selected Object from the supplied ones. I am talking for Java version 8 for the sake of example.
Based on your question and comments, you basically want to:
Match String objects (their name) to integers (their value), so that you can calculate how much they will have to pay, plus the change afterwards.
Receive as input from the user the amount they will give, in order to calculate the change.
If so, then:
For the first case you can use some data structure(s) from which you will be able to match the locations with their value. For example a HashMap<String, Integer> can match the locations with their value, like so:
//Set up the origin options, along with their value:
HashMap<String, Integer> leavingOptions = new HashMap<>();
leavingOptions.put("North Avenue", 10);
leavingOptions.put("Quezon Avenue", 11);
leavingOptions.put("Kamuning", 12);
leavingOptions.put("Cubao", 13);
leavingOptions.put("Santolan", 14);
leavingOptions.put("Ortigas", 15);
leavingOptions.put("Shaw", 16);
leavingOptions.put("Boni", 17);
leavingOptions.put("Guadalupe", 18);
leavingOptions.put("Buendia", 19);
leavingOptions.put("Ayala", 20);
leavingOptions.put("Magallanes", 21);
leavingOptions.put("Taft", 22);
//Get user input for origin:
Object[] leavingOptionsArray = leavingOptions.keySet().toArray();
String leaving = (String) JOptionPane.showInputDialog(null, "Leaving from:", "Train Station", JOptionPane.QUESTION_MESSAGE, null, leavingOptionsArray, leavingOptionsArray[0]);
//Show output depending on user's input or cancel:
if (leaving != null)
JOptionPane.showMessageDialog(null, "You shall pay: " + leavingOptions.get(leaving));
else
JOptionPane.showMessageDialog(null, "Quiting...");
(note here that the casting of the returned value of the showInputDialog to a String reference is safe, just because the way we set up the options' array to contain only String objects)
Or you can use a String array with the locations along with an int array with the corresponding values, like so:
//Set up the origin options, along with their price:
String[] leavingOptions2 = new String[]{"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
int[] price = new int[]{10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};
//Get user input for origin:
Object leaving2 = JOptionPane.showInputDialog(null, "Leaving from:", "Train Station", JOptionPane.QUESTION_MESSAGE, null, leavingOptions2, leavingOptions2[0]);
//Show output depending on user's input or cancel:
if (leaving2 != null) {
//Find the price of the selected location:
int p = -1;
for (int i = 0; i < price.length; ++i)
if (leaving2.equals(leavingOptions2[i])) {
p = price[i];
break;
}
JOptionPane.showMessageDialog(null, "You shall pay: " + p);
}
else
JOptionPane.showMessageDialog(null, "Quiting...");
Or even better, you can use another object type other than String for the options array, for example a class named Location which will have the name and the price as properties, the toString method of which will return the name.
For the second part, obtain the user's input as a String from a JOptionPane and use Integer.parseInt(...) method on the user's input so as to be able to calculate the change afterwards, like so:
String paymentString = JOptionPane.showInputDialog(null, "Enter payment amount:", "Payment", JOptionPane.QUESTION_MESSAGE);
if (paymentString != null) {
try {
int payment = Integer.parseInt(paymentString);
JOptionPane.showMessageDialog(null, "You chose to pay: " + payment);
//Calculate change here...
}
catch (final NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "The input was invalid (not an 'int').");
}
}
else
JOptionPane.showMessageDialog(null, "Quiting...");
Remember that parseInt will throw a NumberFormatException (which is a RuntimeException) if its input String is not an int, so you will have to check for that using a try-catch block.
I am trying to extract pst file into msg.
I am using aspose jar. I share my code where we get exact number of file in each subfolder.
public static void displayFolderAndMessageInformationForPSTFile(String dataDir) {
// Load the Outlook PST file
PersonalStorage pst = PersonalStorage.fromFile(dataDir + "allen.pst");
// Get the folders information
FolderInfoCollection folderInfoCollection = pst.getRootFolder().getSubFolders();
// Browse through each folder to display folder name and number of messages
for (int i = 0; i < folderInfoCollection.size(); i++) {
FolderInfo folderInfo = (FolderInfo) folderInfoCollection.get_Item(i);
System.out.println("FolderId: " + folderInfo.getEntryIdString());
System.out.println("Folder: " + folderInfo.getDisplayName());
System.out.println("Total items: " + folderInfo.getContentCount());
System.out.println("Total unread items: " + folderInfo.getContentUnreadCount());
System.out.println("-----------------------------------");
}
}
FolderId: AAAAAJJu05VTxVRJlC5mJefQvVeCgAAA
Folder: Inbox
Total items: 66
Total unread items: 0
But when extract message content then i get different number of msg. It give only 49 msg in inbox folder.
The following below code:
public static void main(String[] args) {
String pstFileName = dataDir + "allen.pst";
// Load the Outlook PST file
PersonalStorage pst = PersonalStorage.fromFile(pstFileName);
// Get the folders and messages information
FolderInfo folderInfo = pst.getRootFolder();
// Create a folder for this PST
String strRootFolderName = "allen.pst".replace(".pst", "") + ".Java";
new File(dataDir + strRootFolderName).mkdir();
// Call the recursive method to extract msg files from each folder
extractMsgFiles(folderInfo, pst, dataDir + strRootFolderName);
}
private static void extractMsgFiles(FolderInfo folderInfo, PersonalStorage pst, String strPSTFile) {
// Display the folder name
System.out.println("Folder: " + folderInfo.getDisplayName());
// Create folder to store the messages
String folderName = strPSTFile + "\\" + folderInfo.getDisplayName();
new File(folderName).mkdir();
// Loop through all the messages in this folder
MessageInfoCollection messageInfoCollection = folderInfo.getContents();
for (int i = 0; i < messageInfoCollection.size(); i++) {
MessageInfo messageInfo = (MessageInfo) messageInfoCollection.get_Item(i);
System.out.println("Saving message " + messageInfo.getSubject() + "....");
// Get the message in MapiMessage instance
MapiMessage message = pst.extractMessage(messageInfo);
// Delete special characters which are invalid to use as windows file name
String messageName = null;
if (message.getSubject() == null || message.getSubject().isEmpty() == true) {
messageName = getRidOfIllegalFileNameCharacters(messageInfo.getEntryIdString());
} else {
messageName = getRidOfIllegalFileNameCharacters(message.getSubject());
}
// Save this message to disk in MSG format
message.save(folderName + "\\" + messageName + ".msg");
}
// Call this method recursively for each subfolder
if (folderInfo.hasSubFolders() == true) {
for (int i = 0; i < folderInfo.getSubFolders().size(); i++) {
FolderInfo subfolderInfo = (FolderInfo) folderInfo.getSubFolders().get_Item(i);
extractMsgFiles(subfolderInfo, pst, strPSTFile);
}
}
}
Help me... Where did i make mistake ? I am new in Aspose.
Please have a look at the following code snippet for extracting message files. You may use this method in place of your extractMsgFiles method.
private static void ExtractMsgFiles(FolderInfo folderInfo, PersonalStorage pst)
{
// display the folder name
Console.WriteLine("Folder: " + folderInfo.DisplayName);
Console.WriteLine("==================================");
// loop through all the messages in this folder
MessageInfoCollection messageInfoCollection = folderInfo.GetContents();
foreach (MessageInfo messageInfo in messageInfoCollection)
{
Console.WriteLine("Saving message {0} ....", messageInfo.Subject);
// get the message in MapiMessage instance
MapiMessage message = pst.ExtractMessage(messageInfo);
// save this message to disk in msg format
message.Save(message.Subject.Replace(":", " ") + ".msg");
// save this message to stream in msg format
MemoryStream messageStream = new MemoryStream();
message.Save(messageStream);
}
// Call this method recursively for each subfolder
if (folderInfo.HasSubFolders == true)
{
foreach (FolderInfo subfolderInfo in folderInfo.GetSubFolders())
{
ExtractMsgFiles(subfolderInfo, pst);
}
}
}
You may visit the link Working with Messages in a PST File in case you are interested in more details.
I work with Aspose as Developer evangelist.
The emails not having unique subject names could be causing this issue? I had this exact issue when doing something similar in Powershell. Putting an autonumber in the filename could help get around this.
I'm not sure how the start and end date work with the whole find appointments. I am getting all the rooms for a public group, then getting the rooms for the group, then getting the appointments within a date range.
But the ranges act weird, I know there are appointments on 12-19 to 12-16, but if I set the start date range to 2013-10-10 and the end date to 2013-12-28, I get nothing.
If I set the end date to 2014-01-28, I get tons of stuff that is in the range previously mentioned. Why is that?
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials( "username", "pw");
service.setCredentials( credentials );
service.setUrl( new URI("my mail url") );
Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
System.out.println("messages: " + inbox.getTotalCount());
CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
//Get all new appts?
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("YYYY-mm-dd");
Date startDate1 = formatter.parse("2013-11-25");
Date endDate1 = formatter.parse("2014-01-28 ");
EmailAddressCollection myRoomLists = service.getRoomLists();
for (EmailAddress item : myRoomLists)
{
System.out.println("Room Email========"+ item.toString());
NameResolutionCollection nameResolutions = service.resolveName(
item.getName(),
ResolveNameSearchLocation.DirectoryOnly,
true);
for (NameResolution nameResolution : nameResolutions)
{
ExpandGroupResults groupResults;
//System.out.println(nameResolution.getMailbox().getAddress());
try {
groupResults = service.expandGroup(nameResolution.getMailbox().getAddress());
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
groupResults=null;
System.out.println("NO INFO FOR "+nameResolution.getMailbox().getAddress());
}
if (groupResults!=null){
for (EmailAddress member : groupResults.getMembers())
{
if (member.getAddress().indexOf("rm.Cary")>-1){
System.out.println(member.getName() + " <" + member.getAddress() + ">");
FolderId folderid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(member.getAddress()));
try {
FindItemsResults<Appointment> aps = service.findAppointments(folderid, new CalendarView(startDate1,endDate1));
for (Item items : aps.getItems())
{
Appointment appt = (Appointment)items;
System.out.println("SUBJECT===== " + appt.getSubject());
System.out.println("Location======== " + appt.getLocation());
System.out.println("Start Time========" + appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Email Address========"+ appt.getOrganizer().getAddress());
System.out.println("Last Modified Time========"+appt.getLastModifiedTime());
System.out.println("Start time========"+appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Is recurring========"+appt.getIsRecurring());
System.out.println("Duration========"+appt.getDuration().toString());
System.out.println("Organizer========"+appt.getOrganizer());
System.out.println("Required Attendees========"+appt.getRequiredAttendees().getCount());
System.out.println("Optional Attendees========"+appt.getOptionalAttendees().getCount());
System.out.println("");
}
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
System.out.println(e.getMessage());
}
}
}
}
}
}
System.out.println("End");
Change it to:
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("yyyy-MM-dd");
I have a SimpleComboBox in GUI which contains some duplicate items also. Assume there are 3 items which is same as "domain". When i select second "domain" or third "domain", the selected item and selected index is always pointing to first occurance of "domain". How can i correct, so that the selected index/item is right one, instead of first occurance of item?
ComboBox with duplicate values:
When i select "domain" at fourth occurence it will always pointing the first occurance of "domain".
Output:
When i select the "192.168.1.30" at last occurenece, it will point the first occurance of "192.168.1.30".
Please any one help me.
private SimpleComboBox<String> domainName = new SimpleComboBox<String>();
domainName = WidgetUtil.getStringCombo("Domain Name", 12, true, domainNameList, null);
domainName.addSelectionChangedListener(getReportSelectionListener());
domainName.setForceSelection(true);
domainName.setTriggerAction(TriggerAction.ALL);
private Button New, add, remove;
New = WidgetUtil.getButton("New", "new", "");
New.addSelectionListener(buttonAction());
thirdLayoutContainer.add(New);
add = WidgetUtil.getButton("Add", "add", "");
add.addSelectionListener(buttonAction());
add.setStyleAttribute("paddingTop", "10px");
thirdLayoutContainer.add(add, formData);
remove = WidgetUtil.getButton("Remove", "remove", "");
remove.addSelectionListener(buttonAction());
public void componentSelected(ButtonEvent ce){
String domain_name = null;
if (ce.getComponent().getId().equals("remove")){
System.err.println("Clicked remove button...");
domain_name = domainName.getRawValue();
domainNameList.remove(domain_name);
systemDetailsMap.remove(domain_name);
systemDetailsMap.remove(domain_name + "_USER_NAME");
systemDetailsMap.remove(domain_name + "_HOST_NAME");
systemDetailsMap.remove(domain_name + "_PASSWORD");
domainName.removeAll();
domainName.add(domainNameList);
userName.clear();
hostName.clear();
password.clear();
System.err.println("After remove domain name list ---> " + domainNameList);
System.err.println("After remove map ---> " + systemDetailsMap);
} else if (ce.getComponent().getId().equals("add")) {
System.err.println("Clicked add button...");
domain_name = domainName.getRawValue();
domainNameList.add(domain_name);
systemDetailsMap.put(domain_name, domain_name);
systemDetailsMap.put(domain_name + "_HOST_NAME", hostName.getValue());
systemDetailsMap.put(domain_name + "_USER_NAME", userName.getValue());
systemDetailsMap.put(domain_name + "_PASSWORD", password.getValue());
// domainName.clear();
domainName.add(domainNameList);
// domainName.reset();
System.err.println("After add domain name list ---> " + domainNameList);
System.err.println("After add map ---> " + systemDetailsMap);
} else if (ce.getComponent().getId().equals("new")) {
System.err.println("Clicked new button...");
userName.clear();
hostName.clear();
password.clear();
domainName.removeAllListeners();
domainName.removeAll();
domainName.clear();
domainName.setEmptyText("Add a new domain");
userName.setEmptyText("Add a new username");
hostName.setEmptyText("Add a new hostname");
password.setEmptyText("Add a new password");
domainName.addSelectionChangedListener(getReportSelectionListener());
}
}
};
private SelectionChangedListener<SimpleComboValue<String>> getReportSelectionListener(){
SelectionChangedListener<SimpleComboValue<String>> ReportListener = new SelectionChangedListener<SimpleComboValue<String>>() {
#Override
public void selectionChanged(SelectionChangedEvent<SimpleComboValue<String>> se) {
SimpleComboValue<String> selectedValue = se.getSelectedItem();
String value = selectedValue.getValue();
System.err.println("Selected Value ---> " + selectedValue.getValue());
if (value != null && !value.equals("---New---") ){
userName.clear();
hostName.clear();
password.clear();
userName.setValue(systemDetailsMap.get(value + "_USER_NAME").toString());
hostName.setValue(systemDetailsMap.get(value + "_HOST_NAME").toString());
password.setValue(systemDetailsMap.get(value + "_PASSWORD").toString());
}
}
};
return ReportListener;
}
Please help me. Thanks in advance.
I am not using Ext-gwt just the standard ext-js, but I think I know what you need! You should define a display and value field.
Ext.create('Ext.form.ComboBox', {
store: xyz,
queryMode: 'local',
displayField: 'name',
valueField: 'id',
renderTo: Ext.getBody()
});
You just have to make sure, that the duplicated items are getting unique id. I think that if this is possible in ext-js it should also be possible in ext-gwt!
I have this code. And basically this returns the correct data without the town qualities. When I add the town qualities the method returns nothing, not even the orginal data that it has been and I dont know why. Can anyone see a problem?
protected void listRecords() {
mListForm.deleteAll(); // clear the form
try {
RecordStore rs = RecordStore.openRecordStore("Details", true);
RecordEnumeration re = rs.enumerateRecords(null, new RecordSorter(), false);
while (re.hasNextElement()) {
byte [] recordBuffer = re.nextRecord();
String record = new String(recordBuffer);
// extract the name and the age from the record
int endOfName = record.indexOf(";");
int endOfDesc = record.indexOf(";" , endOfName + 1);
int endOfTown = record.indexOf (";", endOfDesc + 1);
String name = record.substring(0, endOfName);
String desc = record.substring(endOfName + 1, endOfDesc);
String town = record.substring(endOfDesc +1, endOfTown);
mListForm.append(name + " aged: "+ desc + " " + town);
}
rs.closeRecordStore();
}
catch(Exception e){
mAlertConfirmDetailsSaved.setString("Couldn't read details");
System.err.println("Error accessing database");
}
mDisplay.setCurrent(mListForm);
}
Have you tried running it in the debugger? Is the exception happening? Are the three semicolons present in the record? Is there a limit on mDisplay's string size? When setCurrent is called, is the mListForm correct?
In other words, what have you done so far and where is it definitely right, and where does it become wrong?