Random poem generator - java

I need to create a random poem generator while using arrays and input from the user (the user needs to input a minimal of 3 adjectives and 3 nouns) then the program has to randomly combine an adjective with a noun (a noun and an adjective can not be re-used twice) and display it. There needs to be 3 lines in the poem. Here's my code but it doesn't function at all the way it's supposed to! Please tell me what i did wrong!
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kb = new Scanner (System.in);
char ch;
do{
int x,y;
String noun2, adj;
//The following is my "Welcome"/Opening message to the user
System.out.println(" ---------------------------------------");
System.out.println(" Welcome to the random poem generator!!!");
System.out.println(" ---------------------------------------\n\n");
System.out.println("Please enter a set of relevant nouns and adjectives that are inspired by the themes of nature and wilderness! \n\n");
//The following will work as a prompt message for the user to input a value when demanded
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
if (x >= 3){
String[] noun = new String [x];
for(int j=0; j<noun.length;j++){
System.out.println("Enter your " + x + " nouns: ");
System.out.println(j);
noun[j] = kb.nextLine();
}
}
else{
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
}
if (y >=3){
String[] adjective = new String [y];
for(int j=0; j<adjective.length;j++){
System.out.println("Enter your " + y + " adjectives: ");
System.out.println(j);
adjective[j] = kb.nextLine();
}
}
else{
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
}
System.out.println(" --------------------");
System.out.println(" Here is your poem!!!");
System.out.println(" --------------------\n\n");
String[] poemline = new String[3];
poemline[0] = adj + noun2;
poemline[1] = adj + noun2;
poemline[2] = adj + noun2;
System.out.println(poemline[0]);
System.out.println("/t/t" + poemline[1]);
System.out.println("/t/t/t/t" + poemline[2]);
System.out.println("Would you like to try another poem (y/n)? ");
String answer;
answer = kb.nextLine().trim().toUpperCase();
ch = answer.charAt(0);
}while(ch == 'Y');
}
}

Try this
import java.util.Random;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner (System.in);
char ch;
do{
int x,y;
String noun2 = null;
String adj = null;
//The following is my "Welcome"/Opening message to the user
System.out.println(" ---------------------------------------");
System.out.println(" Welcome to the random poem generator!!!");
System.out.println(" ---------------------------------------\n\n");
System.out.println("Please enter a set of relevant nouns and adjectives that are inspired by the themes of nature and wilderness! \n\n");
//The following will work as a prompt message for the user to input a value when demanded
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
String[] noun = null;
String[] adjective = null;
if (x >= 3){
noun = new String [x];
for(int j=0; j<noun.length;j++){
System.out.println("Enter your " + x + " nouns: ");
System.out.println(j);
noun[j] = kb.nextLine();
}
}
else{
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
}
if (y >=3){
adjective = new String [y];
for(int j=0; j<adjective.length;j++){
System.out.println("Enter your " + y + " adjectives: ");
System.out.println(j);
adjective[j] = kb.nextLine();
}
}
else{
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
}
System.out.println(" --------------------");
System.out.println(" Here is your poem!!!");
System.out.println(" --------------------\n\n");
String[] poemline = new String[3];
Random rnd = new Random();
poemline[0] = adjective[rnd.nextInt(y-1)] +" "+ noun[rnd.nextInt(x-1)];
poemline[1] = adjective[rnd.nextInt(y-1)] +" "+ noun[rnd.nextInt(x-1)];
poemline[2] = adjective[rnd.nextInt(y-1)] +" " +noun[rnd.nextInt(x-1)];
System.out.println(poemline[0]);
System.out.println("\t\t" + poemline[1]);
System.out.println("\t\t\t\t" + poemline[2]);
System.out.println("Would you like to try another poem (y/n)? ");
String answer;
answer = kb.nextLine().trim().toUpperCase();
ch = answer.charAt(0);
}while(ch == 'Y');
}
}

Related

How to calculate sum of elements of an array

I have this code where I'm able to calculate the average of marks but unable to calculate the sum and percentage.
And I want to print the name of the student under student name but I'm getting only the student number.
I tried understand more about these, but was unable to get through.
Could you please help me out?
package cube;
import java.io.*;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
String arrayOfNames[] = new String[nos];
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
DB[i][3] = (int) (DB[i][0] + DB[i][1] + DB[i][2] / 3); //calculating the Average Marks of Each Student
DB[i][4] = (int) (DB[i][0] + DB[i][1] + DB[i][2]);
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}
You are initializing your arrayOfNames array to a length of zero always. You should be initializing it once you get the value of the variable nos ( similar to your initialization of 2d array DB)
You are creating the array of names, i.e, arrayOfNames as an array of length 0 because nos is initially zero.
Observe this:
int DB[][],nos=0; //nos is initialized to 0
String arrayOfNames[] = new String[nos]; //arrayOfNames is of size = nos,which is in turn equal to 0, hence arrayOfNames is basically an array which can't hold anything.
instead do this: just declare arrayOfNames and don't initialize it. ==> String arrayOfNames[];
define the string size after you accept the size, i.e, nos. So it should be as follows:
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
arrayOfNames[] = new String[nos]; //now define the size
...
This would ensure that the string is accessible outside the Input() function as well as is defined with a valid size.
Following corrections can make your code run..
package testProgram;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
//here initaialise reference will null
String arrayOfNames[] = null;
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
//create string array object here
arrayOfNames = new String[nos];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
//take extra variable that holds total, it increases the readability of the code
int total = DB[i][0] + DB[i][1] + DB[i][2];
DB[i][3] = (total) / 3; //calculating the Average Marks of Each Student
DB[i][4] = total;
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}
Arrays are not dynamic. either you declare its size before hand or you use Arraylist..
boolean loopNaming = true;
int i = 0;
//you are creating array of zero size, use ArrayList instead
// String[] name = new String[i];
ArrayList<String> nameList = new ArrayList<>();
while (loopNaming == true) {
System.out.printf("Enter name of student or done to finish: ");
String name = keyboard.nextLine();
//check if name is 'done'
if (name.equals("done")) {
loopNaming = false;
} else {
nameList.add(name);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
//nextLine positions cursor to next line
keyboard.nextLine();
}
i = i + 1;
}
System.out.println(nameList);

My scanner class java code has a exception that is a error

I get this error when running my code, please help.
Exception in thread "main" java.util.InputMismatchException
I would appreciate any fixes you could provide to the code overall.
When I input data like weight in this case, it is full of mistakes and it's annoying.
package howto;
import java.util.Scanner;
public class Howto {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
double weightkg [] = new double [30];
double weightkgEndOfMonth [] = new double [30];
String name [] = new String [30];
double weightDifference [] = new double[30];
for (int i = 0; i<31; i++)
{
System.out.println("Input name: ");
String scanner1 = sc1.nextLine();
name [i] = scanner1;
System.out.println("Input weight: ");
double scanner2 = sc2.nextDouble();
if(!sc1.hasNextDouble())
{
System.out.println("Invalid Weight!. Start Again");
} else
{
weightkg[i] = scanner2;
}
System.out.println("Name: " + name[i]);
System.out.println("weight : " + weightkg[i]);
}
for (int i = 0; i<31; i++)
{
System.out.println("Input weight at the end of month: ");
double scanner2 = sc2.nextDouble();
if(!sc1.hasNextDouble())
{
System.out.println("Invalid Weight!. Start Again");
} else
{
weightkgEndOfMonth[i] = scanner2;
}
weightDifference [i] = weightkg[i] - weightkgEndOfMonth[i];
if(weightDifference[i]>2.5)
{
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Rise");
}
if(weightDifference[i]> -2.5)
{
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Fall");
}
}
}
}
Error Message:
run:
Input name:
Test
Input weight:
90
10
Name: Test
weight : 90.0
Input name:
Input weight:
Test1
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at howto.Howto.main(Howto.java:45)
Java Result: 1
BUILD SUCCESSFUL (total time: 16 seconds)
There are a few issues which stand out...
First...
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
You don't need multiple scanners, they are reading from the same stream anyway, better to use just one and reduce the complexity.
Next...
String scanner1 = sc1.nextLine();
name [i] = scanner1;
System.out.println("Input weight: ");
double scanner2 = sc2.nextDouble();
if(!sc1.hasNextDouble())
{
System.out.println("Invalid Weight!. Start Again");
} else
{
weightkg[i] = scanner2;
}
When using nextDouble, the buffer still contains a newline marker, meaning that the next time you use nextLine, it will return a blank String and move on.
Also, hasNextDouble seems to be waiting for data, but you've already read the double value from the buffer, leaving the dangling new line. In my test, this was causing issues with the program waiting for more input.
I "solved" the basic problem by doing something like this...
String scanner1 = sc1.nextLine();
name [i] = scanner1;
System.out.println("Input weight: ");
double scanner2 = sc1.nextDouble();
weightkg[i] = scanner2;
sc1.nextLine();
Now this "will" work, but it's not the best solution. A "different" approach might be to read the weight in as a String and attempt to parse it as a double, this gives you the chance to trap the invalid input and handle it in a more appropriate manner, for example...
System.out.println("Input name: ");
String scanner1 = sc1.nextLine();
name[i] = scanner1;
boolean done = false;
double weight = 0;
do {
System.out.println("Input weight: ");
String input = sc1.nextLine();
try {
weight = Double.parseDouble(input);
done = true;
} catch (NumberFormatException nfe) {
System.out.println("!! Invalid value");
}
} while (!done);
weightkg[i] = weight;
System.out.println("Name: " + name[i]);
System.out.println("weight : " + weightkg[i]);
}
you have some logical mistakes in your code. after every line i mention them.
import java.util.Scanner;
public class HowTo {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in); // you need only 1 scanner
double weightkg[] = new double[30];
double weightkgEndOfMonth[] = new double[30];
String name[] = new String[30];
double weightDifference[] = new double[30];
for (int i = 0; i < 30; i++) { // need to iterate from 0 index to 29
System.out.print("Input name: ");
String scanner1 = sc1.nextLine();
name[i] = scanner1;
System.out.print("Input weight: ");
if (!sc1.hasNextDouble()) {
System.out.println("Invalid Weight!. Start Again");
} else {
weightkg[i] = sc1.nextDouble();// if it has double then read it
}
System.out.println("Name: " + name[i]);
System.out.println("weight : " + weightkg[i]);
sc1.nextLine();
}
for (int i = 0; i < 30; i++) {// need to iterate from 0 index to 29
System.out.println("Input weight at the end of month: ");
if (!sc1.hasNextDouble()) {
System.out.println("Invalid Weight!. Start Again");
} else {
weightkgEndOfMonth[i] = sc1.nextDouble();// read double here
}
weightDifference[i] =weightkgEndOfMonth[i]- weightkg[i] ;// weight difference is (final weight- initial weight)
if (weightDifference[i] > 2.5) {
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Rise");
}
if (weightDifference[i] < -2.5) {// fall if weight less than 2.5
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Fall");
}
}
}
}
Now it is working fine.

How to add more variables inside of loops java

Have each department's number of computers stored in variables. Have the program store the values in variables, calculate the total and average computers and display them.
example output:
Chemistry: 4
Physics: 8
Music: 2
Math lab: 12
Total: 26
Average: 6.5
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What is the name of your first class?");
String class1 = sc.nextLine();
System.out.print("What is the name of your second class?");
String class2 = sc.nextLine();
System.out.print("What is the name of your third class?");
String class3 = sc.nextLine();
System.out.print("What is the name of your fourth class?");
String class4 = sc.nextLine();
System.out.print(" \n\n");
System.out.println("How many computers are in each class?");
System.out.print(class1 + ": \t");
int class1comp = sc.nextInt();
System.out.print(class2 + ": \t");
int class2comp = sc.nextInt();
System.out.print(class3 + ": \t");
int class3comp = sc.nextInt();
System.out.print(class4 + ": \t");
int class4comp = sc.nextInt();
int sum = class1comp + class2comp + class3comp + class4comp;
double avg = sum / 4.0;
System.out.print(" \n\n");
System.out.println("\n\n" + class1 + ":\t" + class1comp);
System.out.println(class2 + ":\t" + class2comp);
System.out.println(class3 + ":\t" + class3comp);
System.out.println(class4 + ":\t" + class4comp);
System.out.println("\n");
System.out.println("Total:\t\t" + sum);
System.out.println("Average:\t" + avg);
}
}
After unit 2: Allow the user to add more departments.
I want the user to be able to add more classes until they say stop. Then later ask how many computers each class needs. Then display them, add them to the sum and average.
This should work for your purposes , it uses an ArrayList for the class names and an array of integers for the grades. It uses the AddOrdinal method taken from this answer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> stringList = new ArrayList<>();
String capture;
int count =1;
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
while (!((capture = scan.nextLine()).toLowerCase().equals("stop"))) {
count++;
stringList.add(capture);
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
}
System.out.println("How many computers are in each class?");
int[] intList = new int[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
String className = stringList.get(i);
System.out.println(className + "\t:");
intList[i] = (scan.nextInt());
}
scan.close();
Arrays.stream(intList).sum();
int sum = Arrays.stream(intList).sum();
double average = (double)sum/intList.length;
/*
Output goes here
*/
}

Inserting values into two array using scanner class in java

import java.util.Scanner;
public class Demo3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many friends: ");
int numOfFriends = Integer.parseInt(scan.nextLine());
String arrayOfNames[] = new String[numOfFriends];
long income[] = new long[numOfFriends];
for (int i = 0; i < arrayOfNames.length; i++)
{
System.out.print("\nEnter the name of friend " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
for(int j = 0; j<arrayOfNames.length;j++)
{
System.out.print("\nEnter the income of friend " + (j+1) + " : ");
income[j] = scan.nextLong();
}
}
}
}
This is my code, I want to take input name from user then the income of that person then again the name of another person
The above code is not arranged properly, I think there's problem in the for loop the sample output should be like:
Enter how many friends: 2
Enter name of friend 1 : #############
Enter income of friend 1 : ##############
Enter name of friend 2 : #############
Enter income of friend 2 : ##############
You should take inner for loop out.
import java.util.Scanner;
public class Demo3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many friends: ");
int numOfFriends = Integer.parseInt(scan.nextLine());
String arrayOfNames[] = new String[numOfFriends];
long income[] = new long[numOfFriends];
for (int i = 0; i < arrayOfNames.length; i++)
{
System.out.print("\nEnter the name of friend " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
for(int j = 0; j<arrayOfNames.length;j++)
{
System.out.print("\nEnter the income of friend " + (j+1) + " : ");
income[j] = scan.nextLong();
}
scan.close();
}
}
Besides, if you want to enter them in order, you should just use one for loop
import java.util.Scanner;
public class Demo3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many friends: ");
int numOfFriends = Integer.parseInt(scan.nextLine());
String arrayOfNames[] = new String[numOfFriends];
long income[] = new long[numOfFriends];
for (int i = 0; i < arrayOfNames.length; i++)
{
System.out.print("\nEnter the name of friend " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
System.out.print("\nEnter the income of friend " + (i+1) + " : ");
income[i] = scan.nextLong();
scan.nextLine();
}
scan.close();
}
}
As a side note, don't forget to close() scanner after its task is completed.

Printing out elements at certain indexes in vectors in Java

This is probably very basic stuff, but I am not too sure how I should ask questions because I am very new to this, so here goes.
I am practicing vectors and what we can do to them. I have prompted the user for the elements of the vectors (per my directions) among other things successfully. For my next step, I have to "print out the element at index i in each of the two vectors." I was given the methods which I am supposed to use, but the explanations I saw of them were very unclear. Here they are:
Object get (int which)
Object remove (int which)
set (int index, object element)
How would I get the system output to be the element at the index i?
package vectorusage;
import java.util.*;
public class VectorUsage {
public static void main(String[] args) {
Vector a = new Vector ();
Vector b = new Vector ();
System.out.println (a);
System.out.println (b);
Scanner input = new Scanner(System.in);
String first;
System.out.print("Please enter 4 strings.");
first = input.next();
a.add (first);
String second;
second = input.next();
a.add (second);
String third;
third = input.next();
a.add (third);
String fourth;
fourth = input.next();
a.add (fourth);
String fifth;
System.out.print("Please enter 4 more strings.");
fifth = input.next();
b.add (fifth);
String sixth;
sixth = input.next();
b.add (sixth);
String seventh;
seventh = input.next();
b.add (seventh);
String eighth;
eighth = input.next();
b.add (eighth);
System.out.println("Vector a is size " + (a.size()) + " and contains: " + (a));
System.out.println("Vector b is size " + (b.size()) + " and contains: " + (b));
int i;
System.out.println("Please enter an integer.");
i = input.nextInt();
System.out.println("Element at index " + i + " in Vector a is: " + ;
Avoid using vectors, they are deprishiated. Use ArrayList instead.
Using a for loop you can simplify your code like below,
(Please note, this code does not validate user input or do error handling)
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Please enter 8 strings.");
for(int i = 1; i <= 8; i++) {
System.out.print("Please enter strings #" + i + ": ");
numbers.add(input.nextInt());
}
for(int j = 0; j < numbers.size(); j++) {
System.out.println("Number at index " + j + " is " + numbers.get(j));
}
}
}
I usually use a mix of while and for loop. The while loop is used to add the user input into the vector. The for loop prints out the elements of the vector using index i. I've set it to print all the elements of the vector but you can modify it by using if conditions. Here's my code, hope it helps!
import java.util.*;
import java.io.*;
public class VectorUsage {
public static void main(String[]args) {
Scanner input=new Scanner(System.in);
Vector a=new Vector();
int count =0;
while(count<4)
{
System.out.print("Enter a string: ");
a.addElement(input.nextLine());
count++;
}
for(int i=0;i<a.size();i++)
{
System.out.println(a.elementAt(i));
}
Vector b=new Vector();
int count1=0;
while(count1<4)
{
System.out.print("Enter a string: ");
b.addElement(input.nextLine());
count1++;
}
for(int i=0;i<b.size();i++)
{
System.out.println(b.elementAt(i));
}
}
}

Categories