Results 1 to 4 of 4
Thread: help with loop
- 03-26-2011, 03:20 PM #1
Member
- Join Date
- Feb 2011
- Posts
- 1
- Rep Power
- 0
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 03:25 PM.
- 03-26-2011, 03:25 PM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
You want to use the strings length and subtract I each time through the loop.
- 03-26-2011, 04:10 PM #3
Member
- Join Date
- Mar 2011
- Posts
- 7
- Rep Power
- 0
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()));
}
}
}
- 03-26-2011, 04:12 PM #4
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Similar Threads
-
JTextField loop 2x for-loop WEIRD!
By Streetproject in forum AWT / SwingReplies: 2Last Post: 02-16-2011, 05:46 PM -
[Q] Loop issue (while loop)
By iriscience in forum New To JavaReplies: 9Last Post: 01-31-2011, 04:21 PM -
Convert do while loop to for loop
By sandeeptheviper in forum New To JavaReplies: 3Last Post: 01-03-2011, 12:37 PM -
How can I rewrite the following while loop using a for loop?
By gt11990 in forum New To JavaReplies: 5Last Post: 04-30-2010, 05:05 PM -
while-loop stopping on first loop
By davester in forum New To JavaReplies: 6Last Post: 06-26-2009, 08:46 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks