Convert sql_Varient to integers

i want to convert the Server_Name value from actual server name to 1 or 2 based on output, which i am already able to do in the code below,now i want to convert the data type of column "Server_Name" to integer after updating the values to 1 or 2please assist.alter procedure ACtiveClusterNodeAOHC
AS
IF OBJECT_ID('tempdb..#tempvarienttype') IS NOT NULL
DROP TABLE ACtiveClusterNodeAOHC
create table #tempvarienttype(
Server_Name sql_variant
insert INTO #tempvarienttype
select ComputerName=SERVERPROPERTY('ComputerNamePhysicalNetBIOS')
update #tempvarienttype
set Server_Name=case
when server_Name='DBAOHC01A' then 1
when Server_Name='DBAOHC02A' then 2
end
select * from #tempvarienttype
exec ACtiveClusterNodeAOHC
k

create one more column in your temporary table with integer datatype and update that column based on the value of servername column.
You can select that column instead of select * from
You wont have to convert then.
create table #tempvarienttype(
Server_Name sql_variant,
serverid int
insert INTO #tempvarienttype
select ComputerName=SERVERPROPERTY('ComputerNamePhysicalNetBIOS')
update #tempvarienttype
set serverid =case
when server_Name='DBAOHC01A' then 1
when Server_Name='DBAOHC02A' then 2
end
select serverid from #tempvarienttype
alternatively you can use this approach as well
declare @var sql_variant
declare @value int
set @var = SERVERPROPERTY('ComputerNamePhysicalNetBIOS')
if @var = 'DBAOHC01A'
set @value = 1
else if @var = 'DBAOHC02A'
set @value =2
select @value
Regards, Ashwin Menon My Blog - http:\\sqllearnings.com

