Quick String / char  question

Hi, i have to write a encrytion method for a assignment, it must take a string, move the characters on by a set number given by the user and return the result.
public class Encryption
    int key;
    public Encryption(int k)
        key = k;
public String encrypt(String si)
si = si.toUpperCase();
int i = 0;
for (int index = 0; index< si.length(); index++);
char c = si.charAt(i);
int n = c - 'A' + key;
char a = (char)(n + 'A');
return si ;
}it compiles, but what i need to know is how to i get my new chars (that have been moved the set amout) back into a string that is returned to the user, as i cant seem to find the code i need to do this???

String result = "";
Each time through the loop, you will want to add it to the result
result = result + a;This is poor adviceimport java.io.*;
public class Encryption{
   public static void main(String[] args) {
      new Encryption();
   Encryption(){
      String toEncyrpt = "The quick brown fox jumps over the lazy dog";
      int key = 0;
      try{
         BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
         System.out.print("Enter a number for the encryption key ");
         key = Integer.parseInt(br.readLine());
      }catch(IOException e){}
      String encrypted = encrypt(toEncyrpt, key);
      System.out.println("Encrypted string : "+ encrypted);
      String decrypted = decrypt(encrypted, key);
      System.out.println("Decrypted string : "+ decrypted);
    public String encrypt(String s, int k){
       StringBuffer sb = new StringBuffer();
       for(int i=0; i<s.length(); i++) {
           int temp = (int) s.charAt(i)+k;
           sb.append((char)temp);
       return sb.toString();
    public String decrypt(String s, int k){
       StringBuffer sb = new StringBuffer();
       for(int i=0; i<s.length(); i++) {
           int temp = (int) s.charAt(i)-k;
           sb.append((char)temp);
       return sb.toString();
}

Similar Messages

  • Quick string tokenizer question

    HELP!
    I'm quite new to using string tokenizers in Java.
    I'm trying to use a string tokenizer to read some data into a multi dimensional int array and then print it to the screen.
    What I'm using so far is:
    FileReader file = new FileReader("test.txt");
    BufferedReader inputFile = new BufferedReader(file);
    StringTokenizer data;
    for(int i=0; i<LEARN; i++)
         data = new StringTokenizer(inputFile.readLine());
         for (int j=0; j<NEURONS; j++)
                                 examples[i][j] = new int(data.nextToken().intValue);
    for(int row=0; row<LEARN; row++)
         for (int collumn=0; collumn<NEURONS; collumn++)
                             screen.print(examples[row][collumn] + " ");
                             screen.flush();
    }However, I'm getting errors!!
    Could anyone help at all??
    Cheers
    Ross

    However, I'm getting errors!!The messages that come with errors usually play a significant role in resolving them. Would you mind posting those messages?
    Where do you define the variable "examples" ?
    new int(data.nextToken().intValue);This is definitely wrong.

  • Quick SAP Script question New Page Print

    Quick SAP Script question
    I have added a new page to an existing SAP Script BUT only want it to print if a condition is true.
    I need to do this from within the form as the print program is SAP Std.
    Any idea how I can prevent the new page from printing?
    i.e. I need the form NOT to call the new page if the condition is false. Is there a way of forcing an exit or stop from with in the form?

    Hi,
    To trigger a new page, there is script ediotr command NEW-PAGE.
    so find where is that command is triggered and use the below code for trigger it on any specific condition....
    if &condition& = 'True'
    /*  NEW-PAGE
    elseif
    /: NEW-PAGE   
    endif
    so it means if condition is satisfied your new page will not work.. else it will...
    Hope you got it...
    Try this..
    Best luck..
    Regs,
    Lokesh.

  • I have what is hopefully a quick and easy question. I kno...

    I have what is hopefully a quick and easy question. I know almost nothing about this stuff so go easy on me . All I need to do is find out if my DHCP is enabled. I'm having problems with my Xbox 360 and one of the possible problems is this DHCP thing. However I have no idea how to find the settings for my router on my computer. If it helps I have a Wirless model BEFW11S4. Thanks in advance for any help.

    You need to access your router to check if the DHCP is on.  To access the router open your browser and type in http://192.168.1.1 into the address field and hit enter.  That should open the routers log on screen and by default the user is left blank (some routers it is admin) and the password is abmin.  If you changed your routers password as you should for security reasons then use that password.  That will bring you to your routers user interface and on the main set up page should be your DHCP.
    Richard Aichner (Ikester)

  • How to to scan a string, char by char?

    Hi i have some xml data, i want to scan the string char until it sees > for the first time. Then it adds the following data until it sees <, at which point it stops. So i should get s2tidm1 from "<server>s2tidm1</server>"
    The problem with the below code is that sa.next() gives me the whole string as there is no space, is there a sa.nextChar() or something similar?
    Code following -- Thanks Peter
    import java.io.*;
    import java.util.Scanner;
    import java.util.*;
    public class xmltestmod {
    static String data =  "<server>s2tidm1</server>";
        public static void main(String args[]) {
              Scanner sa = new Scanner(data);
              String pete = " ";
              String temp =" ";
              while (sa.hasNext())          {
                   temp = sa.next();
                   System.out.println(temp);
                   if (temp.contains(">")){
                        while (true){
                        System.out.println("Entering if");
                        temp = sa.next();
                        pete = pete + temp;
                             if(temp.contains("<")) break;
         System.out.println(pete);               
         sa.close();
    }

    >
    I got muiltiple xml lines in a array, i want to loop
    the array and strip out the tags so only the data is
    left. Thats why i didn't use the xml apis out there
    as you need to say starttag = "<Server>";, endtag =
    "/Server>", but i just want to say store all data
    inbetween < and >, that way i can loop through the
    whole array.
    Actually if you use the SAX parser, rather than the DOM parser, it will call a method of your chosing for each text element, and you can just ignore the callbacks for tags etc. if you wish.
    Can you explain abit more about hte substring and
    index of part please.Check the Javadocs. Substring chops part of a string out, indexOf finds the first occurance of a character.

  • Quick string question finding if a string contains a character

    hello peeps
    is there a quick way of checking if a string contains a specific character
    e.g.
    myString="test:test";
    myString.contains(":");
    would be true
    any ideas on a quick way of doing it

    is there a contains() method in 1.4.2? i couldnt see
    it in the docsNo there isn't. But the 1.5 has a contains(CharSequence s) method.

  • Quick String Question

    A co-worker had a query he was running with a where clause something like this...
    Where
    Name='BLAH & BLAHBLAH'
    How do I pervent sql developer from treating the & symbole as a request for a variable prompt?
    It's would prompt for variable named BLAHBLAH...
    Thanks
    Obe
    ps. So far the Java SDK 6_10 is working...

    In SQL*Plus you can "SET DEFINE OFF" prior to the SQL statement to get it to ignore the ampersand, but as far as I know (and I may be wrong), you can't do that in SQL Developer Worksheet.
    What I normally do in this situation is break the string up and use "||" and "CHR". To use your example:
    WHERE name = 'BLAH ' || CHR(38) || ' BLAHBLAH'
    Ed. H.

  • QUICK VIEWER RELATED QUESTION

    Hi
    Can I add a new column to my quick viewer report that will display TOTAL of existing columns in the report.  What is the method? 
    How can I make my quick viewer report to open a document when I double click a field value.  I see it happening in VF05 , va05 (lists).
    Any advice appreciated.
    Thanks,
    Surya

    Okay, Ceci, I don't know as much about this stuff as
    you obviously do, so I'm really sorry I offended you
    with my newbie faux pas. Do you realize that in the
    time it took you to rip on me you could have already
    answered the question? Thanks for the sentiment.I answered it the best I could: write a small program and try it.
    With MSAccess, my understanding is that if you have a string with length under
    255 it's type is TEXT, and over 255 it's MEMO... is this right?String: max. 255 chars
    Memo: max 64000 chars.
    Sez the Access help.
    But what does this string look like if the column will hold strings of text longer
    than 255? Try it. Might puke, might truncate the String, might autoconvert. I don't know. You'll see.
    Do I only specify the size like TEXT(400), or do I list the type like MEMO(400) or what?If you expect it to be > 255 chars, why not simply define the field as Memo right away? I doubt you can write a Memo to a textfield.

  • Quick SQL-related question

    With MSAccess, my understanding is that if you have a string with length under 255 it's type is TEXT, and over 255 it's MEMO... is this right?
    My real question is about the CREATE TABLE string, which might look something like this for a shorter bit of text:
    CREATE TABLE MyTable ([MyColumn] TEXT(30) NOT NULL, etc.)
    But what does this string look like if the column will hold strings of text longer than 255? Do I only specify the size like TEXT(400), or do I list the type like MEMO(400) or what?
    I realize that this isn't really a Java focused question, but I'm hoping it's close enough. After all, the app that I'm working on is in Java. I haven't had much luck finding the clarification I need by just googleing this. Thanks for the help.

    Okay, Ceci, I don't know as much about this stuff as
    you obviously do, so I'm really sorry I offended you
    with my newbie faux pas. Do you realize that in the
    time it took you to rip on me you could have already
    answered the question? Thanks for the sentiment.I answered it the best I could: write a small program and try it.
    With MSAccess, my understanding is that if you have a string with length under
    255 it's type is TEXT, and over 255 it's MEMO... is this right?String: max. 255 chars
    Memo: max 64000 chars.
    Sez the Access help.
    But what does this string look like if the column will hold strings of text longer
    than 255? Try it. Might puke, might truncate the String, might autoconvert. I don't know. You'll see.
    Do I only specify the size like TEXT(400), or do I list the type like MEMO(400) or what?If you expect it to be > 255 chars, why not simply define the field as Memo right away? I doubt you can write a Memo to a textfield.

  • Quick string problem - takes 2 seconds lol

    hey guys, quick question...
    i am working on an email client, and through trial and error found out i need to use a strange string class, so i was wondering how do i declare this string in my constructor
    Parameters
    public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingExceptionConstructor Line
    test.postMail([email protected], "test", "test2", "[email protected]");my problem is in that first [email protected]

    My first thought is to think that this isn't a string
    test.postMail([email protected], "test", "test2", "[email protected]");your method innvocation need to be the same as the declaration
    test.postMail([email protected], "test", "test2", "[email protected]"); // this is not the same
    public void postMail( String recipients[ ], String subject, String message , String from) // as thisSee how your first value you pass to the method isn't a string. Hope that helps!
    test.postMail("[email protected]", "test", "test2", "[email protected]"); // this is
    public void postMail( String recipients[ ], String subject, String message , String from) Edited by: didittoday on Mar 8, 2008 8:12 PM

  • SAXParser and char question

    I have a non-validating sax-parser, which appears to work fine. Except in some instances it hiccups and loses characters. "How are you" will come out as "are you".
    I found the problem occurs in the method that reads chars and creates a substring.
    When start reaches 8192, it resets itself to 1 and starts a new line, thereby chopping the text.
    How can I reset start?
    Jim
    public void characters (char ch[], int start, int length)
        // add the question text to the array
         if(question_text)
                  String question = new String(ch).substring(start,start + length);
                  question = question.replace('|', '&');
                  XMLQuestionText[XMLquestion_text_counter] = question;
                  System.out.println("Q " + question );
       // add the choices
         else if( choice_text )
                  choice = new String(ch).substring(start,start + length);
                  choice = choice.replace('|', '&');
                  XMLChoices[XMLquestion_text_counter][choice_counter] = choice;
                  System.out.println("Choices " + choice );
    for (int i = start; i < start + length; i++) {
             switch (ch) {
         case '|':
    ch[i] = '&';
              break;
         case ' ':
              //System.out.print("**");
              break;
         case '\n':
              //System.out.print("\\n");
              break;
         case '\r':
              //System.out.print("\\r");
              break;
         case '\t':
              //System.out.print("\\t");
              break;
         default:
              break;
         }// switch(ch[i])
         }// for
    }// characters()

    Probably your characters() method is being called twice by the parser, once for the "How " part and again for the "are you" part, and probably the parser decides to do this because of its 8192-character internal buffers. Unfortunately this is legitimate behaviour for a SAX parser, and you'll have to fix your program to allow for it.

  • Quick CSS box question

    Hi guys,
    Firstly a very Merry Christmas to you all !
    I'm just getting to grips with converting all the text on my
    site to CSS and have a quick question.
    On some of my pages I add an 'Also see' links box aligned to
    the right - it's a CSS div tag thingy someone kindly talked me
    through once. All of my pages are built from a template with an
    editable region.
    My question is, can I add this box (perhaps with a standard
    'Also check out' title and then spaces for my links) at the
    template level? This will save me having to go to Insert>Layout
    Objects>DivTag on every page. I've tried simply adding this to
    the editable region of the template but it simply pushed the
    editable region box over to the right and then didn't appear on my
    pages
    Also, the links box would ideally appear about half way down
    my pages on the right...
    Hope you can help, many thanks in advance!
    James
    Here's an example page where I have manually added my link
    box on the right of the page...
    http://www.fyrne.com/james_journalism/Pages/Mosaic_of_the_med.html

    Your CSS link implies that the CSS file is in the Templates
    folder. You
    shouldn't have anything there other than the template (dwt)
    files
    themselves. Please move it out to any other location in your
    site.
    <link href="../../Templates/Box.css" rel="stylesheet"
    type="text/css">
    Changes made to template editable regions would not propagate
    to existing
    child pages - that's why you aren't seeing that addition in
    them....
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.dreamweavermx-templates.com
    - Template Triage!
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    http://www.macromedia.com/support/search/
    - Macromedia (MM) Technotes
    ==================
    "JamesFryer" <[email protected]> wrote in
    message
    news:[email protected]...
    > Hi guys,
    >
    > Firstly a very Merry Christmas to you all !
    >
    > I'm just getting to grips with converting all the text
    on my site to CSS
    > and
    > have a quick question.
    >
    > On some of my pages I add an 'Also see' links box
    aligned to the right -
    > it's
    > a CSS div tag thingy someone kindly talked me through
    once. All of my
    > pages are
    > built from a template with an editable region.
    >
    > My question is, can I add this box (perhaps with a
    standard 'Also check
    > out'
    > title and then spaces for my links) at the template
    level? This will save
    > me
    > having to go to Insert>Layout Objects>DivTag on
    every page. I've tried
    > simply
    > adding this to the editable region of the template but
    it simply pushed
    > the
    > editable region box over to the right and then didn't
    appear on my pages
    >
    >
    > Also, the links box would ideally appear about half way
    down my pages on
    > the
    > right...
    >
    > Hope you can help, many thanks in advance!
    >
    > James
    >
    > Here's an example page where I have manually added my
    link box on the
    > right of
    > the page...
    >
    http://www.fyrne.com/james_journalism/Pages/Mosaic_of_the_med.html
    >

  • A Few Quick Lenovo T410 Questions

    Hi all,
    I posted here quite a while ago about my 9 cell battery in my integrated graphics T410 only lasting up to 5 hours. I have yet to send the notebook in simply because I haven't been able to go without it. However, I plan to do so at the start of this next week. Before I do so I was going to swap out the 500GB 7200.1RPM hard drive I installed with the 250GB 5400RPM drive that came with the notebook to see if it was an excessive power issue with the drive.This is where my worries are.
    When I inserted the 500GB hard drive into the drive tray, I had a very hard time screwing the tray in place. The screws were damaged in the process, and I have worries about taking them out, and putting them back in again. I am still under warranty.
    Am I able to recieve a new set of these screws?
    Also, 2 quick questions
    I plan on moving my 500GB drive into the slot where my optical drive is now, and putting a SSD in wheremy 500GB drive is located now. Do I need to buy anything special to make this work?
    I also plan on upgrading from the 2x2GB RAM I installed myself (machine came with 1x2GB), to 4x2GB. Is this RAM compatible?
    Thanks in advance.
    Solved!
    Go to Solution.

    FirstTimeLenovo wrote:
    Am I able to recieve a new set of these screws?
    Hi,
    I think only lenovo techs can determine or tell that, but my guess is that if they feel they need to be replaced, then they probably will.
    FirstTimeLenovo wrote:
    Also, 2 quick questions
    I plan on moving my 500GB drive into the slot where my optical drive is now, and putting a SSD in wheremy 500GB drive is located now. Do I need to buy anything special to make this work?
    I also plan on upgrading from the 2x2GB RAM I installed myself (machine came with 1x2GB), to 4x2GB. Is this RAM compatible?
    Thanks in advance.
    1. Yes, you would need this:- http://www-307.ibm.com/pc/support/site.wss/MIGR-73​170.html
    2. Yep, the RAM will definitely work.
    Hope this helps.
    Maliha (I don't work for lenovo)
    ThinkPads:- T400[Win 7], T60[Win 7], IBM 240[Win XP]
    IdeaPad: U350
    Apple:- Macbook Air [Snow Leopard]
    Did someone help you today? Compliment them with a Kudos!
    Was your question answered today? Mark it as an Accepted Solution! 
      Lenovo Deutsche Community     Lenovo Comunidad en Español 
    Visit my YouTube Channel

  • Very simple XSLT string replacing question

    Hi,
    This is a really simple question for you guys, but it took me long, and i still couldn't solve it.
    I just want to remove all spaces from a node inside an XML file.
    XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <root insertedtime="2008-05-01T14:03:00.000+10:00" pkid="23421">
       <books>
          <book type='fiction'>
             <author>John Smith</author>
             <title>Book title</title>
             <year>2 0  0 8</year>
          </book>
       </books>
    </root>in the 'year' node, the value should not contain any spaces, that's the reason why i need to remove spaces using XSLT. Apart from removing space, i also need to make sure that the 'year' node has a non-empty value. Here's the XSLT:
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:strip-space elements="*"/>
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="//books/book[@type='fiction']">
            <xsl:copy>
                <xsl:apply-templates select="@*"/>
                <xsl:attribute name="id">101</xsl:attribute>
                <xsl:call-template name="emptyCheck">
                    <xsl:with-param name="val" select="year"/>
                    <xsl:with-param name="type" select="@type"/>
                    <xsl:with-param name="copy" select="'true'"/>
                </xsl:call-template>
                <xsl:value-of select="translate(year, ' ', '')"/>
            </xsl:copy>
        </xsl:template>
        <!-- emptyCheck checks if a string is an empty string -->
        <xsl:template name="emptyCheck">
            <xsl:param name="val"/>
            <xsl:param name="type"/>
            <xsl:param name="copy"/>
            <xsl:if test="boolean($copy)">
                <xsl:apply-templates select="node()"/>
            </xsl:if>
            <xsl:if test="string-length($val) = 0 ">
                <exception description="Type {$type} value cannot be empty"/>
            </xsl:if>
        </xsl:template>
    </xsl:stylesheet>The 'emptyCheck' function works fine, but the space replacing is not working, this is the result after the transform:
    <?xml version="1.0" encoding="utf-8"?>
    <root insertedtime="2008-05-01T14:03:00.000+10:00" pkid="23421">
       <books>
          <book type="fiction" id="101">
             <author>John Smith</author>
             <title>Book title</title>
             <year>2 0 0 8</year>2008</book>
       </books>
    </root>The spaced year value is still there, the no-space year is added outside the 'year' tags'
    anyone can help me, your help is extremely appreciated!
    Thanks!

    You should add a template for 'year' :<xsl:template match="year">
    <year><xsl:value-of select="translate(.,' ','')"/></year>
    </xsl:template>and remove the translate call in the 'book' template.
    It would be better to add a 'priority' attribute at each template so it would be explicit which template to use because match="@*|node()" could be interpreted by another transform engine as the unique template to be used !

  • How do I view previous strings of questions and answers on FF support?

    I read this response but it really doesn't answer the question.
    "If you are logged on then you see a My Contributions item in the Filter bar at the top that goes to:
    https://support.mozilla.org/questions?filter=my-contributions"
    I don't see the "filter bar" or "my responses" after I log in. I just see "Ask a question" "my log in name" and some other stuff to the right of that and below that.
    So after I log in, how do I look at strings of my previous questions and all responses to them, including new ones?

    I just figured it out!!! Wha-lah. Go to a question and then click on the underlined text in the question. Then a string of the Q and subsequent responses appears.

Maybe you are looking for

  • Using Mail to monitor my work e-mail account

    My employer has its own e-mail server and it uses XP/Outlook. I want all of my work e-mail to show up in my Mac Mail account. (I have my MacBook Pro connected to the internet at all times.) I went through the File/Add Account thing. I then got the fo

  • Can I get an older version of iTunes?

    I must be dyslexic or just plain accident prone. I installed iTunes 9.1.1.12 and that was a mistake! The requirements said I needed a Pentium D at least to run it. Guess I was in the habit of thinking my stuff was so new, everything would work - wron

  • Using external libraries in Web Dynpro DCs

    Hi, I've followed the example in the following blog for using external libraries in my Web Dynpro (WD) DCs: /people/valery.silaev/blog/2005/09/14/a-bit-of-impractical-scripting-for-web-dynpro and some other messages in the forums. However, it isn't w

  • How to name a layer with the file name - action or script???

    Hi all, Can anyone tell me if it is possible to automatically name a photoshop layer to be the name of the file itself? I have 600 files to do and need to automate the process. Thanks in advance for any advice. Marvo.

  • My Iphone4s does not recognize phone numbers

    Hi! My iphone 4s lists *every* incoming call - even those on my contact list - as "Unknown Caller."  Morever, it DOES NOT remember/list the number of any missed calls, so I a.) never know who called, and b.) can't call them back. This was not a probl