public static void main(String[] args) {
String word;
String[] RobinWords = {"Hole In A Donut", "Bankruptcy", "Popcorn", "Ravioli", "Hijack", "Camouflage", "Key Hole", "New Year's Eve", "Trampoline", "Zorro", "Hallucination", "Alter Ego", "Backfire", "Batman"};
Random rand = new Random();
word = RobinWords [rand.nextInt(RobinWords.length)];
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
}
It might seem a little silly but I couldn't figure out how to make the output to be different from one another.
What you likely meant to do
for (int i = 0 ; i < 5 ; i++)
{
word = RobinWords[rand.nextInt()];
System.out.println("Holy " + word + ", Batman");
}
This code will select a randomized index, send it to your array, store that Index's corresponding element in a String then print the string.
Put it in a loop, and get a new random word on each iteration.
String[] robinWords = { "Hole In A Donut", "Bankruptcy", "Popcorn", "Ravioli", //
"Hijack", "Camouflage", "Key Hole", "New Year's Eve", "Trampoline", //
"Zorro", "Hallucination", "Alter Ego", "Backfire", "Batman" };
Random rand = new Random();
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(robinWords.length);
System.out.printf("Holy %s, Batman!%n", robinWords[index]);
}
Note that I have tried to improve the readability of your code by using a more standard name for robinWords and using printf instead of String concatenation. If you need five unique phrases, then you should probably prefer a Set; and assuming you're using Java 8+, you could do something like
Set<String> wordSet = new LinkedHashSet<>();
Random rand = new Random();
while (wordSet.size() < 5) {
int index = rand.nextInt(robinWords.length);
wordSet.add(robinWords[index]);
}
wordSet.stream().forEachOrdered(word ->
System.out.printf("Holy %s, Batman!%n", word));
Try this
System.out.println("Holy " + RobinWords [rand.nextInt(RobinWords.length)] + ", Batman!");
Because when rand.nextInt() execute it only generate random number once
Related
so I'm having a small problem in java. I have something like
"Victor Fleming"
"Gone With"
"With The"
"The Wind."
So what the sentence should actually look like is
"Victor Fleming"
"Gone with the wind."
Therefore I'm looking to form a single sentence, by words that are adjacent and the same. If no adjacent same word is detected then the sentence will be separated as in "Victor Fleming" case where Fleming is not the same with Gone, so a new sentence is starting. What I've written so far:
List<String> separatedText = new ArrayList<>();
int i = 0;
while (i < mergedTextByHeightColor.size()) {
if ((i < (mergedTextByHeightColor.size() - 3)) && !(mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
separatedText.add(mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1));
i = i + 2;
}
String concatStr = "";
while ((i < (mergedTextByHeightColor.size() - 3)) && (mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
if (concatStr.contains(mergedTextByHeightColor.get(i))) {
concatStr = mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
} else {
concatStr = mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
}
i = i + 3;
}
separatedText.add(concatStr);
}
We can store the sentences in a String array, then loop through each one.
Inside the loop, we check whether the last word of the last item (by splitting it into an array with .split(" "), then getting the last element) is equal to the first word of the current item. If it is, we first remove the first word of the current item, then append it to a StringBuilder.
If it isn't, then we append the StringBuilder's value to the list, append the current element, and move on.
String[] sentences = {"Victor Fleming", "Gone With", "With The", "The Wind."};
List<String> newsentences = new ArrayList<>();
StringBuilder str = new StringBuilder();
for(int i = 0; i < sentences.length; i++) {
String cur = sentences[i];
if(i != 0) {
String[] a = sentences[i-1].split(" ");
String[] b = cur.split(" ");
String last = a[a.length-1];
String first = b[0];
if(last.equalsIgnoreCase(first)) {
str.append(cur.substring(first.length()));
}else {
newsentences.add(str.toString());
str = new StringBuilder();
str.append(cur);
}
}else {
str.append(cur);
}
}
newsentences.add(str.toString());
System.out.println(Arrays.toString(newsentences.toArray()));
Output:
[Victor Fleming, Gone With The Wind.]
I'm making a random creature generator, its going all nice and dandy, however when it comes to printing the results, it prints the same result 5 times. I tried some different things like using println() multiple times and do while loops, however every time I run the file I just get a bunch of the same results. "a b c d e" are strings that generate the creature
int x = 1;
do {
System.out.println(x +" " +a +" " +b +" " +c +" " +d +" " +e);
x++;
} while (x<=5);
The reason why you're getting the same answer 5 times is because your do-while loop runs 5 times without changing the 'creatures' .
System.out.println(a +" "+ b + " " + c + " " + d + " " +e);
If you remove the do-while loop you'll get the same answer only once however just in case i misunderstood your question i made a small demo of a simple way in which to get multiple random results with a for-loop,a String-array and the Random class
String[] creatures = {"Dog", "Cat", "Fish", "Monkey", "Horse"};
Random r = new Random();
for (int i = 0; i < 5; i++) {
String creature1 = creatures[r.nextInt(creatures.length)];
String creature2 = creatures[r.nextInt(creatures.length)];
String creature3 = creatures[r.nextInt(creatures.length)];
String creature4 = creatures[r.nextInt(creatures.length)];
String creature5 = creatures[r.nextInt(creatures.length)];
System.out.println(creature1 + " " + creature2 + " " + creature3
+ " " + creature4 + " " + creature5);
}
I am creating a Premier League football table in my spare time and I have come across a problem. While the program runs I want it to be perfect and output in the format I want it to, the problem is:
You enter the the Input (" HomeTeam : AwayTeam : HomeScore : AwayScore ") as follows
When you are done with the list you enter "quit" to stop the program
My issue is that the scores come out like this
(" HomeTeam | AwayTeam | HomeScore | AwayScore ")
I intend it to print like this (" HomeTeam [HomeScore] | AwayTeam [AwayScore] ")
I have tried many variations of System.out.printlns to no avail, even trying to make several Boolean conditions that will output the input in the way I want it too. I am truly at a loss and it is frustrating - I hope that someone can give me tips the code is attached
Edited for loop;
for (int i = 0; i < counter; i++) { // A loop
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + "[" + words[2].trim() + "]" + " | " + words[1].trim() + "[" + words[3].trim()) + "]";
This should work:
Scanner sc = new Scanner(System.in);
public void outputScore(String input) {
String[] words = input.trim().split("\\s+");
String satisfied = sc.nextLine();
if (satisfied.equals("quit")) {
System.out.println(words[0] + " [" + words[4] + "] | " + words[2] + " [" + words[6] + "]");
}
}
This is what the method should look like when you call it:
outputScore(sc.nextLine());
Here is the code to your edited question:
String [] product_list = new String [100];
int counter = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Input as follows:");
System.out.println("Home team : Away team : Home score : Away score");
String line = null;
while (!(line = scanner.nextLine()).equals("")) {
if (line.equals("quit")) {
break;
} else {
product_list[counter] = line;
System.out.println("Home team : Away team : Home score : Away score");
}
counter++;
}
for (int i = 0; i < counter; i++) {
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + " : " + words[2].trim() + " | " + words[1].trim() + " : " + words[3].trim());
}
Hope this helps.
I have a long text which is stored in a String (i.e. tstr1 im code). Now I want to store the user input from console in a String[] (i.e. itemsFromArray im code).
I want for each word stored in the user input String[] array, the system to show how many times that word is present in the long Text String[] array. I tried in this way, but the problem is that the system shows the count just for first entry from an array but for the next it is showing zero.
btnNewButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
keyW = txtKeyword.getText();
search = textField.getText();
System.out.println("String for car = " + search);
System.out.println("String keyword = " + keyW);
WebDriver driver = new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/" + search);
tstr1 = driver.findElement(By.xpath("//*[#id='content']")).getText();
String [] itemsFromArray = keyW.split(",");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String word : itemsFromArray){
map.put(word, 0);
}
Scanner s = new Scanner(tstr1);
while (s.hasNext()){
String word = s.next();
if (map.containsKey(word)){
map.put(word, map.get(word) + 1);
System.out.println("Word1 '" + word + "' count:" + map.get(word));
} else {
System.out.println("Word2 '" + word + "' not in map");
}
}
driver.close();
}
});
It's probably better to use a Map<String, Integer>:
// initialize a mapping that is used to map words to their count
Map<String, Integer> counter = new HashMap<String, Integer>();
// initialize all counts to 0
for (String word : itemsFromArray){
counter.put(word, 0);
}
// ...
// count words that are in map (give up those that aren't)
while (s.hasNext()){
String word = s.next();
if (counter.containsKey(word)){
counter.put(word, counter.get(word) + 1);
System.output.println("Word '" + word + "' count:" + counter.get(word));
} else {
System.output.println("Word '" + word + "' not in map");
}
}
After I spent one day, the problem was that when I tried to separate the string (without comma) and insert into array, the first string was good but the next started with white spaces and the system does not recognize the word.
btnNewButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//If the button UPLOAD was not pressed we should to clear the ArrayList
listKeys.clear();
//////////////////////////////////////////////
if(textField.getText().equals("")) {
JOptionPane.showMessageDialog(null,"Make sure you enter at least one search key");
}
else if (txtKeyword.getText().equals("")) {
System.out.println("String is NULL ");
JOptionPane.showMessageDialog(null,"Add at least one keyword");
} else {
keyW = txtKeyword.getText();
search = textField.getText();
System.out.println("String for car = " + search);
System.out.println("String keyword = " + keyW);
WebDriver driver = new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/" + search);
tstr1 = driver.findElement(By.xpath("//*[#id='content']")).getText();
String [] items = keyW.split(",");
String [] itemsFromArray = new String[items.length];
for ( int i = 0; i < items.length; i++)
{
itemsFromArray[i] = items[i].trim();
}
for(String string : itemsFromArray)
{
//if (args[i].toLowerCase().startsWith( "from:" ))
System.out.println("FOREACH " + string);
int i = countWords(tstr1, string);
System.out.println("Word count "+ string + ": " + i);
Keyword1 = ("Count for word " + string + " are " + i);
listKeys.add(Keyword1);
}
driver.close();
}
}
private static int countWords(String tstr1, String string)
{
int i = 0;
Scanner s = new Scanner(tstr1);
while (s.hasNext())
{
if (s.next().equals(string))
i++;
}
return i;
}
}
for(int counter = 0; counter < args.length; counter++){
System.out.println("Displaying per words: " + args[counter]);
splitWords = args[counter].toCharArray();
for(int counter2 = 0; counter2 < splitWords.length; counter2++){
System.out.println("Word spliced: " + splitWords[counter2]);
System.out.println("The number equivalent of " + splitWords[counter2] + " is "
+ (int) splitWords[counter2]);
occurenceCount[(int)splitWords[counter2]]++;
System.out.println("The letter " + splitWords[counter2] +
" was shown " + occurenceCount[(int)splitWords[counter2]] + " times.");
}
}
My function doesn't detect counter2 as a variable since it was inside the nested for loop. So how do I get out of this dilemma?
I'm trying to use the argument inputs (string respectively) and post the number of occurrences using an ascii table as reference and, as you see, there's just one obstacle from stopping me from accomplishing that.
Any ideas?
Your primary problem is that you have missed one important fact - your counts are not complete until after your loop has completed.
You therefore need to print out your counts in a separate loop after your first loop is complete.
public void test() {
String[] args = {"Hello"};
int[] occurenceCount = new int[256];
for (int word = 0; word < args.length; word++) {
System.out.println("Displaying per words: " + args[word]);
char[] splitWords = args[word].toCharArray();
for (int character = 0; character < splitWords.length; character++) {
System.out.println("Word spliced: " + splitWords[character]);
System.out.println("The number equivalent of " + splitWords[character] + " is "
+ (int) splitWords[character]);
occurenceCount[(int) splitWords[character]]++;
System.out.println("Word spliced: " + splitWords[character]);
}
}
// Scond loop to print the results.
for (int character = 0; character < occurenceCount.length; character++) {
int count = occurenceCount[character];
if (count > 0) {
System.out.println("The letter " + ((char) character)
+ " was shown " + count + " times.");
}
}
}