So I am creating an MVC Random Word generator that submits user input and retrieves it. I am having a hard time with my RandomWordModel class. I created an ArrayList of strings that are supposed to store user input and then retrieve it one the user presses the "Retrieve Word" button.
public class RandomWordModel {
private ArrayList<String> randomWords;
public RandomWordModel()
{
}
public String putWord(String userWords) {
randomWords.add(userWords);
return userWords;
}
public String getWord() {
Collections.shuffle(randomWords);
String userInput = randomWords.get(randomWords.size());
return userInput;
}
This is what I have so far and it is not really working for some reason. I'm not sure if I am doing this wrong but if anyone could help that would be great.
First of all you forget to initialize the arraylist. Try to initialize ArrayList as :
List<String> randomWords= new ArrayList<String>();
The working snippet is :
private ArrayList<String> randomWords = new ArrayList<String>();;
public static void main(String args[]) {
rep1 obj = new rep1();
obj.putWord("user1");
obj.putWord("user2");
obj.putWord("user3");
System.out.println(obj.randomWords);
Object[] object = obj.getWord();
System.out.println(Arrays.toString(object));
}
public void RandomWordModel() {
}
public String putWord(String userWords) {
randomWords.add(userWords);
return userWords;
}
public Object[] getWord() {
Collections.shuffle(randomWords);
return randomWords.toArray();
}
I'm not sure why you would want to create a full MVC model for that.
I would personally go with something simpler like below:
import java.util.Scanner;
import java.util.Random;
public class test2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Random rand = new Random();
System.out.print("Enter string > ");
String input = sc.nextLine();
String words[] = new String[input.length()];
if(!input.isBlank())
words = input.split(" ");
System.out.println(words[rand.nextInt(words.length)]);
}
}
[Edited Code Below]
As per your requirement you can split the above code into MVC rather easily. It is very much just rearranging the codes.
RandomWordView.java
import java.util.Scanner;
public class RandomWordView{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter string > ");
String input = sc.nextLine();
RandomWordModel rwm;
if(!input.isBlank()){
rwm = new RandomWordModel(input.split(" "));
System.out.println(RandomWordController.getRandomWord(rwm));
}
}
}
RandomWordModel.java
public class RandomWordModel{
String wordArr[];
public RandomWordModel(String wordArr[]){
this.wordArr = wordArr;
}
public String[] getWordArr(){
return this.wordArr;
}
}
RandomWordController.java
import java.util.Random;
public class RandomWordController{
public static String getRandomWord(RandomWordModel x){
Random rand = new Random();
String wordArr[] = x.getWordArr();
return wordArr[rand.nextInt(wordArr.length)];
}
}
As the functionality requirement you provided is rather simple there is really no need for an MVC framework as you can see. The model for your question is simply a String array and the controller only requires a single function of random word which is why my initial recommendation for going simple. Hope this helps you see how it can be converted to MVC nonetheless.
Related
I have two java classes, while one contains the getters and setters the other is a driver class. I need the user input from the scanner in the driver class to be in one of the getters in the first class. The user input has to be a double because it will be used as a formula in the getter.
//First Class
public class shopping
{
String orangeSelected;
public double getOrangeSelected()
{
return (user input makes a formula to be returned to the driver class)
}
public void setOrangeSelected(String orangeSelected)
{
this.orangeSelected = orangeSelected;
}
}
//Driver Class
import java.util.Scanner
public class shoppingApp
{
public static void main(String[] args)
{
Scanner inputOrangeSelected = new Scanner(System.in)
System.out.println("Premium Oranges");
String orangeSelected = inputOrangeSelected.nextLine();
}
}
The problem you are facing is that you are not storing the String "orangeSelected" into an instance of your shopping object. In order to do that, you would would to create an instance of your shopping object, and then call the "setOrangeSelected" method.
Example
Here is how it would look in your driver class:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/* I would recommend changing your shopping class name to Shopping
for correct naming conventions.*/
Shopping shopping = new Shopping();
/* Changed the system out to a question. Not a nessicary change.
All depends on what your program is doing. */
System.out.println("What type of oranges would you like?");
String orangeType = input.nextLine();
// Here you are actually storing the user input into the shopping object.
shopping.setOrangeSelected(orangeType);
}
Once the input is placed in an object, you can take that variable, and call "getOrangeSelected" on it to return the type of orange, like so:
System.out.println(shopping.getOrangeSelected());
Extra Resources
I suggest you look at the Oracle naming conventions for the java language. It is helpful to follow them to improve readability of your code.
Edit
For clarity, I also wanted to add that you have the getter method return the orangeSelected variable, like so:
public double getOrangeSelected() {
return orangeSelected;
}
What would really be best is to put everything in one class, there is no reason to separate 1 class into 2 just to keep getters and setters separate from the rest, it makes no sense. I do wonder if you have misunderstood your assignment.
import java.util.Scanner;
class shoppingApp
{
//since it's an instance field not local to the class it's declared here instead of main
static String orangeSelected = "";
public static void main(String[] args)
{
//orange selected is an odd name for a scanner, just use scan or something similar
Scanner scan = new Scanner(System.in); //note that you were missing a semicolon
System.out.println("Premium Oranges\n"); //include a new line or a space before asking for input, for example with \n
orangeSelected = scan.nextLine();
}
//setter
public static void setOrangeSelected(String str)
{
orangeSelected = str;
}
//getter
public static String getOrangeSelected()
{
return orangeSelected;
}
//Note that all methods and instance fields are static because the main method must be static if you don't understand this yet that's ok.
}
Now if for some reason you absolutely had to use two classes it would look something like this, although I'd note that just copying and pasting my code without understanding it would be cheating.
import java.util.Scanner;
class shoppingApp
{
//normally this shouldn't be public
public static String orangeSelected = "";
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Premium Oranges\n");
orangeSelected = scan.nextLine();
}
}
class gettersAndSetters
{
//setter
public void setOrangeSelected(String str)
{
Main.orangeSelected = str;
}
//getter
public String getOrangeSelected()
{
return Main.orangeSelected;
}
}
I am creating a program in Java for a restaurant. I am using ArrayList but for some reason my starter class doesn't seem to run in the main menu.
This is my starter class:
import java.util.ArrayList;
public class Starter
{
Starter()
{
String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
//System.out.println(myList[]);
}
}
This seems to be correct, but when I try to choose from the Main menu it doesn't seem to work.
Main Menu:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a =input.nextInt();
input.nextLine();
if(a==1)
{
System.out.println("Starter");
Starter OS1=new Starter();
System.out.println("Your starter is "+OS1.myList[]);
}
else if(a==2)
{
System.out.println("Main Course");
MaiinCourse OMC1=new MaiinCourse();
System.out.println("Your MainCourse is "+OMC1.MCname);
System.out.println("The price is "+OMC1.MCprice);
}
else if(a==3)
{
System.out.println("Desert");
Deserrt ODS1=new Deserrt();
System.out.println("Your Desert is "+ODS1.DSname);
System.out.println("The price is "+ODS1.DSprice);
}
else
{
System.out.println("End");
System.out.println("Program Closing");
System.exit(1);
}
}
}
The error I get is:
'.class' expected System.out.println("Your starter is "+OS1.myList[]);
How to fix this?
When I run the main menu it should allow me to choose from the array list.
I did few changes to your code. Now it works. Try and see.
import java.util.Arrays;
import java.util.Scanner;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1)
{
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println("Your starter is " + Arrays.toString(OS1.getMyList()));
}
}
}
class Starter
{
private String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
public String[] getMyList()
{
return myList;
}
}
Your code won't work because you are trying to give an Array values within you class constructor (Starter constructor in this case). This will lead to a RunTime exception because you cannot create Array constants within a constructor. I much more viable approach would be to create a private Array as an attribute for each object that you create of type "Starter". Then you can use something that we call a "Getter" method to get the value of the myList attribute for the instance you're creating. Here's a mini example of how we can change your Starter class structure below:
public class Starter {
private String[] myList = {"Coffee", "Tea", "Somola", "Cake"};
public String[] getterMethod() {
return this.myList;
}
}
Now we have what is called a "Getter" method in Java which will return the private class attribute so that users cannot alter the internal state of the Object. Here is an example of how you will call the Array in your main method:
public class App {
public static void main( String[] args ) throws IOException{
System.out.println("1=Starter");
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int a = input.nextInt();
if(a == 1) {
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println(Arrays.toString(OS1.getterMethod()));
}
}
}
That is a very simplified version of your code that I simply used to illustrate the broader concept. Here is the output:
1=Starter
Enter a number
1
Starter
[Coffee, Tea, Somola, Cake]
We simply call the getterMethod() which will return the value for the private Array that you are looking for.
Actually, your myArray is not visible outside the Starter class, so you have to make it visible by declaring as public, or package default. Here you can take help of Arraylist.
So you can change your class as below :
public class Starter {
// this myList will be visible outside of this class and can be accessed to show menu.
ArrayList<String> myList = new ArrayList<>();
Starter() {
String[] myArray = { "Coffee", "Tea", "Somosas", "Cake" };
for (String str : myArray) {
myList.add(str);
}
//System.out.println(myList);
}
}
and kindly update Your Menu.java class as below :
import java.util.Scanner;
public class Menu {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1) {
System.out.println("Starter : ");
Starter os1 = new Starter();
for (String str : os1.myList) {
System.out.print(str + " ");
}
}
}
}
I have this kind of structure of program.
This program have one function named run(), and the other function named solve().
In this program, I want to get some information from run() and solve().
Also, I want to put these information to one list vector (named information_one_iteration in the following code).
Because this vectors get together to form a matrix (named information in the following code).
That's why I define the information_one_iteration as static variable, and in every new iteration new objects is defined newly.
But, I know this kind of way is not effective!
How can I improve it?
package java_test2;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Random;
public class staticvarTest {
private Random random = new Random();
static ArrayList<ArrayList<String>> information = new ArrayList<ArrayList<String>>();
static ArrayList<String> information_one_iteration = new ArrayList<String>();
public staticvarTest() {
}
public void run() {
for (int i=0; i<10; i++) {
information_one_iteration.add(String.valueOf(i));
solve(); // add two random number generated in function solve()
information.add(information_one_iteration);
information_one_iteration = new ArrayList<String>();
}
print_information(information);
}
public void solve() {
information_one_iteration.add(String.valueOf(random.nextInt()));
information_one_iteration.add(String.valueOf(random.nextInt()));
}
public static void print_information(ArrayList<ArrayList<String>> information) {
for (ArrayList<String> newLine : information) {
ArrayList<String> list_set = newLine;
System.out.println("");
for(String data: list_set) {
System.out.print(data+" ");
}
System.out.println("");
}
System.out.println("");
}
public static void main(String args[]) {
staticvarTest na = new staticvarTest();
na.run();
}
}
Since you are not using static ArrayList<String> information_one_iteration = new ArrayList<String>(); anywhere apart from the run method you can remove it.
I have changed the random variable since it's okay for multiple objects to share it - the behaviour remains the same therefore no need to initialize every time Main object is created.
Change the solve method to take a ArrayList as a parameter too.
print_information looks okay but there is no need for ArrayList<String> list_set = newLine;
I have also made information as a state variable over a static variable so that each instance of the object can have it's own information therefore allowing you to run multiple instances of this class.
I also added a lambda to print the members to give you an idea about them newLine.forEach(data -> System.out.println(data + " "));.
Finally I have used variable names and class names that adhere to Java coding conventions for better readability. Here is one of the style guides which you may follow https://google.github.io/styleguide/javaguide.html
The cleaned up version of your code is below
package com.company;
import java.util.ArrayList;
import java.util.Random;
public class Main {
private static Random random = new Random();
private ArrayList<ArrayList<String>> information = new ArrayList<>();
private void run() {
for (int i=0; i<10; i++) {
ArrayList<String> informationInIteration = new ArrayList<>();
informationInIteration.add(String.valueOf(i));
solve(informationInIteration); // add two random number generated in function solve()
information.add(informationInIteration);
}
printInformation();
}
private void solve(ArrayList<String> iterationInformation) {
iterationInformation.add(String.valueOf(random.nextInt()));
iterationInformation.add(String.valueOf(random.nextInt()));
}
private void printInformation() {
for (ArrayList<String> newLine : information) {
System.out.println();
newLine.forEach(data -> System.out.println(data + " "));
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
Main main = new Main();
main.run();
}
}
Based on your comments I am adding a method that creates no object for storing any information.
package com.company;
import java.util.Random;
public class Main {
private Random random = new Random();
private void run() {
for (int i=0; i<10; i++) {
System.out.println(String.valueOf(i));
System.out.println(random.nextInt() + " " + random.nextInt() + "\n");
}
}
public static void main(String[] args) {
Main main = new Main();
main.run();
}
}
This should work for you.
public void run() {
for (int i=0; i<10; i++) {
staticvarTest.information.add(solve(String.valueOf(i)));
}
print_information(information);
}
public String[] solve(String i) {
return {String.valueOf(random.nextInt()),
String.valueOf(random.nextInt()),
i};
}
Or you could maybe concatenate the array returned in solve() and the i String and avoid passing the variable around.
I have not tested the code above btw but apart from accessing and modifying the static variable there shouldn't be a problem.
Hope this works for you.
Okay. Here's my first page with the accessors and mutators
public class TimeCard {
private int employeeNum;
private String[] clockInTimes = new String[14];
private String[] clockOutTimes = new String[14];
private float[] decimalClockIn = new float[14];
private float[] decimalClockOut = new float[14];
private float[] timeElapsed = new float[14];
public String[] getClockInTimes()
{
return clockInTimes;
}
public void setClockInTimes(String[] value)
{
clockInTimes = value;
}
}
My second class acessessing those set/get arrays.
How would I ask for user input for each array subscript 0-13?
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
TimeCard josue = new TimeCard();
System.out.println("Enter Monday Clock In Times:");
//not sure if this is right?
josue.setClockInTimes[0](reader.next());
}
}
By the way I need to do it like this because teacher wants it this way. I'm just not really sure how to get user input and put it into an array using an object class.
I'd probably start by changing your setter to take an index and a value, so something like this:
public void setClockInTime(int day, String clockInTime) {
this.clockInTimes[day] = clockInTime; // note you don't need to write "this," but it's clearer that this is a member field
}
And then in your main method:
for (int i=0;i<14;i++) {
String input = <get input>
josue.setCliockInTime(i, input);
}
Now you can set one value at a time, and that should let you populate all of your fields.
I have two methods, the first one creates a string, then I want to use that string in the second method.
When I researched this, I came across the option of creating the string outside of the methods, however, this will not work in my case as the first method changes the string in a couple of ways and I need the final product in the second method.
Code:
import java.util.Random;
import java.util.Scanner;
public class yaya {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Random ran = new Random();
int ranNum = ran.nextInt(10);
input = input + ranNum;
}
public void change(String[] args) {
//more string things here
}
}
Create an instance variable:
public class MyClass {
private String str;
public void method1() {
// change str by assigning a new value to it
}
public void method2() {
// the changed value of str is available here
}
}
You need to return the modified string from the first method and pass it into the second. Suppose the first method replaces all instances or 'r' with 't' in the string (for example):
public class Program
{
public static String FirstMethod(String input)
{
String newString = input.replace('r', 't');
return newString;
}
public static String SecondMethod(String input)
{
// Do something
}
public static void main(String args[])
{
String test = "Replace some characters!";
test = FirstMethod(test);
test = SecondMethod(test);
}
}
Here, we pass the string into the first method, which gives us back (returns) the modified string. We update the value of the initial string with this new value and then pass that into the second method.
If the string is strongly tied to the object in question and needs to be passed around and updated a lot within the context of a given object, it makes more sense to make it an instance variable as Bohemian describes.
Pass the modified string in the second method as an argument.
create a static variable used the same variable in both the method.
public class MyClass {
public string method1(String inputStr) {
inputStr += " AND I am sooo cool";
return inputStr;
}
public void method2(String inputStr) {
System.out.println(inputStr);
}
public static void main(String[] args){
String firstStr = "I love return";
String manipulatedStr = method1(firstStr);
method2(manipulatedStr);
}
}
Since you mentioned that both methods should be able to be called independently, you should try something like this:
public class Strings {
public static String firstMethod() {
String myString = ""; //Manipulate the string however you want
return myString;
}
public static String secondMethod() {
String myStringWhichImGettingFromMyFirstMethod = firstMethod();
//Run whatever operations you want here and afterwards...
return myStringWhichImGettingFromMyFirstMethod;
}
}
Because both of these methods are static, you can call them in main() by their names without creating an object. Btw, can you be more specific about what you're trying to do?