I am attempting to make this code take each variable, pass it down to the builder method and have it create a full sentence based on what was input by the user. The builder method passes it back to the main method and prints out the complete sentence consisting of "subject + verb + adjective + object + adverb".
Do I need to store each user input into an ArrayList? If so, how do I prompt the user for each new sentence piece? I've tried using for loops, however it just asks me for the first line 5 times, assuming I make the Array[5].
package assignment.pkg4.pkg3.string.input;
import java.util.Scanner;
public class Assignment43StringInput {
private static Scanner scanner = new Scanner( System.in );
public static void main(String[] args) {
System.out.print("Enter a subject: ");
String subject = scanner.nextLine();
System.out.print("Enter a verb: ");
String verb = scanner.nextLine();
System.out.print("Enter an adjective: ");
String adjective = scanner.nextLine();
System.out.print("Enter an object: ");
String object = scanner.nextLine();
System.out.print("Enter an adverb: ");
String adverb = scanner.nextLine();
System.out.print(builder(text));
}
public static String builder(String text) {
String sentence = subject + verb + adjective + object + adverb;
return sentence;
}
}
If I understand your question correctly, you want to use one unique structure instead of one variable for each input. If you know your size is always going to be 5 and will not change, then you can use String[]. Alternatively, you can use a List.
But if you want to know exactly what is what, you might want to give Map a go. I'll explain it with an example:
public class Assignment43StringInput {
private static Scanner scanner = new Scanner( System.in );
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
System.out.print("Enter a subject: ");
map.put("subject", scanner.nextLine());
System.out.print("Enter a verb: ");
map.put("verb", scanner.nextLine());
System.out.print("Enter an adjective: ");
map.put("adjective", scanner.nextLine());
System.out.print("Enter an object: ");
map.put("object", scanner.nextLine());
System.out.print("Enter an adverb: ");
map.put("adverb", scanner.nextLine());
System.out.print(builder(map));
}
public static String builder(Map<String,String> map) {
return map.get("subject") + " " + map.get("verb") + " " + map.get("adjective") + " " + map.get("object") + " " + map.get("adverb");
}
}
This way you can easily reorder your sentence if you need to, and even add more elements to it.
You do not need array or Map or whatever. To properly achieve your requirement, you just need to make your builder (I'd rather call it buildSentence, as method is supposed to be a verb) accept corresponding arguments:
public static String buildSentence(String subject,
String verb,
String adj,
String obj,
String adverb) {
return subject + " " + verb + " "
+ adjective + " " + object + " " + adverb;
}
and you simply call it with your variables passed in correspondingly:
System.out.print(buildSentence(subject, verb, adjective, object, adverb));
Regarding use of Array/ ArrayList/ Map, given you have a very well-defined sets of values to use, you shouldn't use these data structure as they are too versatile and making your code hard to read and error-prone. Declare a simple class to serve for struct-like purpose is a much better choice:
class Sentence {
public String subject;
public String verb;
public String adjective;
public String object;
public String adverb;
}
In your main:
public static void main(String[] args) {
Sentence sentence = new Sentence();
System.out.print("Enter a subject: ");
sentence.subject = scanner.nextLine();
// do the same for other values
System.out.print(buildString(sentence));
}
public static String buildString(Sentence sentence) {
return sentence.subject + " "
+ sentence.verb + " "
+ sentence.adjective + " "
+ sentence.object + " "
+ sentence.adverb;
}
See how much clearer and readable the code become?
A even better change is to move buildString() above as a member method of Sentence.
Related
My program is supposed to output labels. All of the input works when I run it but the output is wrong and all that it outputs is null, for every part of the label except for the box number.
import javax.swing.JOptionPane;
public class MailOrderpractice {
static String nameAddressArray[] = new String[7];
public static void main(String[] args) {
// declare variables
String nameAddressArray[] = new String[7];
String numBoxesInput;
int numBoxes;
String enterAnother = "Y";
int counter;
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
// begin outer loop logic that determines when user is finished entering mail orders
while (enterAnother.equalsIgnoreCase("Y")) {
counter = 1;
// begin the inner loop to display a label and increment the counter
while (counter <= numBoxes) {
System.out.println(nameAddressArray[0] + " " + nameAddressArray[1] + " " + nameAddressArray[2]);
System.out.println(nameAddressArray[3]);
System.out.println(nameAddressArray[4] + ", " + nameAddressArray[5] + " " + nameAddressArray[6]);
System.out.println("Box " + counter + " of " + numBoxes);
System.out.println();
counter = counter + 1;
}
enterAnother = " "; // initialize the variable to something other than "Y" before sending the prompt
enterAnother = JOptionPane.showInputDialog("Do you want to produce more labels? Y or N");
while (!enterAnother.equalsIgnoreCase("Y") && !enterAnother.equalsIgnoreCase("N")) {
enterAnother = JOptionPane.showInputDialog(null, "Invalid Response. Please enter Y or N.",
"DATA ENTRY ERROR", JOptionPane.ERROR_MESSAGE);
} // end while
if (enterAnother.equalsIgnoreCase("Y")) {
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
} // end if
} // end while
System.exit(0);
}
public static void getLabelData() {
nameAddressArray[0] = JOptionPane.showInputDialog("Enter title (Mr., Ms., Dr., etc.): ");
nameAddressArray[1] = JOptionPane.showInputDialog("Enter first name: ");
nameAddressArray[2] = JOptionPane.showInputDialog("Enter lastname: ");
nameAddressArray[3] = JOptionPane.showInputDialog("Enter street address: ");
nameAddressArray[4] = JOptionPane.showInputDialog("Enter city: ");
nameAddressArray[5] = JOptionPane.showInputDialog("Enter state (IL, MO, etc.): ");
nameAddressArray[6] = JOptionPane.showInputDialog("Enter zip (e.g., 62025): ");
}
The array nameAddressArray is declared twice. You have a static field
static String nameAddressArray[] = new String[7];
You also have a local variable with the same name in the main method.
String nameAddressArray[] = new String[7];
Your main method is putting values into the second array, whereas your getLabelData method is using the values from the static field, and these are all the initial value (null).
One way to solve this problem is to just get rid of the local variable. Then both parts of the code will use the same array.
Alternatively, you could get rid of the static field, and pass the array as a parameter to the getLabelData method. This is probably a better solution, as mutable static fields are generally not a good idea.
you just need to comment this line into Main method(),
// String nameAddressArray[] = new String[7];
The code is fine, but when I need to take the variables out of the functions and put them into the public static void, it says the variable cannot be found. Anybody know how to solve this issue?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
System.out.println("Greetings, " + String(s) + ". " +
String(j) +"!" + " You are about " + int(z) + " years old");
}
public static String fNameGenerator(String s){
Scanner scan1 = new Scanner(System.in);
System.out.println("Please enter your first name: ");
String first = scan1.next();
s = first.substring(0,1).toUpperCase();
return s;
}
public static String LastName(String j){
Scanner scan2 = new Scanner(System.in);
System.out.println("Please enter you last name: ");
String second = scan2.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
j = y.substring(0,1).toUpperCase();
return j;
}
public static int age(int z){
Scanner scan3 = new Scanner(System.in);
System.out.println("Please enter your year of birth: ");
int third = scan3.nextInt();
z = (2015 - third);
return z;
}
}
You are not calling any of the methods, so how do you expect them to return something?
Two things to remember:
just because you wrote return s at the end of a method, it does not mean you can access s outside of this method. There's something called scopes in java, that means that a variable exists only on the scope it's define in- in your case - inside the methods. if you want it to exist outside - take the returned value and do something with it.
declaring the methods does nothing until you actually call them
so in order to access these variables, you need to do something like this:
public static void main(String[] args) {
String s = fNameGenerator();
String j = LastName();
int z = age();
System.out.println("Greetings, " + s + ". " + j +"!" +" You are about " + z + " years old");
}
one more thing you can see that I did there- you don't need to pass anything to your methods, as you are not doing anything with the given values before re-setting them. just make sure you declare the fields inside. for example your age method should look like:
public static int age(){
Scanner scan3 = new Scanner(System.in);
System.out.println("Please enter your year of birth: ");
int third = scan3.nextInt();
int z = (2015 - third);
return z;
}
There is a compile error in your code
System.out.println("Greetings, " + String(s) + ". " + String(j) +"!" +" You are about " + int(z) + " years old");
If you're trying to call the methods then replace
String(s) --> fNameGenerator(s)
String(j) --> LastName(j)
int(z) --> age(z)
Have the s,j,z as the local variables or static members.
or remove the arguments passing to the method as you're getting input from scanner
So my goal is to rearrange a string that is inputted into the program so that it outputs the same info but in a different order. The input order is firstName middleName, lastName, emailAddress and the intended output is lastName, firstName first letter of middleName .
For example the input
John Jack,Brown,JJB#yahoo.com
would output
Brown, John J .
Here's what I have so far
import java.util.Scanner;
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
String entireLine = keyboard.nextLine();
String[] fml = entireLine.split(",");
String newName = fml[0].substring(7);
String newLine = fml[1] + "," + newName + ".";
System.out.println(newLine);
}
public String substring(int endIndex) {
return null;
}
}
I can't figure out how to separate the firstName and middleName so I can substring() the first letter of the middleName followed by a .
This meets your required output.
import java.util.Scanner;
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
String entireLine = keyboard.nextLine();
String[] fml = entireLine.split(","); //seperate the string by commas
String[] newName = fml[0].split(" "); //seperates the first element into
//a new array by spaces to hold first and middle name
//this will display the last name (fml[1]) then the first element in
//newName array and finally the first char of the second element in
//newName array to get your desired results.
String newLine = fml[1] + ", " + newName[0] + " "+newName[1].charAt(0)+".";
System.out.println(newLine);
}
}
Check this.
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
System.out.println(rearrangeName(keyboard.nextLine()));
}
public static String rearrangeName(String inputName) {
String[] fml = inputName.split(" |,"); // Separate by space and ,
return fml[2] + ", " + fml[0] + " " + fml[1].charAt(0) + ".";
}
}
You need to delimit the string for spaces as well. And don't forget the alternate "|" character. Try the following.
String[] fml = entireLine.split(" |, ");
Hi guys I'm currently creating a program that allows the user to create an array, search an array and delete an element from an array. Looking at the LibraryMenu method, the first case where you create an array in the switch statement works fine, however the other ones create a "cannot find symbol error" when I try to compile.
My question is I want the search and delete functions to refer to the first switch case - the create Library array. Any help is appreciated, even if its likely from a simple mistake.
import java.util.*;
public class EnterLibrary
{
public static void LibraryMenu()
{
java.util.Scanner scannerObject =new java.util.Scanner(System.in);
LibraryMenu Menu = new LibraryMenu();
Menu.displayMenu();
switch (scannerObject.nextInt() )
{
case '1':
{
System.out.println ("1 - Add Videos");
Library[] newLibrary;
newLibrary = createLibrary();
}
break;
case '2':
System.out.println ("2 - Search Videos");
searchLibrary(newLibrary);
break;
case '3':
{
System.out.println ("3 - Change Videos");
//Change video method TBA
}
break;
case '4':
System.out.println ("4 - Delete Videos");
deleteVideo(newLibrary);
break;
default:
System.out.println ("Unrecognized option - please select options 1-3 ");
break;
}
}
public static Library[] createLibrary()
{
Library[] videos = new Library[4];
java.util.Scanner scannerObject =new java.util.Scanner(System.in);
for (int i = 0; i < videos.length; i++)
{
//User enters values into set methods in Library class
System.out.print("Enter video number: " + (i+1) + "\n");
String number = scannerObject.nextLine();
System.out.print("Enter video title: " + (i+1) + "\n");
String title = scannerObject.nextLine();
System.out.print("Enter video publisher: " + (i+1) + "\n");
String publisher = scannerObject.nextLine();
System.out.print("Enter video duration: " + (i+1) + "\n");
String duration = scannerObject.nextLine();
System.out.print("Enter video date: " + (i+1) + "\n");
String date= scannerObject.nextLine();
System.out.print("VIDEO " + (i+1) + " ENTRY ADDED " + "\n \n");
//Initialize arrays
videos[i] = new Library ();
videos[i].setVideo( number, title, publisher, duration, date );
}
return videos;
}
public static void printVidLibrary( Library[] videos)
{
//Get methods to print results
System.out.print("\n======VIDEO CATALOGUE====== \n");
for (int i = 0; i < videos.length; i++)
{
System.out.print("Video number " + (i+1) + ": \n" + videos[i].getNumber() + "\n ");
System.out.print("Video title " + (i+1) + ": \n" + videos[i].getTitle() + "\n ");
System.out.print("Video publisher " + (i+1) + ": \n" + videos[i].getPublisher() + "\n ");
System.out.print("Video duration " + (i+1) + ": \n" + videos[i].getDuration() + "\n ");
System.out.print("Video date " + (i+1) + ": \n" + videos[i].getDate() + "\n ");
}
}
public static Library searchLibrary( Library[] videos)
{
//User enters values to setSearch
Library titleResult = new Library();
java.util.Scanner scannerObject =new java.util.Scanner(System.in);
for (int n = 0; n < videos.length; n++)
{
System.out.println("Search for video number:\n");
String newSearch = scannerObject.nextLine();
titleResult.getSearch( videos, newSearch);
if (!titleResult.equals(-1))
{
System.out.print("Match found!\n" + newSearch + "\n");
}
else if (titleResult.equals(-1))
{
System.out.print("Sorry, no matches found!\n");
}
}
return titleResult;
}
public static void deleteVideo( Library[] videos)
{
Library titleResult = new Library();
java.util.Scanner scannerObject =new java.util.Scanner(System.in);
for (int n = 0; n < videos.length; n++)
{
System.out.println("Search for video number:\n");
String deleteSearch = scannerObject.nextLine();
titleResult.deleteVideo(videos, deleteSearch);
System.out.print("Video deleted\n");
}
}
public static void main(String[] args)
{
Library[] newLibrary;
new LibraryMenu();
}
}
I think this is a terrible design. You've mingled too many things together: user interface, logic, data structure.
Start by isolating your LibraryArray from the LibraryMenu. You shouldn't see any switch or input or output in it at all.
Java's an object-oriented language. Start thinking about your system in terms of objects. I don't see classes like Video and VideoCatalog. You'll find this system to be a lot easier to implement if you created them.
Looks like you've got a start:
package model;
public class Video {
private Long id;
private String title;
private String publisher;
private int durationSeconds;
private Date publicationDate;
// add ctors, getters, etc. Immutable? Could be...
// equals, hash code, toString
}
Keep your VideoCatalog free of user interface or I/O:
package model;
public interface VideoCatalog {
List<Video> find();
List<Video> find(String title);
List<Video> find(Date startDate, Date endDate) ;
Long save(Video video);
void update(Video video);
void delete(Video video);
}
Now you can have an implementation that uses any data structure you want:
package model;
public class VideoCatalogImpl implements VideoCatalog {
private Set<Video> videos;
// add implementations here.
}
You need to move the declaration of that array variable out of the scope of the first case, and up to someplace where the other cases can see it. Given the current structure of your code, it would be most convenient to make it a static member of the class -- i.e.,
public class EnterLibrary
{
Library[] newLibrary;
Then all the static methods of this class could share the one variable. But be sure to remove all the other declarations of the variable that appear in other methods, otherwise they still will be using separate variables, and bugs like that can be very hard to track down!
Library[] newLibrary; is defined in your case '1' only, you should define it in a wider scope, like your LibraryMenu method. Also, the Library[] newLibrary declared in your main is not called anywhere, and maybe you should add Null check in your search, print an delete methods.
Your constructor class must have the same name of your class and not have any modifier keywords in it. Also, when you create an object of your class, it wont use the static methods declared in there.
A note: when you work with your own declared arrays, it would be better that you declare a int variable to keep track of the actual size of the array. Note that array.length returns how many items the array can have, not how many items it already has.
I would redesign your definitions (not the code) to something like this:
//Note I changed the classname from EnterLibrary to LibraryMenu. Apparently you
//wanted a LibraryMenu class.
public class LibraryMenu {
private final int MAX_ITEMS = 50;
private Library[] videos;
private int size = 0;
//remove the static and void keyworkds from this method, so this will be
//the constructor.
public LibraryMenu() {
videos = new Library[MAX_ITEMS];
//the rest of your code here...
switch (scannerObject.nextInt()) {
//if you're reading an int, keep the constants in the case as int.
case 1:
//no need of brackets inside a case statement
//check that you can add an item in your Library array
//also, its not good to ask the user to add 4 (or N) videos in 1 round :).
if (size < MAX_ITEMS) {
Library video = addVideo();
videos[size++] = video;
}
break;
case 2:
break;
}
}
//remove the static keyword so the instance of your class can call the method.
public Library addVideo() {
Library video = new Library();
//your code to read data goes here...
//then fulfill the video and return it.
return video;
}
//The Library[] videos is declared in your class, so all other methods could
//use it without having to receive it as a parameter.
public void printVidLibrary() {
//your code goes here...
}
public Library searchLibrary() {
//your code goes here...
}
public void deleteVideo( Library[] videos) {
//your code goes here...
}
public static void main(String[] args) {
new LibraryMenu();
}
}
Try this,
Declare Library[] newLibrary; as an instance variable (at class scope), or as local variable before the switch statement.
This is my Code that I have so far:
import java.util.*;
public class VoteRecorder
{
// Variables and instance variables
public static String nameCandidatePresident1;
public static String nameCandidatePresident2;
public static String nameCandidateVicePresident1;
public static String nameCandidateVicePresident2;
public static int votesCandidatePresident1;
public static int votesCandidatePresident2;
public static int votesCandidateVicePresident1;
public static int votesCandidateVicePresident2;
private int myVoteForPresident;
private int myVoteForVicePresident;
public VoteRecorder()
{
nameCandidatePresident1 = "null";
nameCandidatePresident2 = "null";
nameCandidateVicePresident1 = "null";
nameCandidateVicePresident2 = "null";
votesCandidatePresident1 = 0;
votesCandidatePresident2 = 0;
votesCandidateVicePresident1 = 0;
votesCandidateVicePresident2 = 0;
myVoteForPresident = 0;
myVoteForVicePresident = 0;
}
public void setCandidatesPresident(String name1, String name2)
{
nameCandidatePresident1 = name1;
nameCandidatePresident2 = name2;
}
public void setCandidatesVicePresident(String name1, String name2)
{
nameCandidateVicePresident1 = name1;
nameCandidateVicePresident2 = name2;
}
public static void resetVotes()
{
votesCandidatePresident1 = 0;
votesCandidatePresident2 = 0;
votesCandidateVicePresident1 = 0;
votesCandidateVicePresident2 = 0;
}
public static String getCurrentVotePresident()
{
return nameCandidatePresident1 + ":" + votesCandidatePresident1 + "\n" +
nameCandidatePresident2 + ":" + votesCandidatePresident2;
}
public static String getCurrentVoteVicePresident()
{
return nameCandidateVicePresident1 + ":" + votesCandidateVicePresident1 + "\n" +
nameCandidateVicePresident2 + ":" + votesCandidateVicePresident2;
}
public void getAndConfirmVotes()
{
}
private String getVotes()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("please vote for a President or vice president " + nameCandidatePresident1 + ", " + nameCandidatePresident2 + ", " + nameCandidateVicePresident1
+ " or " + nameCandidateVicePresident2);
String presidentVote = keyboard.nextLine();
if (presidentVote.equalsIgnoreCase(nameCandidatePresident1))
return nameCandidatePresident1;
if(presidentVote.equalsIgnoreCase(nameCandidatePresident2))
return nameCandidatePresident1;
System.out.println("please vote for a Vice president " + nameCandidateVicePresident1 + " or" + nameCandidateVicePresident2);
String vicePresidentVote = keyboard.nextLine();
if(vicePresidentVote.equalsIgnoreCase(nameCandidateVicePresident1))
return nameCandidateVicePresident1;
if(vicePresidentVote.equalsIgnoreCase(nameCandidateVicePresident2))
return nameCandidateVicePresident2;
else
return "not a valid vote";
}
private boolean confirmVotes()
{
System.out.println("Your vote for President is:");
System.out.println("your vote for Vice President is:");
System.out.println("Is this correct? Yes or No?");
Scanner keyboard = new Scanner(System.in);
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("Yes"))
return true;
else
return false;
}
private void recordVote()
{
puscode: If confirmVotes returns true, take the nameCandidate, and ++ to votesCandidate of the same type
Copy this If statement four times, one for each of the candidates, 2 president and 2 vp.
Else or If confirmvotes returns false, put output saying that the votes were not confirmed.
}
}
Say i had all this code, lets look at the method getVotes() and confrimVotes(), in getVotes() the user picks a candidate and than that candidate is returned. How would i get that return statement to show up else where in other methods? like in confirmVote() i want to do this
System.out.println("Your vote for President is: (PresidentialCandidate return statement");
But how can i do that?
This is not a direct answer to your question, but I think your code could be made a lot simpler by harnessing some of the power of object-oriented programming.
You are storing multiple types of information about 4 candidates for different positions as separate variables, and it's making your class very unwieldy.
A (in my opinion) better approach would be to have e.g. a Candidate class to store information about a single candidate, and then your classes could look as follows:
class Candidate {
String Name;
int votes;
}
class VoteRecorder {
Candidate[] presidents;
Candidate[] vicePresidents;
Candidate myVoteForPresident; //Or even make these both ints.
Candidate myVoteForVicePresident;
}
The classes can be further refined, but this will be a start. Any time you see multiple pieces of information that describe the same entity being repeated multiple times, it's a good indication that you could simplify your life by adding a class to represent them together instead.
Edit (to answer question specifically):
If you want to do effectively the following:
System.out.println("Your vote for President is: (PresidentialCandidate return statement");
You can write something like this:
String voteResult = getVotes();
System.out.println("Your vote for President is: " + voteResult);
Or in one line:
System.out.println("Your vote for President is: " + getVotes());
Each time you run this code though, it will prompt the user for input. If you want to save the result until next time as well, you will have to save it to an attribute, e.g. by having a string in your class, and assigning the value to it first. Then just use that later instead of the local variable voteResult.