Similar Messages

  • "converting strings into integers in a array"

    I'm really left scrating my head trying to figure this out.
    What I have right now is this
    public class NameManager
         private names[] collection; // collection of names
         private int count;
         public NameManager() // Creating an array which for now is empty
              collection = new names[1000];     
              count = 0;
              String [] collection = {"boston", "Springfield", "New Haven",
                        "New York", "Albany"};
    Its a namemanager for my road trip project which will be sort of like mapquest. What it does, or it's supposed to do is I have a array of names of cities, that represented as strings, in a array called, collection. What my proffeser wants me to do is turn the strings into integers, so in this elements in the array can be referenced .
    It's probably so easy that I'll want to kick myself when I find out how to do it , but for whatever reason , all the information have found on the internet seems to go right over
    If any body can give some idea of how to turn the string you see above into a set of intege s I would be so grateful.

    turn the string into the index in the array
    i.e.
    boston => 0
    springfield => 1
    New Haven => 2
    New York => 3
    Albany => 4I should've mention this before but I need the names to go along with the numbers.
    This is the directions from my proffesser, I know it's not the easiest to understand
    but hopefully It will give you a better idea of what I'm talking about.
    A name manager. This object turns strings into numbers. Every time a name is added to the name manager, it is checked to see if it has already been seen. If so, return the number previously assigned to the name. If not, increment the "number of known names" and return this number as well as remember the string for future reference. You can assume that there will be no more than 1000 names in the manager. Each name is a string.
    A city. A city is a simple object: the city has a name and a number (at present).
    I got most of this part done it just strings integers part that's getting me.

  • Converting doubles to integers?

    HI
    i have a slight problem with converting varibles of type to double to an integer. (i just want to output the value as a whole number.)
    Any ideas of how this can be done?
    thanks.

    Just be aware that, unless your program takes steps to prevent it, a double value can have much larger magnitude than an int, so it's possible that the double won't fit into an int, and you'll get the wrong answer back.
    public class DoubleInt {
        public static void main(String[] args) throws Exception {
            double dd = ((double)Integer.MAX_VALUE) * 2;
            System.out.println(dd);
            System.out.println((int)dd);
    :; java -cp classes DoubleInt
    4.294967294E9
    2147483647

  • Why dose Numbers 3.0 while opening csv-Files converts Dates into Integers?

    I want to open a csv-file with a date.
    The Date is in german notation.
    28.10.2013 the value in the cell is 40113.
    This problem occures only in Numbers 3.0
    if I open the same file with Numbers 2.3 it is ok.
    How can I change it.
    The Systempreferences of the date and time handling is ok.

    2. Even though I have set the data type to text within EPMA, once I deploy the application and check it with the EAS console, the data type is NUMERIC - NOT TEXT anymore. This blows my mind. I don't know why this happens.
    Its common ...As enter a text wavlue which has been entered in planning as text in number...Their are certain table's in planning which play role while fetching such values....
    Cheers!
    Sh!va

  • Converting strings to integers

    Hi im trying to do the work but i am having problems with part of my code. my code looks like this...
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TextFieldExample extends Applet implements ActionListener {
    TextField textInput;
    String text = "";
    public void init() {
    textInput = new TextField (20);
    add(textInput);
    textInput.addActionListener(this);
    public void actionPerformed(ActionEvent e) {
    text = textInput.getText();
    repaint();
         int x = Integer.valueOf(text).integerValue();
         public void paint(Graphics g) {
    g.drawString("You wrote " + text,20,100);
    Im trying to get the string coverted to an integer so that i can do calculations with the number a user enters. This is the part that is bringing up errors. i have tried to fix it but with no luck. Can anyone see where i am going wrong?
    int x = Integer.valueOf(text).integerValue();

    thank for the help, but it seems to have created another problem. It is an applet that i am trying to make, if this makes any difference. I have tried to alter my code and it does compile correctly, but there is a problem when I try to view it in the applet. The html i have is:
    <html>
    <head>
    <title>TextFieldExample Web Page</title>
    </head>
    <body>
    <applet code="TextFieldExample.class" width=300 height=250>
    </applet>
    </body>
    </html>

  • Convert unsigned integer to IEEE float

    Hello,
    Is there a typecast function in CVI that would convert 2 unsigned integers to IEEE loat?
    eg:
    1st value MSB:  50588
    2nd value LSB: 16425
    Actual reading:  -5000.02
    Thanks.
    TN
    Solved!
    Go to Solution.

    You just need to do some pointer manipulation to build your float.
    But you need to be aware of the size of the data types you're using.  Based on your example values, it looks like you are using the IEEE single precision format, which is 4 bytes.  In 32 bit operating systems, the unsigned int is also 4 bytes.  So you can't combine two unsigned int into an IEEE single without casting them as short ints, which are 2 bytes each.  You would need to check if the value in your unsigned int will fit in an unsigned short before casting it.
    You can play with the sizeof() function to see the data type sizes on whatever platform you're using.
    Here are a few lines of code the combine your example values to produce the expected result.
    #include <ansi_c.h>
    #include <utility.h>
    main()
     // allocate room for myFloat (IEEE single precision)
     float myFloat;
     // create pointers to the two words in the IEEE single precision format
     unsigned short *pMSW, *pLSW;
     // move the pointers to the first and second word in your float
     pLSW = (unsigned short *) &myFloat;
     pMSW = pLSW +1;
     // initialize the word values
     *pMSW = 50588;
     *pLSW = 16425;
     // print everything out
     printf("MSW: %d\tLSW: %d\tIEEE Single: %f\n", *pMSW, *pLSW, myFloat);
     // wait for a response
     printf("Press any key to continue...\n");
     GetKey();
    Here's a link to a discussion on going the other way, which has a sample program and links to more IEEE format info.
    http://forums.ni.com/t5/LabWindows-CVI/How-to-convert-a-number-to-32-bit-binary-or-Hex/m-p/977159#M4...

  • How can I set specific bits in a 16-bit integer?

    Hello everyone,
    as the title says I need to modify or rather to set a specific bit in a string which then is sent to a motor. I need to be sure that my command is correct as I am experiencing troubles with that motor and need to identify if its source.
    First of all my strings have to be in the Little Endian order. Then the structure of the string should be the following:
    Change Velocity command ‘V’xxCR 056h + one unsigned short (16-bit) integer + 0Dh (Note: Uppercase ‘V’)
    Note: The lower 15 bits (Bit 14 through 0) contain the velocity value. The high-order bit (Bit 15) is used to indicate the microstep-to-step resolution: 0 = 10, 1 = 50 uSteps/step.
    Until now, I used Flatten To String to convert 32 bit integers into bytes of the correct order. I thought I could use the Join Numbers function, but that only works for at least 8 bit numbers and there is no "1 bit number". I searched for an option to build a a string and set the bits via a Boolean Cluster, but I did not really understand how to transfer this to my problem.
    How can I build up the correct 16-bit integer (e.g. set the velocity to "10000" with a resolution of 50 µSteps/step)
    I would like to add the "V" and the CR via Concatenate Strings to the 16-bit integer, but other possibilites are also welcome.
    I have seens the examples for bit manipulation in C-code, but I wish to do this with LabView as I am not familiar with C,matlab and so on.
    Thank you very much for your help!
    Solved!
    Go to Solution.

    You really need to learn Boolean logic and how to shift bits around.
    AND is really good for masking out bits (forcing them to 0) and OR is really good for adding bit values.  Then Logical Shift is used to get the bits in the right places before doing the AND and OR.
    NOTE: Rate is an enum with 10 being a value of 0 and 50 being 1.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Bit Packing.png ‏15 KB

  • It's won't work WHY!!!

    It compiles but I can't convert Strings to Integers
    Heres the code the classes involved work as I've tested them.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import StudentMarks;
    class StudentGrades extends JFrame implements ActionListener
         private JTextField field1;
         private JTextField field2;
         private JTextField field3;
         private JTextField field4;
         private JLabel word1;
         private JLabel word2;
         private JLabel word3;
         private JLabel word4;
         private JPanel main;
         private JPanel panel;
         private JPanel button;
         private JPanel output;
         private JButton EnterStudent;
         private JButton DisplayGrade;
         private JButton ClearFields;
         private JButton Quit;
         private JTextField displayField;
         private StudentMarks sml;
         public StudentGrades()
              setTitle("Student Grades");     //Title
              setSize (500,600);     //Size
              addWindowListener (new WindowAdapter()
              { public void windowClosing(WindowEvent e)
                   {System.exit(0);  //halt the program
                   //Word and Fields
                   word1= new JLabel ("Enter Student ID");
                   word1.setHorizontalAlignment(JLabel.RIGHT);
                   field1=new JTextField(" ");
                   field1.addActionListener(this);
                   word2 = new JLabel ("Enter Student Name");
                   word2.setHorizontalAlignment(JLabel.RIGHT);
                   field2= new JTextField(" ");
                   field2.addActionListener(this);
                   word3 = new JLabel ("Enter Mark 1");
                   word3.setHorizontalAlignment(JLabel.RIGHT);
                   field3 = new JTextField (" ");
                   field3.addActionListener(this);
                   word4= new JLabel ("Enter Mark 2");
                   word4.setHorizontalAlignment(JLabel.RIGHT);
                   field4 = new JTextField(" ");
                   field4.addActionListener(this);
                   //Add to panel the words and fields
                   panel= new JPanel(new GridLayout (4,2,5,5));
                   panel.add(word1);
                   panel.add(field1);
                   panel.add(word2);
                   panel.add(field2);
                   panel.add(word3);
                   panel.add(field3);
                   panel.add(word4);
                   panel.add(field4);
                   button = new JPanel();
                   button.setBackground(Color.white);
                   EnterStudent = new JButton("Enter Student");
                   DisplayGrade = new JButton("DisplayGrade");
                   ClearFields = new JButton("Clear Fields");
                   Quit = new JButton("Quit");
                   button.add(EnterStudent);
                   button.add(DisplayGrade);
                   button.add(ClearFields);
                   button.add(Quit);
                   EnterStudent.addActionListener(this);
                   DisplayGrade.addActionListener(this);
                   ClearFields.addActionListener(this);
                   Quit.addActionListener(this);
                   //The display field
                   displayField = new JTextField(" ");
                   displayField.setEditable(false);
                   displayField.setHorizontalAlignment(JTextField.CENTER);
                   output = new JPanel();
                   output.add(displayField,BorderLayout.SOUTH);
              //addWindowListener();
              //infield.addActionListener(this)     
              main = new JPanel(new GridLayout(6,4,5,5));
              main.add(panel,BorderLayout.NORTH);
              main.add(button,BorderLayout.CENTER);
              main.add(displayField,BorderLayout.SOUTH);
              Container contentPane = getContentPane();
              contentPane.add(main);
              public void actionPerformed (ActionEvent evt)
              Object source = evt.getSource();
                        if(source == Quit) System.exit(0);
                        else if (source == EnterStudent)
                                  //StudentMarks butt1;
                                  //String x = field1.getText();
                                  //String name = field2.getText();
                                  //String mak1 = field3.getText();
                                  //String mak2 = field4.getText();
                                  //Integer id = new Integer(field1.getText());
                                  //Integer mark1 = new Integer(field3.getText());
                                  //Integer mark2 = new Integer(field4.getText());
                                  //sml = new StudentMarks(1,"Baza",25,45);
                                  sml = new StudentMarks(Integer.parseInt(field1.getText()),field2.getText(),Integer.parseInt(field3.getText()),Integer.parseInt(field4.getText()));
                                  displayField.setText("Student " + sml.getID() + " marks have been entered");
                             else if (source == DisplayGrade)
                             //{sml = new StudentMarks(Integer.parseInt(field1.getText()),field2.getText(),Integer.parseInt(field3.getText()),Integer.parseInt(field4.getText()));
                             displayField.setText(sml + "\n" + sml.getGrade());
                             //StudentMarks butt2;
                             //String x = field1.getText();
                             //String name = field2.getText();
                             //String mak1 = field3.getText();
                             //String mak2 = field4.getText();
                             //int id, mark1, mark2;
                             //id = Integer.parseInt(x);
                             //mark1 = Integer.parseInt(mak1);
                             //mark2 = Integer.parseInt(mak2);
                             //butt2 = new StudentMarks(id,name,mark1,mark2);
                             //displayField.setText(butt2.getGrade());
    else if (source == ClearFields)
                                  field1.setText(" ");
                                  field2.setText(" ");
                                  field3.setText(" ");
                                  field4.setText(" ");
                                  displayField.setText(" ");
         public class StudentGradesTest
         {     public static void main (String[] args)
              {     StudentGrades s = new StudentGrades();
                   s.show();
         }

    Try getText().trim()
    This will remove spaces from the text & avoid NumberFormatException being thrown
    Warm regards
    Aswin Asokan

  • Important question about my code

    Okay so here's the deal, I have been working on creating the 6/49 lottery game and so far everything works fine, however I have one problem with how the program runs.
    The instructions are as follows: The program generates 6 random numbers from 1 to 49, then it asks the user to input 6 numbers, and if they guess the generated random numbers they win a prize.
    This is where the problem's at, the program generates 6 random numbers, let's say for this topic's sake : 1,2,3,4,5,6. Now if the user inputs let's say 12,34,56,6,9,11 the program should say 1/6 correct since the user guessed the number 6. However since the user entered 6 as the 4th number, it says that the user has gotten 0/6 correct!
    Tell me what I'm doing wrong here please... here's my code.
    import java.util.Random;
    import javax.swing.*;
    import java.util.*;
    public class GameBeta
         public static void main (String args[])     
              mGame();
         }//end main
    public static void mGame()
              Random randomNumbers = new Random();
                String sInput,
                          win = "";
              int iNumber=0,
                    match=0,
              randNumber,
              prize=0;
    int array [] = new int [50];
         for (int i=1; i<=6; i++)
                   randNumber = 1 + randomNumbers.nextInt(49);
                   array [randNumber] = randNumber;
                             try
                   //get the numbers from the user
                   sInput=JOptionPane.showInputDialog ("Enter winning number");
                   //convert strings to integers
                  iNumber=Integer.parseInt(sInput);
                   catch (NumberFormatException nfe)
                        System.out.println ("Invalid input please try again");
                        System.exit (0);
                  }//end catch
                   if (match==3)
                        prize = 10;
                        if (match==4)
                             prize = 1000;
                             if (match==5)
                                  prize = 10000;
                                  if (match==6)
                                       prize = 1000000;
              for ( int counter = 1; counter < array.length; counter ++)
                      if (counter % 7 == 0)
                                System.out.printf("%s\n", array [counter]);
                     else
                            System.out.printf("%s ",  array [counter]); 
         System.out.println ("You have got: " + match + " correct answers!");
    }//end class Assignment1

    Is there a specific reason your using a static method to run your app?
    I modified your code slightly so that it will run as a app and you shouldn't get the cannot access non-static method from a static context...
        public static void main(String args[])
            GameBeta gm = new GameBeta();  // create a new instance of your game
            gm.mGame();  //  run the game
            gm = null;  // release the object to gc
            System.exit(0);  //  exit gracefully
        }//end main
        public void mGame() {
        //  the rest of your code....I hope it gives you some insight..
    J

  • LAST QUESTION ABOUT MY CODE (promise)

    Here is my final code for the 6/49 lottery game (it's a more simplified version so don't mind that there is no Bonus Number) sorry for the long code...
    I'll just post my question here for those who don't want to go through all of this.
    I want to throw an exception and let it catch it after the first input box appears. So let's say I entered text or a null value in the first input box then it would loop back to the beginning of the program and output a message saying "You entered a wrong value!"
    But in the code that I have, even if I enter text or just press enter without inputting anything, it just moves on to the next input box, until on the 6th input box it says "invalid value".
    So how would I proceed in doing this?
    THANKS!
    import java.util.Random;
    import javax.swing.*;
    public class Game
         public static void main (String args[])     
              mGame();
         }//end main
         public static void mGame()
              JOptionPane.showMessageDialog(null, "Ali Uz\n110231263", "About", JOptionPane.PLAIN_MESSAGE);
              Random randomNumbers = new Random();
              String sInput,
                      win = "";
              int iNumber1=0,
                   iNumber2=0,
                   iNumber3=0,
                   iNumber4=0,
                   iNumber5=0,
                   iNumber6=0,
                   match=0,
                   randNumber,
                   prize=0;
             int array [] = new int [50];
              try
                        //get the numbers from the user
                        sInput=JOptionPane.showInputDialog ("Enter winning number 1.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 2.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 3.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 4.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 5.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 6.");
                        //convert strings to integers
                        iNumber1=Integer.parseInt(sInput);
                        iNumber2=Integer.parseInt(sInput);
                        iNumber3=Integer.parseInt(sInput);
                        iNumber4=Integer.parseInt(sInput);
                        iNumber5=Integer.parseInt(sInput);
                        iNumber6=Integer.parseInt(sInput);
             }//end try
              catch (Exception e)
                        System.out.println ("Invalid input please try again");
                        System.exit (0);
              }//end catch
              for (int i=1; i<=6; i++)
                   randNumber = 1 + randomNumbers.nextInt(49);
                   array [randNumber] = randNumber;
                   if (randNumber==iNumber1)
                             match++;
                   else
                             if (randNumber==iNumber2)
                                       match++;
                             else
                                       if (randNumber==iNumber3)
                                                 match++;
                                       else
                                                 if (randNumber==iNumber4)
                                                           match++;
                                                 else
                                                           if (randNumber==iNumber5)
                                                                     match++;
                                                           else
                                                                     if (randNumber==iNumber6)
                                                                               match++;
                   if (match==3)
                        prize = 10;
                        if (match==4)
                             prize = 1000;
                             if (match==5)
                                  prize = 10000;
                                  if (match==6)
                                       prize = 1000000;
              for ( int counter = 1; counter < array.length; counter ++)
                      if (counter % 7 == 0)
                                System.out.printf("%s\n", array [counter]);
                     else
                            System.out.printf("%s ",  array [counter]); 
                   if (match >= 3)
                             System.out.println ("You have gotten " + match + "/6 correct\nYou have won $" + prize);
                   else
                             System.out.println ("You have gotten " + match + "/6 correct\nSorry you have lost! Please try again");     
    }//end class Assignment1

    Your problem here as that the exception you want to
    throw takes place here
    iNumber1=Integer.parseInt(sInput);
    public void showMessage(int number){
    try{
    sInput=JOptionPane.showInputDialog ("Enter
    nter winning number " + number);
    iNumber1=Integer.parseInt(sInput);
    }catch(Exception e){
    System.out.println ("Invalid input please try
    e try again");
    System.exit (0);
    }then call this method from inside a for loop:
    for(int i=1; i <=6; i++){
    showMessage(i);
    }Hope that helps you a littleOnly catch NumberFormatException there, though.

  • 32 bit integer to byte

    Hi All,
    i convert 32 bit integers to bytes , and this works fine with a small problem.
    when i print the bytes i get 0 for 00 and A for 0A and so on, i use the method below to put the "0" , but it isn't the best way to handle with bytes
    String  tChar;
    String tOut;
    for(int id = 0; id < mSendByteArray.length; id++){
    tChar=Integer.toHexString(mSendByteArray[id] & 0x0FF).toUpperCase();
    tOut = (tChar.length() < 2 ? "0" + tChar : tChar).toUpperCase();
    System.out.println(tOut);
    }can anybody please help
    best regards

    Create an int from the bytes and format that as a hex string, adding on as many extra zeros as necessary?
    You could always build up a char[8] and fill it by bit-shifting and masking your int to fill it with 0-F values. This is essentially all Integer.toHexString does and it's not so special that you couldn't just reimplement it in a utility method yourself.
    Extending NumberFormat to do this would be a tidy approach but perhaps not "optimal".
    Hope this helps.

  • How to use java to send emails

    Hi,
    I am having problems trying to send an email using java. No idea what is going on because it looks fine. Can anyone give any insight?
    Cheers
    Robert
    import java.awt.event.*;
    import java.awt.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    * JEmail.java
    * @author Robert Venning 18/09/2005
    * @version 1.0
    public class JEmail extends JFrame implements ActionListener{
         private static final long serialVersionUID = 1L;
         final int SMTP_PORT = 25;
         JLabel fromLabel = new JLabel("From: ");
         JLabel toLabel = new JLabel("To: ");
         JLabel ccLabel = new JLabel("CC: ");
         JLabel subjectLabel = new JLabel("Subject: ");
         JTextField from = new JTextField(20);
         JTextField to = new JTextField(20);
         JTextField cc = new JTextField(20);
         JTextField subject = new JTextField(20);
         JTextArea message = new JTextArea(10,30);
         JScrollPane scrollPane = new JScrollPane(message);
         JButton send = new JButton("Send");
         public JEmail(){
              super("Email Program");
              JPanel mainPane = new JPanel();
              JPanel pane = new JPanel();
              JPanel fromPane = new JPanel();
              JPanel toPane = new JPanel();
              JPanel ccPane = new JPanel();
              JPanel subjectPane = new JPanel();
              mainPane.setLayout(new FlowLayout());
              pane.setLayout(new GridLayout(4,1));
              fromPane.add(fromLabel);
              fromPane.add(from);
              toPane.add(toLabel);
              toPane.add(to);
              ccPane.add(ccLabel);
              ccPane.add(cc);
              subjectPane.add(subjectLabel);
              subjectPane.add(subject);
              pane.add(fromPane);
              pane.add(toPane);
              pane.add(ccPane);
              pane.add(subjectPane);
              mainPane.add(pane);
              mainPane.add(scrollPane);
              mainPane.add(send);
              setContentPane(mainPane);
              send.addActionListener(this);
         public static void main(String[] args) {
              JFrame aFrame = new JEmail();
              aFrame.setSize(350, 400);
              aFrame.setVisible(true);
         public void actionPerformed(ActionEvent event){
              try{
                   PrintWriter writer = new PrintWriter(new FileWriter("log.txt"));
                   String input, output;
                   Socket s = new Socket("mail.tpg.com.au", SMTP_PORT);
                   BufferedReader in = new BufferedReader
                        (new InputStreamReader(s.getInputStream()));
                   BufferedWriter out = new BufferedWriter
              (new OutputStreamWriter(s.getOutputStream()));
                   output = "HELO theWorld" + "\n";
                   out.write(output);
                   out.flush();
                   System.out.print(output);
                   writer.println(output);
                   input = in.readLine();
                   System.out.println(input);
         //          writer.println(input);
                   output = "MAIL FROM: <" + from.getText() + ">" + "\n";
                   out.write(output);
                   out.flush();
                   System.out.print(output);
                   writer.println(output);
                   input = in.readLine();
                   System.out.println(input);
         //          writer.println(input);
                   output = "RCPT TO: <" + to.getText() + ">" + "\n";
                   out.write(output);
                   out.flush();
                   System.out.print(output);
                   writer.println(output);
                   input = in.readLine();
                   System.out.println(input);
              //     writer.println(input);
                   output = "DATA" + "\n";
                   out.write(output);
                   out.flush();
                   System.out.print(output);
                   writer.println(output);
                   input = in.readLine();
                   System.out.println(input);
              //     writer.println(input);
                   output = "Subject: " + subject.getText() + "\n";
                   out.write(output);
                   out.flush();
              System.out.print(output);
              writer.println(output);
              output = "From: Robert Venning <" + from.getText() + ">" + "\n";
                   out.write(output);
                   out.flush();
              System.out.print(output);
              writer.println(output);
                   // message body
              output = message.getText() + "\n";
                   out.write(output);
                   out.flush();
                   System.out.print(output);
                   writer.println(output);
                   output = ".\n";
                   out.write(output);
                   out.flush();
                   System.out.println(output);
                   writer.println(output);
                   output = "QUIT" + "\n";
                   out.write(output);
                   out.flush();
                   System.out.print(output);
                   writer.println(output);
                   input = in.readLine();
                   System.out.println(input);
         //          writer.println(input);
                   writer.close();
                   s.close();
              catch(Exception exception){
                   exception.printStackTrace();
    }

    Hi, floppit. For sending emails, I used the JavaMail API. Here is some code I wrote where I used JavaMail. The most relevant lines are in bold.
    /*   File:  ListenNotifier.java
    * Author:  Fabricio Machado
    *          [email protected]
    * This utility is based on the "Listen.java" tool from the Tiny OS
    * java tools package, in /tinyos-1.x/tools/java/net/tinyos/tools/.
    * The original application has been extended to convert raw packet data into
    * a more meaningful representation of actual photo sensor readings in
    * lux.
    * The application checks the readings against a user-defined
    * threshold, and sends email notifications when readings break the
    * threshold, and also when readings dip back below the threshold.
    * Currently, the code is only fit to handle packets from the Tiny OS
    * nesc application OscilloscopeRF.nc.  The code gets the packet data
    * by connecting via TCP to a Tiny OS java tool called "Serial Forwarder."
    * "Serial Forwarder" takes packets from the base station, and forwards
    * them to TCP port 9001.
    * Below is UC Berkeley's copyright disclaimer regarding the original code.
    *                              |   |
    *                              |   |
    *                              |   |
    *                              |   |
    *                            __|   |__
    *                                v
    * "Copyright (c) 2000-2003 The Regents of the University  of California. 
    * All rights reserved.
    * Permission to use, copy, modify, and distribute this software and its
    * documentation for any purpose, without fee, and without written agreement is
    * hereby granted, provided that the above copyright notice, the following
    * two paragraphs and the author appear in all copies of this software.
    * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
    * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
    * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
    * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
    * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
    * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
    * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
    * Copyright (c) 2002-2003 Intel Corporation
    * All rights reserved.
    * This file is distributed under the terms in the attached INTEL-LICENSE    
    * file. If you do not find these files, copies can be found by writing to
    * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
    * 94704.  Attention:  Intel License Inquiry.
    import java.util.Properties;
    import java.io.*;
    import java.net.*;
    import net.tinyos.packet.*;
    import net.tinyos.util.*;
    import net.tinyos.message.*;
    import javax.mail.internet.*;
    import javax.mail.*;
    import java.util.*;
    public class ListenNotifier{
        public static void main(String args[]) throws IOException, MessagingException {
         int i;
         int j = 0;
         Integer threshold=0;
         String to="";
         String timeStamp;
         // Check to see if user is running the program correctly.
         // If -T option is not used, a default value of 250 lux is
            // set as threshold . . .
         switch (args.length){
         case 0:
               System.err.println("usage: java ListenNotifier < EmailAddress1 > <  EmailAddress2 > . . .  -T < Threshold >\n");
               System.exit(2);
               break;
         case 1:
             to = args[j];
             threshold = 250;
             break;
         default:
             if (args[args.length-2].equals("-T")){
              threshold = threshold.valueOf(args[args.length-1]);
              to = args[0];
              while(!args[j+1].equals("-T")){
                  to = to + " " + args[j+1];
                  j++;
              break;
             else{
              j = 0;
              threshold = 250;
              to = args[j];
              while((j + 1) < args.length){
                  to = to + " " + args[j+1];
                  j++;
              System.out.printf("Mailing list is: %s\n", to);
              break;
         // Connect to the Serial Forwarder on TCP port 9001 . . .
             PacketSource reader = BuildSource.makeSF("192.168.0.12",9001);
         // Check to see if connection to Serial Forwarder successful . . .
         if (reader == null) {
             System.err.println("Invalid packet source (check your MOTECOM environment variable)");
             System.exit(2);
         try {
             // Use JavaMail API methods to set up an
             // email session . . .
          Properties props = System.getProperties();
         Session session = Session.getInstance(props, null);
         javax.mail.Message message = new MimeMessage(session);
             // Open the packet source . . .
             reader.open(PrintStreamMessenger.err);
             // Set a threshold boolean to be used so
             // email is sent only once after threshold
             // is exceeded.
             Boolean limit = false;
             for (;;) {
              // The node ID field in the OscilloscopeRF packet
              // is 2 bytes long, but all byte pairs in the packet
              // are in little endian order.  Thus, the bytes must
              //  be re-ordered.  They are then converted to unsigned
              // integers and added together to obtain the node ID.
              byte[] packet = reader.readPacket();
              Integer nodeID = (( int ) packet[5] & 0xFF) + ((( int ) packet[6] & 0xFF)<<8);
              System.out.printf("Packet from node %d . . . \n", nodeID);
              // Begin extracting data payload of sensor readings,
                    // which are stored in the last 20 bytes of the packet . . .
             for (i = 0; i <= 9; i++){
              // Convert reading to integer, display on screen . . .
              Integer sensorData = (( int ) packet[(2*i)+11] & 0xFF) + ((( int ) packet[(2*i)+12] & 0xFF)<<8);
              System.out.printf("Sample %d reading at %d lux.\n", i+1, sensorData);
              // Is sensor reading  above limit?
              if(!limit && (sensorData >= threshold)){
                  limit = true;
                  System.out.printf("WARNING: SENSOR READING ABOVE THRESHOLD--SENDING NOTICE BY TEXT MESSAGE.\n");
                  // Compute a time stamp for when threshold was exceeded.
                  java.util.Locale locale = Locale.getDefault();
                  java.text.DateFormat dateFormat = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.LONG,
                                                                  java.text.DateFormat.LONG, locale);
                  timeStamp = dateFormat.format(new java.util.Date());
                  // Build message and send to recipients in mailing list . . .
                  message.setFrom();
              message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to, false));
              message.setSubject("WARNING: NODE " + nodeID.toString() + " SENSOR READING ABOVE THRESHOLD!");
              message.setText("Node " + nodeID.toString() + " sensed " + sensorData.toString() + " lux on " + timeStamp + "\n");
              Transport.send(message);
                  System.out.printf("%s\n",timeStamp);
              //  Has sensor reading now dropped from above threshold to below threshold?
              //  Same concept as before . . .
              if(limit && (sensorData < threshold)){
                  limit = false;
                  System.out.printf("READING BELOW THRESHOLD AGAIN . . . SENDING NOTICE BY TEXT MESSAGE.\n");
                  java.util.Locale locale = Locale.getDefault();
                  java.text.DateFormat dateFormat = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.LONG,
                                                                  java.text.DateFormat.LONG, locale);
                  timeStamp = dateFormat.format(new java.util.Date());
                  message.setFrom();
              message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to, false));
              message.setSubject("NODE " + nodeID.toString() + " READING BELOW THRESHOLD AGAIN.");
              message.setText("Node " + nodeID.toString() + " sensed " + sensorData.toString() + " lux on " + timeStamp + "\n");
              Transport.send(message);
                  System.out.printf("%s\n",timeStamp);
             System.out.println();
             System.out.flush();
         // Catch IOException from Tiny OS java method, and
         // MessagingException from setRecipients method in JavaMail API . . .
         catch (IOException e) {
             System.err.println("Error on " + reader.getName() + ": " + e);
         catch(MessagingException e){
         System.err.println("Error in javax.mail.message.setRecipients:\n" + to);
    }

  • Problem with NumberFormatException

    hi guys,
    below is the codes that catches NumberFormatException
    basically i want to read an int from file number.txt
    can anyone help me?
    thanks
    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class Test
         String id = null;
         GregorianCalendar today = new GregorianCalendar();
         DecimalFormat df1 = new DecimalFormat("00");
         DecimalFormat df2 = new DecimalFormat("00000000");
         public Test(){}
         public String generateID()throws IOException{
              try{
                   BufferedReader read = new BufferedReader(new FileReader("number.txt"));
                   //PrintWriter write = new PrintWriter(new FileOutputStream("number.txt"));
                   int num = 0;
                   Integer year = new Integer(today.get(Calendar.YEAR));
                   Integer month = new Integer(today.get(Calendar.MONTH)+1);
                   String tempYear = year.toString();
                   String tempId = tempYear.substring(2)+df1.format(month);
                   String line = read.readLine();
                   while(read != null){
                        num = Integer.parseInt(line);
                        line = read.readLine();
                   num++;
                   id = tempId+df2.format(num);
                   //write.println(""+num);
              catch(FileNotFoundException ex){
                   System.out.println("File not found");
              catch(IOException e){
                   System.out.println("Error in reading file");
              catch(Exception ec){
                   System.out.println("Error here");
              //write.close();
              return id;          
         public static void main(String[] args)throws IOException{
              Test t = new Test();
              System.out.println(t.generateID());

    These linesString line = read.readLine();
    while(read != null) {
      num = Integer.parseInt(line);
      line = read.readLine();
    num++;are going to read lines from a file and convert them to integers until it can't read any more. You will get the last value from the file... unless the last line (or any line) is blank or contains garbage parseInt can't handle.
    All the programs I have written usually read a number, then do something with it.
    If you just want to read one line, take the while loop off.
    if you want to trap the error, put a try/catch block around it.

  • Get int parameter

    hi..i need some help here..
    i use this code
    keyID2 = request.getParameter("keyID2")
    keyID3 = request.getParameter("keyID3")
    and assign the value to String keyID2 and keyID3. The value i received from keyID2 and keyID3 is both an integer value, but using the syntax request.getParameter("keyID2") i can only assign the value received to a string variable.
    The problem is i need to add up both the value of string keyID2 and keyID3 and assign it to an integer variable, but it seems if i just do the normal keyID2+keyID3, the normal integer addition doesn't occur here; instead it just concantenates both the now string value.
    how do i overcome this problem?
    any help are greatly appreciated. thanks in advance

    Yes, keyID2 and keyID3 are Strings so the + operator concatenates them. If you want to convert them to integers and find their sum, then convert that back to a String, then do this:int keyNum2 = Integer.parseInt(keyID2);
    int keyNum3 = Integer.parseInt(keyID3);
    String result = Integer.toString(keyNum2 + keyNum3);If those parameters happen to not be integers then this code will throw a NumberFormatException. You should catch that and deal with it in some way.

  • Convert integers to equivalent characters in string - NOT ASCII code character

    I have to output my data and associated string information to a string array and then to a spreadsheet file.
    I want to do this by converting integers (and other numbers) to an identical string of characters.
    I have tried Type Cast with a string constant as the type input but it DOES NOT WORK.  Instead, I get the ASCII character whose numerical designation matches the integer, e.g. integer "50" become capital "P".
    I want integer "50" to be string "50".
    Please advise and no, I do not want to make arrays of clusters.
    Solved!
    Go to Solution.

    I found my answer but only after searching for "Number" conversion rather than "Integer" conversions.
    In the Programming palette  - String Functions - String/Number Conversion - Number to Decimal String:
    "Converts number to a string of decimal digits at least width characters wide or wider if necessary. If number is floating-point, it is rounded to a 64-bit integer before conversion."

Maybe you are looking for

  • Bug with "Put Back" feature.

    If I delete file dragging it out from Dock's folder to Trash (checked with Downloads, Applications, custom one, Documents) - file can't be Put Back from Trash (CMD+Z as well). Deleting the same file using Fn+Delete button or opening folder and draggi

  • How to design a fluid site at a specific largest size?

    I liked the sizing of the "desktop" preview standard in dreamweaver so I mocked up a whole site at that size only to find out there are sizes above it that stretch out the page. Should I ALWAYS design websites at the largest size ( 1580 w x 1050 h  )

  • Dimm Riser card ?

    Hello, I need to get a new dimm riser card as one of mine seems to be faulty, can these be bought from apple? I don't see anything on the apple online store, if i phone them could i order one? or go into town to the apple store & buy one? if not wher

  • Dynamic links to modules for user-friendly searching.

    Hi, We want to create a generic search form/report which can be called from any number of our other forms in an application. The results of the search should contain a dynamic link back to whichever form the search facility was called from. This is t

  • Airport problems after installing 10.5.6

    Airport on my MBP (2.4GHz, pre-"unibody") will no longer connect to my home wireless network (set up with WEP) after installing 10.5.6. It was flawless on all prior versions (and my 10.4 machine still connects fine). I installed with the "combo" upda