Java - Getting the value of a method inside of a class - java

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());

Related

Using scanner input in getters and setters?

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;
}
}

Calling Methods in Main Class and Other Class Differences in Java

I have 3 classes, Mainn, ReadFile, and Entry.
ReadFile is basically my class that does all file i/o stuff.
How come I am able to access ReadFile in my Mainn class just fine, but
when I try to access it in Entry "e.openFile()" i get an error that says identifier expected.
I know this can be fixed by making an overloaded method openFile() in Entry but why is this needed in Entry, but not in the main class Mainn?
package homework6;
public class mainn {
public static void main(String[] args){
ReadFile r = new ReadFile();
r.openFile();
//r.readFile();
r.skipFirst();
String x[] = r.getData();
String y[] = r.getData();
String z[] = r.getData();
System.out.println(x[0] + "," + x[1]);
System.out.println(y[0] + "," + y[1]);
System.out.println(z[0] + "," + z[1]);
r.closeFile();
}
}
ReadFile:
package homework6;
import java.util.*;
import java.io.*;
public class ReadFile {
Scanner x = null;
public void openFile(){
try{
x = new Scanner(new FileInputStream(
"C:\\Users\\Rohan Vidyarthi\\workspace\\Data.csv"));
}
catch(FileNotFoundException e){
System.out.println("File not found error");
}
}
public void readFile(){
while (x.hasNextLine())
System.out.println(x.nextLine());
}
public void skipFirst(){
x.nextLine();
}
public String[] getData(){ //returns String[] with Date and ADJ Close
String[] temp;
String[] out = new String[2];
temp = (x.nextLine()).split(",");
out[0] = temp[0];
out[1] = temp[6];
return out;
}
public boolean checker(){
return x.hasNextLine();
}
public void closeFile(){
x.close();
}
}
class Entry:
package homework6;
public class Entry extends ReadFile{
ReadFile e = new ReadFile();
e.openFile();
double minn = Double.MAX_VALUE;
double maxx = Double.MIN_VALUE;
/*public String[] rMax(){
String[] temp1;
String[] temp2;
}
*/
}
I suggest you move your openFile() logic to the ReadFile class constructor as shown below and this approach will give you two advantages:
(1)scanner (which is a mandatory variable of ReadFile class) gets initialized inside the class constructor which makes more sense and avoids all NullPointerException i.e., someone accidentally calling other methods first before openFile() (Always ensure that all mandatory instance variables i.e., data is being initialized by the constructors, I strongly suggest make it as a practice and never allow any object being created freely without being the mandatory variables initialized through constructors which will avoid most of the issues).
(2) It will fix your problem automatically as you don't need a call to openFile() method (well, you don't have that method itself, ReadFile constructor has initialized the scanner).
public class ReadFile {
Scanner x = null;
public ReadFile() {
try{
x = new Scanner(new FileInputStream(
"C:\\Users\\Rohan Vidyarthi\\workspace\\Data.csv"));
}
catch(FileNotFoundException e){
System.out.println("File not found error");
}
}
public void readFile(){
//add code
}
public void skipFirst(){
//add code
}
public String[] getData(){
//add code
}
public boolean checker(){
return x.hasNextLine();
}
public void closeFile(){
x.close();
}
}
Just ensure that you don't need to call openFile() anymore as shown below:
public class Entry extends ReadFile{
ReadFile e = new ReadFile();//initializes scanner as well
public String[] readFile() {//add any methods you like here in this like
return e.readFile();
}
double minn = Double.MAX_VALUE;
double maxx = Double.MIN_VALUE;
}
How come I am able to access ReadFile in my Mainn class just fine, but
when I try to access it in Entry "e.openFile()" I get an error that
says identifier expected.
In Java, invocation of any method call (like your r.openFile()) should be done from another method or from constructor or from initializers (static or instance initializer), so the answer is in your Mainn class, you are calling the openFile() inside from main(String[] args) method whereas in your Entry class your openFile() method call is not wrapped inside any of the above-mentioned code blocks (i.e., methods, constructors, initializers).
One more important point is that in general when you say A extends B in Object Oriented Languages, it means that A IS-A type of B, but in your code Entry extends ReadFile does not make much sense, so you should avoid that.
put e.openFile(); in a method or constructor. You cannot place floating codes outside methods. Any statement can only be used inside the block of codes (i.e. methods, constructors, static initializers)
If you do
public class mainn {
ReadFile r = new ReadFile();
r.openFile();
//r.readFile();
r.skipFirst();
String x[] = r.getData();
...
you will receive the same error in mainn

ArrayList class separate from Java main file

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

Get String From Another Method?

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?

Need help: input int from console and pass it into method in different class

I'm a beginner. I want to read a number a from the console and then store them in variable to use as passing to a different class (different .java file).
How do I code the 2 classes?
public class PassedInMethod{
private int a;
public PAssMethod(int a) {
a = a; // TODO: where to get the a?
System.out.println("a was passed in!"+a);
}
}
public class Mainclass {
public static void main( String args[] ) {
Scanner input = new Scanner( System.in );
int a;
System.out.print( "Enter your nember: " );
a = input.nextInt();
PassedInMethod(int a);
}
}
If you want to create an instance of the PassedInMethod class in which the member variable a contains the value passed to the constructor.
Try changing
PassedInMethod(int a);
to
PassedInMethod myObj = new PassedInMethod(a);
Also, if you want to update the instance variable to the value of the argument you need to do
this.a = a;
since the argument "hides" the instance varuable.
If you don't want to create an instance, and just invoke a method in a different class, you need to make the method static like this:
public static void PassMethod(int a) {
// ....
}
You could then call the method like this
PassedInMethod.passMethod(a);
PassedInMethod however is not a very good name for a class, but I'm sure that was just for the sake of the example in the question.
You need to change
PassedInMethod(int a);
To
new PassedInMethod(a);
This looks to be more of what you want. You code had some syntax errors and such.
public class PassedInMethod {
private int a;
public PAssMethod(int a) {
this.a = a;
System.out.println("a was passed in!"+a);
}
}
public class Mainclass {
public static void main( String args[] ) {
Scanner input = new Scanner( System.in );
int a;
System.out.print( "Enter your nember: " );
a = input.nextInt();
PassedInMethod myobj = new PassedInMethod();
myobj.PAssMethod(a);
}
}

Categories

Resources