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;
}
}
Related
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.
I have two separate files, one named WonderfulArrayList, and the other named ArrayListMain (I'm experimenting with ArrayLists, and I'm not quite sure what to do) and so I have a method in the WonderfulArrayList file, but the main file cannot see the method, which I have named booladdData, which would return true once the data is added to the array list. My WonderfulArrayList file is the following:
import java.util.*;
import java.io.*;
public class WonderfulArrayList{ //implement WonderfulArrayList
public static int ADDNums;
public static int index;
public static int HEADNums;
public static ArrayList<Integer> arr = new ArrayList<Integer>(15);
public static boolean booladdData(ArrayList<Integer>arr){
arr.add(ADDNums);
return true;
}
}
As you can see, I have booladdData instantiated with the ArrayList, named arr. Now, if you look at my main file:
public class ArrayListMain{
//public ArrayList<Integer> arr = new ArrayList<Integer>(15);
public static void main(String[]args){
ArrayList<Integer> arr = new ArrayList<Integer>(15);
int MenuNum = 0;
int ADDNums = 0;
Object Obj = new Object();
Scanner scanner1 = new Scanner(System.in); //set up scanner for user input
while(MenuNum != 7){ //menu loop
Menu(MenuNum);
MenuNum = scanner1.nextInt();
if(MenuNum == 1){
arr.booladdData();
}
For some reason, even though I know that booladdData is created as public and they're both in the same folder, the main file doesn't have the scope to be able to see booladdData in the separate file.
Any idea what I'm doing wrong?
You should be calling WonderfulArrayList.booladdData(arr) instead of arr.booladdData(). The method booladdData() is defined as a class method of your WonderfulArrayList class. It's not an instance method of Java's ArrayList.
You also might want to read into object-oriented programming. Everything in your code is static.
You need to create your type instead of ArrayList
package com.jbirdvegas.test;
import java.util.ArrayList;
public class MainClazz {
public static void main(String[] args) {
// notice I'm creating my type `MyArrayList` instead of `ArrayList` type
MyArrayList myArrayList = new MyArrayList();
myArrayList.add("blah");
System.out.println("My message:" + myArrayList.getSomething());
}
}
class MyArrayList extends ArrayList {
public String getSomething() {
return "something";
}
}
Prints:
My message: something
I am trying to get the value of a method that is inside a class into the main class.
The code is supposed to let me give the variables 'a', 's' and 'u' each a value by using the console and afterwards return the values to the main class.
import java.util.*;
public class Auslesen
{
String a;
private int s;
double u;
public class Scannen
{
Scanner scanner = new Scanner(System.in);
public int Methode()
{
s = scanner.nextInt();
return s;
}
}
}
and here is my main class:
public class Start
{
public static void main(String[] args)
{
Auslesen auslesen = new Auslesen();
//System.out.println(auslesen);
Auslesen.Scannen scannen = auslesen.new Scannen();
//System.out.println(scannen);
Auslesen.Scannen.Methode methode = scannen.new Methode();
System.out.println(methode);
//my approach which didnt worked out...
}
}
Methode is a method not a class. You don't create it with new or create it at all for that matter. A method is defined in a class and you just call it. E.g.
System.out.println(scannen.Methode());
and delete this line :
Auslesen.Scannen.Methode methode = scannen.new Methode();
Also try to stick to the Java naming convention : class names start with uppercase method and variable names with lowercase.
First of all why are you declaring a class inside another class ? If you simply want to return a value from one class to another class then you can do something like this -
String a;
private int s;
double u;
Scanner scanner = new Scanner(System.in);
public int Methode()
{
s = scanner.nextInt();
return s;
}
now in the main method just call the method -
Auslesen a=new Auslesen();
System.out.println("The entered number is: "+a.Methode());
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?
I have two classes. In the first one, I used the Scanner to retrieve the user's name and then store it in a String called name. Then say, I start a new class, and want to print that came out, how do I go about it. So I just wrote up this code as an example, so you can get an idea of what I'm trying to ask. I'll post both classes.
import java.util.Scanner;
public class One {
public static void main(String[] args) {
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two object = new Two();
}
}
}
Second class.
public class Two {
public Two() {
System.out.println("Ok "+One.name+", lets start!");
}
}
So, you will probably be doing something like this: -
class One
{
private String name = "bob";
public String getName()
{
return name;
}
public static void main(String [] args)
{
One one = new One();
Two two = new Two(one);
// You could also just pass an r-value to Two, as in, Two(new One()) if you
// never require 'one' again
}
}
class Two
{
public Two(One one)
{
System.out.println("Ok " + one.getName() + ", lets start!");
}
}
What is going on?
Creating two classes in your main entry point method.
Passing the instance of One to the constructor of Two
Two then calls getName()
You could, as others have suggested, pass a string as the constructor; alternatively, you could do both if required as Java supports overloading methods see
Recommendations
Take a look at http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html for overriding methods so that you may see how to pass both a string and an object reference by value. What you are doing right now is passing the object reference of one by value. It may not be needed or you may want to provide restrictions using an interface, see http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
Use the constructor to pass the values
public class Two {
private String value;
public Two(String a){
this.value=a;
System.out.println("Ok "+value+", lets start!");
}
//getter and setters
}
Then while creating the instance use that constructor
Two object = new Two(name);
pass your value to the Two class constructor.
if(start != null){
Two object = new Two(start );
}
and
public Two(String s){
System.out.println("Ok "+s+", lets start!");
}
To make your code compile, move the String name variable into a static field:
public class One {
public static String name;
public static void main(String[] args){
// Note: The "name" variable is no longer defined here
String start; // etc
// rest of code the same
}
}
I'm not going to tell you this is good code design, but it does what you asked.
You will also do like this
public class One {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
retrun this.name;
}
public static void main(String[] args){
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two two = new Two();
two.printName(this);
}
}
class Two{
public void printName(One one){
System.out.println("" + one.getName() );
}
}