Advertisement
asoler

BACKWARDS cleaned

Feb 19th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class backwards {
  4.     public static void main(String[] args) {
  5.        
  6.         //scanner
  7.         Scanner kbin = new Scanner(System.in);
  8.        
  9.         //sentence input
  10.         System.out.println("enter a sentence: ");
  11.         String sentence = kbin.nextLine();
  12.        
  13.         //sentence data
  14.         int sentenceLength = sentence.length();
  15.         int spaces = 0;
  16.        
  17.         //selection for substring of words
  18.         String selection = "";
  19.         int selectionStart = 0;
  20.         int selectionEnd = 0;
  21.        
  22.         //for loop (count spaces)
  23.         for (int x = 0; x < sentenceLength; x++) {
  24.             String character = sentence.substring(x,x+1);
  25.            
  26.             if (character.equals(" ")) {
  27.                 spaces++;
  28.             }
  29.         }
  30.        
  31.         //create array to start scanning and storing for words
  32.         String[] words = new String[spaces + 1];
  33.         int wordArr = 0;
  34.        
  35.         //for loop (scan and assign words to array)
  36.         for (int x = 0; x < sentenceLength; x++) {
  37.             String character = sentence.substring(x,x+1);
  38.            
  39.             if (x == sentenceLength-1) {
  40.                
  41.                 if (character.equals(" ") && x == sentenceLength - 1) {
  42.                     selectionEnd = x;
  43.                 } else {
  44.                     selectionEnd = x + 1;
  45.                 }
  46.                
  47.                 words[wordArr] = sentence.substring(selectionStart, selectionEnd);
  48.                 selectionStart = x + 1;
  49.                
  50.             } else if (character.equals(" ")) {
  51.                 selectionEnd = x;
  52.                 words[wordArr] = sentence.substring(selectionStart, selectionEnd);
  53.                 selectionStart = x + 1;
  54.                 wordArr++;
  55.                
  56.             }
  57.         }
  58.        
  59.         //for loop (prints words backwards)
  60.         for (int x = words.length - 1; x >= 0; x--) {
  61.             System.out.print(words[x] + " ");
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement