Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class backwards {
- public static void main(String[] args) {
- //scanner
- Scanner kbin = new Scanner(System.in);
- //sentence input
- System.out.println("enter a sentence: ");
- String sentence = kbin.nextLine();
- //sentence data
- int sentenceLength = sentence.length();
- int spaces = 0;
- //selection for substring of words
- String selection = "";
- int selectionStart = 0;
- int selectionEnd = 0;
- //for loop (count spaces)
- for (int x = 0; x < sentenceLength; x++) {
- String character = sentence.substring(x,x+1);
- if (character.equals(" ")) {
- spaces++;
- }
- }
- //create array to start scanning and storing for words
- String[] words = new String[spaces + 1];
- int wordArr = 0;
- //for loop (scan and assign words to array)
- for (int x = 0; x < sentenceLength; x++) {
- String character = sentence.substring(x,x+1);
- if (x == sentenceLength-1) {
- if (character.equals(" ") && x == sentenceLength - 1) {
- selectionEnd = x;
- } else {
- selectionEnd = x + 1;
- }
- words[wordArr] = sentence.substring(selectionStart, selectionEnd);
- selectionStart = x + 1;
- } else if (character.equals(" ")) {
- selectionEnd = x;
- words[wordArr] = sentence.substring(selectionStart, selectionEnd);
- selectionStart = x + 1;
- wordArr++;
- }
- }
- //for loop (prints words backwards)
- for (int x = words.length - 1; x >= 0; x--) {
- System.out.print(words[x] + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement