Created
August 29, 2015 10:15
-
-
Save mick001/3a7801478876e8c50b1a to your computer and use it in GitHub Desktop.
Two simple Java programs part 2. Full article at http://www.firsttimeprogrammer.blogspot.com/2015/03/two-simple-java-programs.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
import java.util.Random; | |
public class SentenceGeneratorMain | |
{ | |
public static void main(String[] args) | |
{ | |
//Variables declaration and initialization | |
Scanner reader = new Scanner(System.in); | |
String input = new String(); | |
String reply = new String(); | |
Random rGenerator = new Random(); | |
boolean again = true; | |
boolean first = true; | |
//Program description | |
String description = "This simple program takes a sentence as input and then\n" | |
+ "it prints another sentence of the same length placing the words\n" | |
+ "in a random place. Enter a sentence to start. After it has run\n" | |
+ "the program asks you if you'd like to play again, enter 'no' to\n" | |
+ "terminate the program otherwise enter a random character.\n" | |
+ "------------------------------------------------------------------\n" | |
+ "Let's start:\n\n"; | |
//Initial prints | |
System.out.println(description); | |
System.out.println("Enter a sentence: "); | |
//Main loop | |
while(again) | |
{ | |
if(!first){System.out.println("Enter a sentence: ");} | |
else{first = false;} | |
//Reading the input and storing the string as an array | |
input = reader.nextLine(); | |
String[] array = new String[input.split(" ").length]; | |
for(int i=0; i< array.length; i++) | |
{ | |
array[i] = input.split(" ")[i]; | |
} | |
//Sentence generation | |
for(int i=0; i < array.length; i++) | |
{ | |
int k = rGenerator.nextInt(array.length); | |
System.out.print(array[k]); | |
System.out.print(" "); | |
} | |
//Play again? | |
System.out.println("\nPlay again?"); | |
reply = reader.nextLine(); | |
if("no".equals(reply) || "No".equals(reply)){again = false;} | |
} | |
reader.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment