Basic Java: How to call a method? - java

I'm trying to create a program that includes a menu and will execute whatever choice the user chooses. I completed the methods and got them to compile, but am lost on how to call the classes. Here is the code in screenshots so they're easier to read:
Geek Class: (Contains all the methods)
public class Geek{
private String name;
private int numberofQuestions=0;
public Geek (String name){
this.name = name;
numberofQuestions = 0;
}
public String getName(){
return name;
}
public int getnumberofQuestions(){
return numberofQuestions;
}
public boolean allTheSame(int num1, int num2, int num3){
numberofQuestions++;
if(num1 == num2 && num2 == num3 && num1 == num3){
return true;}
else return false;
}
public int sum (int num1, int num2){
numberofQuestions++;
int largest = Math.max(num1, num2);
int smallest = Math.min(num1, num2);
int result =0;
for (int i=smallest; i <= largest;i++){
result = result + i;}
return result;
}
public String repeat(String str, int n){
numberofQuestions++;
String repetition = "";
for (int j=0; j < n; j++){
repetition = repetition + str;}
return repetition;
}
public boolean isPalindrome(String str){
numberofQuestions++;
int n = str.length();
for( int i = 0; i < n/2; i++ )
if (str.charAt(i) != str.charAt(n-i-1)) return false;
return true;
}
}
Main:
http://i.imgur.com/DvJ0LU5.png
EDIT: Im getting a cannot find symbol error in this section of code:
case "d":
myGeek.sum(num1, num2, num3);
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
System.out.println("Enter the third number");
int num3 = scan.nextInt();
break;

Classes aren't called, they are blueprints for creating objects.
You need a program entry point, in this case inside your class like so
public static void main(String[] args)
{
Geek myGeekObject = new Geek("Your name");
}
you can then call the methods on your created object
public static void main(String[] args)
{
Geek myGeekObject = new Geek("Your name");
String geekName = myGeekObject.getName();
}

In Java (and any other languages I know), you can only call methods/functions, but not classes (except you count <clinit>). So you could write:
Geek geek = new Geek("Me");
int i = geek.sum(1, 2);
System.out.println(String.valueOf(i));
Assuming the file Geek.java, you can then call/run the class using:
javac Geek.java
java Geek
from the commandline.
Note that this will only succeed if Geek.java contains a main method. Read about them here.

You need to create instance of object and then you can use it
For example:
Geek g = new Geek("Geek");
g.getName();

You need to instantiate an instance of the class in order to use it.
For example, in your main method you may want to define an instance of the object like so:
Geek myGeek = new Geek("user2943817");
You can than access all instance methods on the object using the variable name like so:
myGeek.getName();
I hope this helps!
EDIT :
As for your new issue, simply call the method after you obtain the values from the user. Like this:
case "d":
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
System.out.println("Enter the third number");
int num3 = scan.nextInt();
myGeek.sum(num1, num2, num3);
break;

You cant use non-static class like that.
Imagine that Geek is definition of Geek. You want to create several geeks, each one is standalone instance.
Geek g1 = new Geek("Andrew");
Geek g2 = new Geek("John");
These lines create two instances g1 and g2 of type Geek with name Andrew and John
Then you access them like this :
g1.repeat("myString", 10)

Related

Can I get help figuring out this?

When i run my code, I get an error in mimir (idk if you guys know about it but is a platform that teachers use to check the test cases of the code that you submit) saying that I a have a whitespace that shouldn't be there (check image).
1.) how can i fix that regarding my code.
and another issue which it drove me crazy is,
how can I make it so that when I enter a letter, In this case it was inputted 'f' (check the image) to display the "enter two integers:" just like the imagine. I tried different types of loops and changing the layout but i never got it to be correct.
p.d. Yes, this was a homework and was due yesterday. Even though i got a good grade on it, it still bugged me that I couldn't figure out these two things out.
import java.util.InputMismatchException;
import java.util.Scanner;
public class MathTeacher {
public static int addNumbers(int n1, int n2){
int add = n1+n2;
return add;
}
public static int subtractNumbers(int n1, int n2){
int subs = n1-n2;
return subs;
}
public static int multiplyNumbers(int n1, int n2){
int mulp = n1*n2;
return mulp;
}
public static int divideNumbers(int n1, int n2){
int div = n1/n2;
return div;
}
private static int getIntFromUser(Scanner scan) {
int x;
while (true) {
try {
x = scan.nextInt();
break;
} catch (InputMismatchException e) {
scan.next();
}
}
return x;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Welcome to *Mental Math Practice* where you can test your addition, subtraction, multiplication, and division.");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two integers: ");
String typeQuit= "";
do {
int choices;
int n1 = getIntFromUser(scanner);
int n2 = getIntFromUser(scanner);
System.out.println("Enter 1 to add the two numbers.");
System.out.println("Enter 2 to subtract the second number from the first number.");
System.out.println("Enter 3 to multiply the two numbers.");
System.out.println("Enter 4 to divide the first number by the second number.");
choices = scanner.nextInt();
switch (choices) {
case 1: {
int add = addNumbers(n1, n2);
System.out.println(add);
break;
}
case 2: {
int sub = subtractNumbers(n1, n2);
System.out.println(sub);
break;
}
case 3: {
int mulp = multiplyNumbers(n1, n2);
System.out.println(mulp);
break;
}
case 4: {
int div = divideNumbers(n1, n2);
System.out.println(div);
break;
}
}
System.out.println("Enter 'Quit' to end the program.");
typeQuit = scanner.next();
} while(!typeQuit.equals("Quit"));
}
}

recursive method multiplying without using operator

import java.util.Scanner;
public class LAB1201 {
static int multi(int a, int b){
int c = 0;
if (b == 0) {
c = 0;
}
if (b < 0) {
c = (-multi(a, -b));
}
if (b > 0) {
c = (a + multi(a, b-1));
}
return c;
}
public static void main(String[]args){
int aa;
int bb;
Scanner scanner = new Scanner(System.in);
System.out.println("Type in a integer");
aa = scanner.nextInt();
System.out.println("Type in another integer");
bb = scanner.nextInt();
multi(aa,bb);
}
}
I am coding
(Write a recursive function that multiplies two numbers x and y using recursion (do not
use the multiplication operator). Your main method should prompt the user for the two
numbers, call your function, and print the result)
It allows me to type in values but I am not sure why it is not returning any values
it returns nothing..
You forgot to output the value.
System.out.println(aa + " x " + bb + " = " + multi(aa,bb));
Output example:
Type in a integer
4
Type in another integer
8
4 x 8 = 32
Your code is fine. You just forgot to print the result returned by method static int multi(int a, int b). You can find working code here
You are missing a printing statement. Here is the code, please have a look.
import java.util.Scanner;
public class so {
static int multi(int a, int b){
int c = 0;
if(b<0){
return c=(-multi(a, -b));
}
if(b>0){
return c=(a+multi(a, b-1));
}
return c;
}
public static void main(String[]args){
int aa;
int bb;
Scanner scanner = new Scanner(System.in);
System.out.println("Type in a integer");
aa = scanner.nextInt();
System.out.println("Type in another integer");
bb = scanner.nextInt();
System.out.println(multi(aa,bb));
}

How do I use a function involving integers?

We have an assignment in class to create a greatest common divider (gcd) program using functions. I missed out on the lesson where we learned how to properly use them. I finished the part that actually does the division but I don't know how to separate it into a function and have it work. I'd like to have the input in the main class and the process in function.
This is what I have, it does not work when I run it
package gcd.function.java.program;
import java.util.Scanner;
/**
*
* #author sarah_000
*/
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
int div;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
System.out.printf("The GCD is %d ", div);
}
public static void GCDFunction() {
if(num1 > num2)
div = num2;
else div = num1;
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
}
}
Any tips or help you can give to me will be greatly appreciated, I'm very new
You declare two parameters and modify the return type in your GCDFunction like this:
public static int GCDFunction(int num1, int num2)
You are currently trying to access the variables in the main method but are out of scope.
Also, you never actually call your GCDFunction
Think of it like passing functions in math. The GCDFunction() has to receive the numbers into the function so we do
public static void GCDFunction(int num1, int num2)
That also lets Java know the type it is, type int. And your java variables are scoped inside of the functions so you have to print the output in the function that created the variable in your scenario.
So once you have that function set up to receive the variables and output after processing, you call the function in the main with a
GCDFunction(num1, num2);
Where num1 and num2 are the variables that have your integers stored in.
The end result after a little rearranging looks like this.
import java.util.Scanner;
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
GCDFunction(num1, num2);
}
public static void GCDFunction(int num1, int num2) {
int div;
if(num1 > num2){
div = num2;
}
else{ div = num1;}
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
System.out.printf("The GCD is %d ", div);
}
Trying to give you a example of how the code should be to take in variable number of parameters.
public int gcd(Integer... numbers) {
int gcd = 1;
int miNNumber=Collections.min(Arrays.asList(numbers));
boolean isDivisible;
for(int i=2; i<=miNNumber;i++) {
isDivisible=true;
for(Integer eachNumber : numbers) {
if(eachNumber%i!=0) {
isDivisible=false;
break;
}
}
if(isDivisible) {
gcd=i;
}
}
return gcd;
}
You can call it
gcd(10, 200, 400);
or
gcd(10, 200, 400, 4000, 40);

Java fraction calculator, global variables?

This is my second time asking this question because this assignment is due tomorrow, and I am still unclear how to progress in my code! I am in an AP Computer programming class so I am a complete beginner at this. My goal (so far) is to multiply two fractions. Is there any way to use a variable inside a particular method outside of that method in another method? I hope that wasn't confusing, thank you!!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
Is there any way to use a variable inside a particular method outside of that method in another method?
Yes you can do that. You can declare a variable in a method, use it there and pass it to another method, where you might want to use it. Something like this
void test1() {
int var = 1;
System.out.println(var); // using it
test2(var); // calling other method and passing the value of var
}
void test2(int passedVarValue) {
System.out.println(passedVarValue); // using the passed value of the variable
// other stuffs
}

How to send variables from one class to another.

Hopefully it's not too late for someone to help me out. I'm trying to create a program that has one class (TestCode) that asks the user to enter 4 integers. Then, I send the variables from that class to another class (MySmartDataType). Then, I use those integers to perform certain calculations. The problem is, I'm not sure how to get the second program to accept those integers properly. Here is the first class.
import java.util.*;
class TestCode{
public static void main(String args[]){
int n1 = 0;
int n2 = 0;
int n3 = 0;
int n4 = 0;
String repeat = "Y";
int evenTotal = 0;
int oddTotal = 0;
MySmartDataType msdt;
Scanner sc;
sc = new Scanner(System.in);
while (repeat == "Y"){
System.out.println("Enter number 1 ");
n1 = sc.nextInt();
System.out.println("Enter number 2 ");
n2 = sc.nextInt();
System.out.println("Enter number 3 ");
n3 = sc.nextInt();
System.out.println("Enter number 4 ");
n4 = sc.nextInt();
System.out.println("Would you like to continue? N for no and Y for Yes.");
repeat = sc.nextLine();
msdt = new MySmartDataType(n1,n2,n3,n4);
}
evenTotal = msdt.getEvenTotal();
System.out.println("Even total is: " + evenTotal);
oddTotal= msdt.getOddTotal();
System.out.println("Odd total is: " + oddTotal);
System.out.println("Grand Total is: " + msdt.getTotal() );
}
}
And here's the second one:
import java.util.*;
class MySmartDataType {
private int myArray[] = new int [4];
myArray[4] = {n1, n2, n3, n4};
int getEvenTotal(){
int sumEven = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 2 == 0){
sumEven += myArray[i];
}
}
System.out.println("The even total is: " + sumEven);
return sumEven;
}
int getOddTotal(){
int sumOdd = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 3 == 0){
sumOdd += myArray[i];
}
}
System.out.println("The odd total is: " + sumOdd);
return sumOdd;
}
int getTotal(){
int sumTotal;
for (int i = 0; i <= 3; i++){
sumTotal += myArray[i];
}
System.out.println("The total is: " +sumTotal);
return sumTotal;
}
}
Do a setter and getter method in order to get the variable to the other class.
Here is a tutorial on how to do it:
YOUTUBE link
declare the variables globally then create getter, setter for the declared variables. So you can get the variable's value in any other class you want by getter method.
Using public static modifier.
Example: public static int example, now you can using example in other class.
Add the following in your MySmartDataType class. Create 4 instance variables in your MySmartDataType which can hold the data being sent from other class.(eg: int var1...)
MySmartDataType(int num1,int num2,int num3,int num4)
{
var1 = num1;
var2 = num2;
var3 = num3;
var4 = num4;
}
Use var1...var4 in the methods to do the operations. You can replace var1...var4 with array, but then you need to loop every time to read the values and to do the opr's(which is not a bad option and up to you).
You missed the constructor in MySmartDataType class. This constructor will be called when you create the object of this class in your first class; i.e.
msdt = new MySmartDataType(n1,n2,n3,n4);
the following doesn't make sense, remove it
myArray[4] = {n1, n2, n3, n4};
The constructor in MySmartDataType class will set the values to the array;
public MySmartDataType (int n1, int n2, int n3, int n4) {
//this constructor will be called when the object of this class will be created with 4 integer parameters
myArray[0] = n1;
myArray[1] = n2;
myArray[2] = n3;
myArray[3] = n4;
}
I guess now you're learning OOP, right?
you can create some method with one or more parameters to fill your second class attributes.
for example :
function setData(int data, int pos){ myArray[pos] = data;}
and you can call that method from your first class
msdt.setData(something, 0);
Try this one:
import java.util.*;
class MySmartDataType {
private int myArray[] = new int [4];
public MySmartDataType(int n1, int n2, int n3, int n4) {
myArray[0] = n1;
myArray[1] = n2;
myArray[2] = n3;
myArray[3] = n4;
}
int getEvenTotal(){
int sumEven = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 2 == 0){
sumEven += myArray[i];
}
}
System.out.println("The even total is: " + sumEven);
return sumEven;
}
int getOddTotal(){
int sumOdd = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 3 == 0){
sumOdd += myArray[i];
}
}
System.out.println("The odd total is: " + sumOdd);
return sumOdd;
}
int getTotal(){
int sumTotal = 0;
for (int i = 0; i <= 3; i++){
sumTotal += myArray[i];
}
System.out.println("The total is: " +sumTotal);
return sumTotal;
}
}
Add following constructor to the MySmartDataType class.
public MySmartDataType(int n1, int n2, int n3, int n4)
{
myArray = new int[]{n1, n2, n3, n4};
}
http://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html
package greetings;
import javax.inject.Inject;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
#Named
#RequestScoped
public class Printer {
#Inject #Informal Greeting greeting;
private String name;
private String salutation;
public void createSalutation() {
this.salutation = greeting.greet(name);
}
public String getSalutation() {
return salutation;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Setters set a variable to your input parameters. Getters return the instance variable that one is "getting". For example,
Printer myobject = new Printer();
//sets instance variable 'name' to "Hello World"
myobject.setName("Hello World");
//gets instance variable 'name' with getter and sets it to mystring
String mystring = myobject.getName();
//will print "Hello World"
System.out.println(mystring);

Categories

Resources