Results 1 to 4 of 4

Thread: help with loop

  1. #1
    kidza12 is offline Member
    Join Date
    Feb 2011
    Posts
    1
    Rep Power
    0

    Default help with loop

    hi,

    i am trying to write a programme that reads in a word, and outputs the last charecter, then the last two then the last three and so on
    e.g
    input: java
    output: a, va, ava, java

    i have written the code but my loop is backward, insteed of reading the last character first, it will start with the first one
    e.g
    input: java
    output: j, ja, jav, java

    here is my code, any help would be greatly appreciated
    package Loop;
    import java.util.Scanner;

    public class loop {

    public static void main(String[] args) {
    String word;
    String output = "";

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter a string: ");
    word = scan.next();

    int numbers = word.length();

    for (int i = 0; i < numbers; i++)
    {
    output += word.substring(0, i + 1) + ",";
    }
    System.out.println(output + "\n");
    }
    Last edited by kidza12; 03-26-2011 at 04:25 PM.

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You want to use the strings length and subtract I each time through the loop.

  3. #3
    BOJANM is offline Member
    Join Date
    Mar 2011
    Posts
    7
    Rep Power
    0

    Default

    public class SubStr {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String word = "Tell me where?";
    for (int i = word.length(); i >= 0; i--) {
    System.out.println(word.substring(i, word.length()));
    }
    }
    }

  4. #4
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Please don't spoonfeed, and use code tags. My post gave a pretty clear idea of what to do. Giving him the code does him no real good.

Similar Threads

  1. JTextField loop 2x for-loop WEIRD!
    By Streetproject in forum AWT / Swing
    Replies: 2
    Last Post: 02-16-2011, 06:46 PM
  2. [Q] Loop issue (while loop)
    By iriscience in forum New To Java
    Replies: 9
    Last Post: 01-31-2011, 05:21 PM
  3. Convert do while loop to for loop
    By sandeeptheviper in forum New To Java
    Replies: 3
    Last Post: 01-03-2011, 01:37 PM
  4. Replies: 5
    Last Post: 04-30-2010, 06:05 PM
  5. while-loop stopping on first loop
    By davester in forum New To Java
    Replies: 6
    Last Post: 06-26-2009, 09:46 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •