How to put GUI in joptionpane? - user-interface

How to add GUI in this JOPTIONPANE?
private static final DecimalFormat df = new DecimalFormat("0.00");
public static final String[] Vehicle = { "Car","Motorcycle" };
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String userVehicleType;
String userInputHours;
String userInput;
int hoursPark;
int totalHours;
double userPayment=0;
double balance=0;
double addHours;
double totalAmount=0;
Integer ParkHours;
int newPayment;
JOptionPane.showMessageDialog( null, "Welcome to Wangsa Walk Ticket " );
do{
JFrame frame = new JFrame();
String[] choice = new String[2];
choice[0] = "Car";
choice[1] = "Motocycle";
int showOptionDialog = JOptionPane.showOptionDialog(frame.getContentPane(),"What Type of vehicle your using?","Title", 0,JOptionPane.QUESTION_MESSAGE,null,choice,null);
switch(showOptionDialog){
case 0:
userInputHours= JOptionPane.showInputDialog("how long do you park?");
hoursPark= Integer.parseInt(userInputHours);
if (hoursPark==2){
totalAmount=2;
userInput= JOptionPane.showInputDialog("Your fee is RM 2.00. "+
"Please insert your money (RM)");
userPayment= Integer.parseInt(userInput);
balance= userPayment - 2;
JOptionPane.showMessageDialog(null, " Your balance is RM " +df.format(balance));
break;
}
else if (hoursPark>2&&hoursPark!=24){
totalAmount=(hoursPark*1)+ 2;
userInput= JOptionPane.showInputDialog(" Your fee is RM "+df.format(totalAmount)+
". Please insert your money (RM)");
userPayment= Integer.parseInt(userInput);
balance= userPayment - totalAmount;
JOptionPane.showMessageDialog(null, " Your balance is RM " +df.format(balance));
break;
}
else if (hoursPark==24){
totalAmount=30;
userInput= JOptionPane.showInputDialog("Your parking fee is RM 30.00. "+
"Please insert your money (RM)");
userPayment= Integer.parseInt(userInput);
balance= userPayment-30;
JOptionPane.showMessageDialog(null, " Your balance is RM " +df.format(balance));
break;
}
case 1:
userInputHours= JOptionPane.showInputDialog("Input your parking hours");
hoursPark= Integer.parseInt(userInputHours);
if (hoursPark==1){
totalAmount=1;
userInput= JOptionPane.showInputDialog("Your fee is RM 1.00. "+
"Please insert your money (RM)");
userPayment= Integer.parseInt(userInput);
balance= userPayment - 1;
JOptionPane.showMessageDialog(null, " Your balance is RM " +df.format(balance));
break;
}
else if (hoursPark>=2){
addHours=(hoursPark-1)*0.5;
totalAmount= addHours+1;
userInput= JOptionPane.showInputDialog("Your fee is RM "+df.format(totalAmount)+
". Please insert your payment (RM)");
userPayment= Integer.parseInt(userInput);
balance= userPayment - totalAmount;
JOptionPane.showMessageDialog(null, " Your balance is RM " +df.format(balance));
break;
}
}
String Receipt = "Your parking fees is RM "+df.format(totalAmount)+". the amount you pay is RM "
+df.format(userPayment)+". Your balance is RM "+df.format(balance)+
".\n Thank you, Please come again.";
JOptionPane.showMessageDialog( null, Receipt );
String anotherpayment = JOptionPane.showInputDialog(null,
"Would you like to make another payment?\n1.Yes\n2.No",
JOptionPane.QUESTION_MESSAGE);
newPayment = Integer.parseInt(anotherpayment);
}while(newPayment==1);
System.exit(0);
}
}`

Related

ESP32 WifiClientSecure no response

I'm working on a project using a google script to publish images from an ESP32-CAM to google drive.
I keep getting the error "no response", no matter how long I set the wait peroid to. I tried using http and https(wificlient and wificlientsecure) but it doesn't work no matter what.
What could be the issue?
WiFiClientSecure clienthttps;
Serial.println("Connect to " + String(myDomain));
if (clienthttps.connect(myDomain, 443)) {
Serial.println("Connection successful");
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
delay(1000);
ESP.restart();
return;
}
char *input = (char *)fb->buf;
char output[base64_enc_len(3)];
String imageFile = "";
for (int i = 0; i < fb->len; i++) {
base64_encode(output, (input++), 3);
if (i % 3 == 0) imageFile += urlencode(String(output));
}
String Data = myFilename + mimeType + myImage;
esp_camera_fb_return(fb);
Serial.println("Send a captured image to Google Drive.");
Serial.println("POST " + myScript + " HTTP/1.1");
Serial.println("Host: " + String(myDomain));
Serial.println("Content-Length: " + String(Data.length() + imageFile.length()));
Serial.println("Content-Type: application/x-www-form-urlencoded");
Serial.println(Data);
Serial.println();
clienthttps.println("POST " + myScript + " HTTP/1.1");
clienthttps.println("Host: " + String(myDomain));
clienthttps.println("Content-Length: " + String(Data.length() + imageFile.length()));
clienthttps.println("Content-Type: application/x-www-form-urlencoded");
clienthttps.println();
clienthttps.print(Data);
int Index;
for (Index = 0; Index < imageFile.length(); Index = Index + 1000) {
clienthttps.print(imageFile.substring(Index, Index + 1000));
}
Serial.println("Waiting for response.");
long int StartTime = millis();
while (!clienthttps.available()) {
Serial.print(".");
delay(100);
if ((StartTime + waitingTime) < millis()) {
Serial.println();
Serial.println("No response.");
//If you have no response, maybe need a greater value of waitingTime
break;
}
}
Serial.println();
while (clienthttps.available()) {
Serial.print(char(clienthttps.read()));
}
} else {
Serial.println("Connected to " + String(myDomain) + " failed.");
}
clienthttps.stop();
Note that in the latest "github.com/espressif/arduino-esp32" (as at 17Jan23) the command
"WiFiClientSecure.println();" (your "clienthttps.println()") seems to corrupt the SSL-buffer somehow, and although the command returns after a bit, the SSL-connection fails at that point (this didn't happen in earlier versions of the software).
The solution which worked for me was to ensure I at very least sent "WiFiClientSecure.println(" ");" (ie. " \r\n") as this seems to work.
(This solution appears also often necessary if sending data over a GPRS connection because in that instance a ".println()" seems to be ingored!)

SQL command not ended properly

I try to make a code in java that accesses some tables from sql but when I try to run the code I get an error saying:
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly
ended
Here is the code that it's been giving me troubles:
history.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent actionEvent)
{
for(int i = 0; i < table.getRowCount(); i++)
for(int j = 0; j < table.getColumnCount(); j++)
table.setValueAt("", i, j);
int i=0;
try
{
rs = stmt.executeQuery("SELECT toyname, toyid, price "
+" FROM toys t, userbuy u "
+" WHERE u.toyid=t.toyid "
+" AND u.userid= "+user1.getUserid()+" )");
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try {
if(rs.next())
{
table.setValueAt(rs.getString(1), i, 0);
table.setValueAt(rs.getString(2), i, 1);
table.setValueAt(rs.getString(3), i, 2);
i++;
while(rs.next())
{
table.setValueAt(rs.getString(1), i, 0);
table.setValueAt(rs.getString(2), i, 1);
table.setValueAt(rs.getString(3), i, 2);
i++;
}
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
});
Those are my two tables:
CREATE TABLE users
(
userid NUMBER(2) NOT NULL CONSTRAINT users_pk PRIMARY KEY,
username VARCHAR(17) NOT NULL,
password VARCHAR(20),
email VARCHAR(20),
adress VARCHAR(20),
CNP VARCHAR(14)
);
CREATE TABLE userbuy
(
userid NUMBER(2),
buyid NUMBER(2) ,
toyid NUMBER(2),
CONSTRAINT userid_fk FOREIGN KEY (userid) REFERENCES users(userid),
CONSTRAINT buyid_fk FOREIGN KEY (buyid) REFERENCES buy(buyid)
);
Does anyone know what is wrong here?
your sql query is wrong.correct sql
rs = stmt.executeQuery("SELECT toyname, toyid, price "
+" FROM toys t, userbuy u " +" WHERE u.toyid=t.toyid "
+" AND u.userid= "+user1.getUserid());
It is advisable to use PreparedStatement to get rid of sql injection
Example of PreparedStatement
correct sql query :
rs = stmt.executeQuery("SELECT t.toyname, t.toyid, t.price "
+" FROM toys t, userbuy u "+" WHERE u.toyid=t.toyid "
+" AND u.userid= "+user1.getUserid());
remove that " )", may be you forgot it :)

Java IO not displaying file data

Okay, I guess I'm stuck here. Can't get the values from the file to show in JOptionPane's message dialog box where it's enclosed within a while loop.
Right now I don't know which method of Input/Output stream to use to display all the data on this file which I believed to be serialized as UTF8??
Please tell me what to do and what things I missed since I'm new to java.io classes.
Also, the file StudentData.feu was just given to me. It's not that I don't want to research on my own because I already did, I'm just stuck. I read the Javadoc but I'm clueless right now.
import java.io.*;
import javax.swing.JOptionPane;
public class MyProj {
public void showMenu() {
String choice = JOptionPane.showInputDialog
(null, "Please enter a number: " + "\n[1] All Students" + "\n[2] BSCS Students" + "\n[3] BSIT Students"
+ "\n[4] BSA Students" + "\n[5] First Year Students" + "\n[6] Second Year Students" + "\n[7] Third Year Students"
+ "\n[8] Passed Students" + "\n[9] Failed Students" + "\n[0] Exit");
int choiceConvertedString = Integer.parseInt(choice);
switch(choiceConvertedString){
case 0:
JOptionPane.showMessageDialog(null, "Program closed!");
System.exit(1);
break;
}
}
DataInputStream myInputStream;
OutputStream myOutputStream;
int endOfFile = -1;
double grades;
int studentNo;
int counter;
String studentName;
String studentCourse;
public void readFile()
{
try
{
myInputStream = new DataInputStream
(new FileInputStream("C:\\Users\\Jordan's Pc\\Documents\\NetBeansProjects\\MyProj\\StudentData.feu"));
try{
while((counter=myInputStream.read()) != endOfFile)
{
studentName = myInputStream.readUTF();
studentCourse = myInputStream.readUTF();
grades = myInputStream.readDouble();
JOptionPane.showMessageDialog
(null, "StdNo: " + studentNo + "\n"
+ "Student Name: " + studentName + "\n"
+ "Student Course: " + studentCourse + "\n"
+ "Grades: " + grades);
}
}
catch(FileNotFoundException fnf){
JOptionPane.showMessageDialog(null, "File Not Found");
}
}/* end of try */
catch(EOFException ex)
{
JOptionPane.showMessageDialog(null, "Processing Complete");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "An error occured");
}
}
}
while((counter=myInputStream.read()) != endOfFile)
The problem is probably here. You're reading a byte and then throwing it away. It isn't likely that the file contains extra bytes like this that are intended to be thrown away. The correct loop would go like this:
try
{
for (;;)
{
// .... readUTF() etc
}
}
catch (EOFException exc)
{
// You've read to end of file.
}
// catch IOException etc.

C#. Search array of strings for longest element

I want to know how I can get out everyone of the the longest persons if there are several with the same length?
If only one person is the longest, then it works fine and the longest person with it´s name will show in MessageBox. But if there are more than one who are the longest, this code will not work...
public partial class Form1 : Form
{
int[] längdArray = new int[5];
string[] namnArray = new string[5];
int namn = 0;
int längd = 0;
public Form1()
{
InitializeComponent();
}
private void btnVisa_Click(object sender, EventArgs e)
{
int längst = 0;
int längdvärdet = 0;
int längdindex = 0;
string name = textBox1.Text;
namnArray[namn] = name;
namn = namn + 1;
textBox1.Clear();
int centimeter = int.Parse(textBox2.Text);
längdArray[längd] = centimeter;
längd++;
textBox2.Clear();
listBox1.Items.Add(name + " " + centimeter + " centimeter ");
if (längd == 5)
{
btnVisa.Enabled = false;
foreach (int antalLängder in längdArray)
{
if (antalLängder > längst)
{
längst = antalLängder;
längdvärdet = längdindex;
}
längdindex++;
}
string test = namnArray[längdvärdet]
MessageBox.Show(" Längsta person är " + test + " som är " + längst + " centimeter lång ");
}
Define behavior you want your app to present when there is more than one person. Should all display, or any one, or other? Try to use object constructions, it's easier to operate on them. C# is an object-oriented language. Put name and length in one structure then use LINQ.

Salesforce error: Too many code statements 200001

I have created an opportunity trigger to send out an email to two separate email address field whenever the stage is Closed Won depending on the Campaign Type. It works perfectly fine but recently when I tried updating a list of 200 opportunity records it gave me an error saying "Too many code statements 200001".
My code is as follows:
trigger SendEmail on Opportunity (after update)
{
Set<Id> accountSet = new Set<Id>();
Set<Id> marketSet = new Set<Id>();
for (Opportunity o : Trigger.new) {
accountSet.add(o.Accountid);
marketSet.add(o.Campaignid);
}
Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Name, Phone, PersonMobilePhone, PersonEmail from Account where id in :accountSet] );
map<Id, Campaign> marketMap = new Map<Id, Campaign>([SELECT Name, Parent_Market__c from Campaign where id in :marketSet]);
for (Opportunity o : Trigger.new) {
if(o.Campaign_Type__c != Null && o.StageName != Null){
for (Integer i = 0; i < Trigger.old.size(); i++) {
Opportunity old = Trigger.old[i];
Opportunity nw = Trigger.new[i];
Account theAccount = accountMap.get(o.AccountId);
Campaign Market = marketMap.get(o.CampaignId);
String userName = UserInfo.getUserName();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> toAddresses = new List<String>();
List<String> ccAddresses = new List<String>();
ccAddresses.add('test#test.com');
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
mail.setSenderDisplayName('Campaign Information');
mail.setSubject(+ theAccount.Name + ' is Closed Won');
mail.setReplyTo('noreply#salesforce.com');
//Body of the Email
mail.setHtmlBody(
'<font face="Times" size="3">'+
'<table width="100%">'+
'<tr width="0%">'+
'<td rowspan="0">'+
'</td>'+
'<td>'+
'<h2>Account is closed won notification</h2>'+
'</td>'+
'</tr>'+
'</table>'+
'<br/>'+
'<b>Stage:</b> ' + o.StageName + '<br/>' + '<br/>' +
'<b>Opportunity Number:</b> ' + o.Name + '<br/>' +
'<b>Amount Paid:</b> $' + o.Amount + '<br/>' + '<br/>' +
'<b>Account Name:</b> ' + theAccount.Name + '<br/>' +
'<b>Phone:</b> ' + theAccount.Phone + '<br/>' +
'<b>Mobile:</b> ' + theAccount.PersonMobilePhone + '<br/>'+
'<b>Email:</b> ' + theAccount.PersonEmail + '<br/>'+
);
// Send Email if it isCampaign1 and Closed Won
if((nw.StageName !=old.StageName) || (nw.Campaign_Type__c !=old.Campaign_Type__c)){
if(o.Campaign_Type__c.equals('Campaign1')){
if(o.StageName.equals('Closed Won') ){
toAddresses.add(o.Email__c);
try {
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
catch(Exception ex) { }
}
}
}
// Send Email if it is Campaign2 and Closed Won
if((nw.StageName !=old.StageName) || (nw.Campaign_Type__c !=old.Campaign_Type__c)){
if(o.Campaign_Type__c.equals('Campaign2')){
if(o.StageName.equals('Closed Won')){
toAddresses.add(o.Email2__c);
toAddresses.add(o.Email1__c);
try {
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
catch(Exception ex) { }
}
}
}
}
}
}
}
Any help will be appreciated.
Thanks
Why you sand for each opportunity Trigger.new.size() emails?
your code degree is n*n.
Change
for (Opportunity o : Trigger.new) {
if(o.Campaign_Type__c != Null && o.StageName != Null){
for (Integer i = 0; i < Trigger.old.size(); i++) {
Opportunity old = Trigger.old[i];
Opportunity nw = Trigger.new[i];
To something like
for (Opportunity o : Trigger.new) {
if(o.Campaign_Type__c != Null && o.StageName != Null){
Opportunity old = Trigger.old.get(o.Id);
Opportunity nw = o;
if(((nw.StageName !=old.StageName) || (nw.Campaign_Type__c !=old.Campaign_Type__c)) && (nw.StageName.equals('Closed Won')&&((nw.Campaign_Type__c.equals('Campaign1')||(nw.Campaign_Type__c.equals('Campaign2')){
.......................

Resources