Problems to use the variables in methods - java

I am getting an error when am trying to get the variables in the If else if statements any help will do thanks here is the program
public class Info {
public static void main(String [] args){
char f,F,c,C,h,H;
Scanner input=new Scanner(System.in);
System.out.print("Enter employee num");
int e_num=input.nextInt();
System.out.print("Enter employee first name");
String e_fname=input.next();
System.out.print("Enter employee surname");
String e_sname=input.next();
System.out.print("Enter employee code C or c,H or h and F or f");
char e_code = input.next().charAt(0);
if(e_code=='f' || e_code=='F') {
System.out.print("Enter employee salary: ");
double salary=input.nextDouble();
e_code=calGrossF();
}
else if(e_code=='c'||e_code=='C'){
e_code=calGrossC();
}
else if(e_code=='h'|| e_code=='H'){
e_code=calGrossH();
}
}//end of main
public static void calGrossF(int f, int F){
}//end of Gross(F)
public static char calGrossC(){
}// end of Gross(C)
public static char calGrossH();{

Your code currently has several syntax errors.
Your methods calGrossC() and calGrossH() have to return a char according to the declaration. Currently they just return nothing.
This code e_code=calGrossF(); expects calGrossF() to return a char as well. Currently it is declared to return void.
You did not import the class Scanner (probably just not in the code sample).
callGross() expects two int parameters. You gave none in e_code=calGrossF();.
All those errors are pointed out by the Java compiler. Just get through your error messages one by one and correct the code accordingly.
Not really syntax, but wanted to note it here:
You declare a bunch of variables at the start (f,F,c,C,h,H), but never use them.
Here is a corrected code (just placeholders on several occasions):
import java.util.Scanner;
public class Info {
public static void main(String [] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter employee num");
int e_num=input.nextInt();
System.out.print("Enter employee first name");
String e_fname=input.next();
System.out.print("Enter employee surname");
String e_sname=input.next();
System.out.print("Enter employee code C or c,H or h and F or f");
char e_code = input.next().charAt(0);
if(e_code=='f' || e_code=='F') {
System.out.print("Enter employee salary: ");
double salary=input.nextDouble();
e_code=calGrossF( 0, 0 );
}
else if(e_code=='c'||e_code=='C'){
e_code=calGrossC();
}
else if(e_code=='h'|| e_code=='H'){
e_code=calGrossH();
}
}//end of main
public static char calGrossF(int f, int F){
return 'F';
}//end of Gross(F)
public static char calGrossC(){
return 'C';
}// end of Gross(C)
public static char calGrossH(){
return 'H';
}
}

First of all u have public static void calGrossF(int f, int F) as "void"
and u are storing its value in e_code
and also no arguments is being passed in the calling

//Method Statement
public char calGrossF(String name, int emp_num, double gross_sal, double fix_sal, double
ded, double net_pay, double highest_sal, double lowest_sal,
char ch)
{
//return statement
return calGrossF(name, emp_num, gross_sal, fix_sal, ded, net_pay, highest_sal, lowest_sal, ch);
}

Related

Is there a way to access variables in another method?

I'm new to java and I was wondering if there was a way to access a variable from one method in another method. While writing a program using methods, I realized that I cannot just take one variable from one method and use it in another method. So I was wondering if there was a way to do this.
Here is my code so far
import java.util.Scanner;
public class program{
public static void mass(){
double a,e,p,v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v=scanner.nextDouble();
p=0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e=scanner.nextDouble();
e=e/100;
a=v*e*p;
System.out.println("mass is: "+a);
}
public static void Concentration(){
double w,r,m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc=new Scanner(System.in);
person=sc.nextLine();
switch(person){
case "m": r=0.7;
break;
case "f": r=0.6;
break;
case "j": r=0.5;
break;
}
System.out.println("Enter person's weight: ");
m=sc.nextDouble();
//w=a/(m*r); //a from the method mass
}
public static void main(String[]args){
mass();
Concentration();
/*If(w>=0.5){ //w from the method concentration
System.out.println("You cannot drive!");
Else{
System.out.println("You can drive");
}
} */
}
}
There are two kinds of variables:
local variables (block-scoped)
member variables (class/instance level scope)
See: https://www.geeksforgeeks.org/variable-scope-in-java/
So, if you want to reuse a variable accross multiple methods, then you will need to convert it from a local variable into a member variable. In your case you only use static methods, so a would be declared outside your methods as
static double a;
and avoid declaring it inside your mass method, so your declaration line would be changed to
double e,p,v;
Note that the a is missing to avoid variable shadowing.
You may want to change your methods to instance-level methods, in which case you can declare a without the static keyword, depending on your plans and needs.
Also, a well-known approach is to implement getters and setters in order to make sure that whenever you get or set a value, if there are common operations, then they are implemented only once instead of code repeating.
Below you see the simplest changes to your code to achieve the goal you have specified:
import java.util.Scanner;
public class program{
static double a;
public static void mass(){
double e,p,v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v=scanner.nextDouble();
p=0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e=scanner.nextDouble();
e=e/100;
a=v*e*p;
System.out.println("mass is: "+a);
}
public static void Concentration(){
double w,r,m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc=new Scanner(System.in);
person=sc.nextLine();
switch(person){
case "m": r=0.7;
break;
case "f": r=0.6;
break;
case "j": r=0.5;
break;
}
System.out.println("Enter person's weight: ");
m=sc.nextDouble();
w=a/(m*r); //a from the method mass
}
public static void main(String[]args){
mass();
Concentration();
/*If(w>=0.5){ //w from the method concentration
System.out.println("You cannot drive!");
Else{
System.out.println("You can drive");
}
} */
}
}
Finally, you could also use a as a return value, like:
import java.util.Scanner;
public class program{
public static double mass(){
double a,e,p,v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v=scanner.nextDouble();
p=0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e=scanner.nextDouble();
e=e/100;
a=v*e*p;
System.out.println("mass is: "+a);
return a;
}
public static void Concentration(double a){
double w,r,m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc=new Scanner(System.in);
person=sc.nextLine();
switch(person){
case "m": r=0.7;
break;
case "f": r=0.6;
break;
case "j": r=0.5;
break;
}
System.out.println("Enter person's weight: ");
m=sc.nextDouble();
//w=a/(m*r); //a from the method mass
}
public static void main(String[]args){
Concentration(mass());
/*If(w>=0.5){ //w from the method concentration
System.out.println("You cannot drive!");
Else{
System.out.println("You can drive");
}
} */
}
}
To make a variable accessible in all functions of the class you can static the variable in question in the current class
package javaapplication6;
import java.util.Scanner;
// #author Vulembere
public class JavaApplication6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
mass();
Concentration();
if (w >= 0.5) {
System.out.println("You cannot drive!");
} else {
System.out.println("You can drive");
}
}
static double w;
public static void mass() {
double a, e, p, v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v = scanner.nextDouble();
p = 0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e = scanner.nextDouble();
e = e / 100;
a = v * e * p;
System.out.println("mass is: " + a);
}
public static void Concentration() {
double r, m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc = new Scanner(System.in);
person = sc.nextLine();
switch (person) {
case "m":
r = 0.7;
break;
case "f":
r = 0.6;
break;
case "j":
r = 0.5;
break;
}
System.out.println("Enter person's weight: ");
m = sc.nextDouble();
//w=a/(m*r); //a from the method mass
}
}

How can I use parameters to pass down a non constant variable value to a method?

I'm struggling with passing a variable value that a user has entered into my program into a method. I think the technical word is parameters.
The problem I'm having is that after the user enters a number in the getnum() method I want the number to be passed down to the two methods calculation and `calculation_two. However, I can't seem to be able to achieve it.
Just to explain the program, the user enters a number in the getnum() method, then they go to the option method and after they select what option, in the calculations methods the number that was written in the getnum() method needs to be passed down the the calculations methods. Therefore, I will then be able to perform calculations with it that way. I need the program to be set up like this as well for my own personal reasons.
Can anyone assist please?
Thanks
public static void main (String[]args){
getnum();
}
public static void getnum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
option();
}
public static void option() {
Scanner input2 = new Scanner(System.in);
System.out.println("would you like to see option 1 or 2");
int num2 = input2.nextInt();
if(num2==1) {calculation();}
else if(num2==2) {calculation_two();}
else {System.exit(0);}
}
public static void calculation() {
}
public static void calculation_two() {
}
Please see call by reference and call by value to further clarify how primitives or objects are passed from one method to another.
Here are the steps to pass the parameter from one method to another:
You pass the int you got from the scanner as an argument in the option method call:
public static void getnum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
option(num); // You pass the int as an argument
}
Now, since you are now calling a method with arguments you need to change the signature of the option method to take a parameter. You pass the int value(theNumber variable) from the option method's parameter to the calculation method call.
Arguments and parameters are terms which are used interchangeably but you can check the difference here.
public static void option(int theNumber) { // option now takes a int parameter
Scanner input2 = new Scanner(System.in);
System.out.println("would you like to see option 1 or 2");
int num2 = input2.nextInt();
if(num2==1) {
calculation(theNumber); // method now takes an argument
}
else if(num2==2) {
calculation_two(theNumber); // method now takes an argument
}
else {System.exit(0);}
}
You pass the parameter again to the calculation(s) method and change the signature to:
public static void calculation(int theNumber) { // method with parameter
}
public static void calculation_two(int theNumber) {
}
Declare your methods to use parameters and return values. Easiest way to do it:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
System.out.println("would you like to see option 1 or 2");
int option = input.nextInt();
int result = 0;
if (option == 1) {
result = calculation(num);
} else if (option == 2) {
result = calculation_two(num)
} else {
System.out.println("Invalid option, exiting...");
System.exit(0);
}
System.out.println("Result = " + result);
}
private static int calculation(int num) {
// implement this
return 0;
}
private static int calculation_two(int num) {
// implement that
return 0;
}
To answer with secure coding practices
package in.faridabad.mandheer;
public class Main{
public static void main (String[]args){
Main m = new Main();
// Assuming calculation is "sum"
System.out.println("sum is + "+ m.option());
}
private int getnum() {
Scanner input = new Scanner(System.in);
return input.nextInt();
}
int option() {
System.out.println("would you like to see option 1 or 2");
int num2 = getnum();
if(num2==1) {return calculation();}
else if(num2==2) {return calculation_two();}
else {System.exit(0);}
}
private int calculation() {
System.out.println("Enter a number: ");
int num1 = getnum();
return num1;
}
private int calculation_two() {
System.out.println("Enter a number: ");
int num1 = getnum();
System.out.println("Enter 2nd number: ");
int num2 = getnum();
return num1+num2;
}
}

How to access arguments of one method in another method?

/*
Program for salary incrementation
*/
import java.util.*;
class Increment
{
Scanner sc = new Scanner(System.in);
void getdata(String n, double d, int a)
{
System.out.print("Enter name of employee ");
n = sc.nextLine();
System.out.println("Enter current salary ");
d = sc.nextDouble();
System.out.println("Enter age");
a = sc.nextInt();
}
void calculate()
{
if(a>=56)
{
d = d+(20/100);
}
if(a>45&&a<56)
{
d = d+(15/100);
}
if(a<=45)
{
d = d+(10/100);
}
}
void display()
{
System.out.println("Name \t Age \t Basic ");
System.out.print(n +"\t"+ d + "\t" + a);
}
public static void main(String[] args)
{
Increment i = new Increment();
i.getdata();
i.calculate();
i.display();
}
}
How can I use values of n, d and a in calculate() method?
Please help me if you find any other mistake!
You have getdata return the information (as an object with private fields and getters [at least] for them), and then you pass that object into calculate and have calculate use the getters to get the values. (Similarly, this is how you would get information from calculate into display.)
You could also make them fields in Increment, but that makes Increment stateful (prior to calling getdata, it doesn't have the necessary information), which is generally best avoided.
In this case you need to have instance variables, so you can use them in methods
class Increment
{
String n; double d; int a;
Scanner sc = new Scanner(System.in);
void getdata()
{
System.out.print("Enter name of employee ");
n = sc.nextLine();
System.out.println("Enter current salary ");
d = sc.nextDouble();
System.out.println("Enter age");
a = sc.nextInt();
}
void calculate()
{
if(a>=56)
{
d = d+(20/100);
}
if(a>45&&a<56)
{
d = d+(15/100);
}
if(a<=45)
{
d = d+(10/100);
}
}
void display()
{
System.out.println("Name \t Age \t Basic ");
System.out.print(n +"\t"+ d + "\t" + a);
}
public static void main(String[] args)
{
Increment i = new Increment();
i.getdata();
i.calculate();
i.display();
}
}
You must declare the variables you are using
String n;
double d;
int a;
Also the main put it in another class.
In method "calculate" use the switch

how do i make java code that reads a word and tells me if is starts with the letter a or not? i am lost

import java.util.Scanner;
public class IfAndString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word:");
String line = input.next();
char a = line.charAt(2);
char b = line.charAt(2);
if (a < b)
System.out.printf("%s starts with 'a'.",a);
else if (a > b)
System.out.printf("\n%s does not start with 'a'.",b);
}
}
You can use the startsWith() method
Example:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word:");
String line = input.next();
if (line.startsWith("a"))
{
System.out.println(line + ": starts with a");
}
else
{
System.out.println("does not start with a");
}
}
Also if you wanted to check for an a even if they entered an uppercase A you could change your line variable to lower case in the if check to account for both lowercase and uppercase a.
Example:
if (line.toLowerCase().startsWith("a"))
Anwser to your question in the headline. Simply use the Method boolean startsWith(String string) method from the String class, e.g. like this:
import java.util.Scanner;
public class IfAndString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word:");
String line = input.next();
if (line.startsWith("a")){
System.out.printf("%s starts with 'a'.",a);
} else{
System.out.printf("\n%s does not start with 'a'.",b);
}
}
}
When you want to compare chars do something like this:
"abc".charAt(0) == 'a'; // String implement CharSequence.

How do I create a user-defined method that returns the length of a string?

I am trying to write a program that takes a user's input and outputs the number of characters they typed in. I have to do this by creating a method that calculates the amount of characters, then call that method in main to output the results. I was encouraged to use a for loop, but I don't see how that would work. I can calculate the number of characters using length(), but I can't figure out how to make my method work. This is what I have so far:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
return;
}
public static int GetNumOfCharacters(int userCount) {
int i = 0;
String userInput = "";
userCount = userInput.length();
return userCount;
}
}
My method is not returning the length of the string, it just gives me 0 or an error.
Right now, you are never calling your "GetNumOfCharacters" method in your main. The way Java programs work, is by calling the main method and executing line per line what lies there. So you need to call you method from inside the main method. On the other hand, it should get the Stirng as a parameter, so you can get its length. It would look something like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
int lenInput = GetNumOfCharacters(userInput);
System.out.println("The length was: "+lenInput+" characters");
}
public static int GetNumOfCharacters(String userInput) {
int len = userInput.length();
return len;
}
A problem is that you are not actually calling the method
so try
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
System.out.println ("The length is " + GetNumOfCharacters (userInput))
}
// need to pass string into this method
public static int GetNumOfCharacters(String myString) {
int userCount = myString.length();
return userCount;
}
}
Your question included the line:
I was encouraged to use a for loop, but I don't see how that would
work.
There's no elegant way to do this in Java because you are assumed to use String.length() to get the length of strings. There is no 'end of string' marker as there is in, say, C. However you could mimic the same effect by catching the exception thrown when you access past the end of the string:
for (int len = 0; ; len++) {
try {
text.charAt(len);
} catch (StringIndexOutOfBoundsException ex) {
return len;
}
}
That's not a nice, efficient or useful piece of code but it does demonstrate how to get the length of a string using a for loop.
Problems with your code:
No Function call
Add function call in main() as int count=GetNumOfCharacters(userInput);
Parameter datatype mismatch
change the datatype in function definition from int to String as public static int GetNumOfCharacters(String userInput) {
Unwanted return statement in main()
remove the return from main()
Not displaying the value returned from GetNumOfCharacters
Add System.out.print("Number of characters: "+ count); inside main()
Code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
int count=GetNumOfCharacters(userInput);
System.out.print("Number of characters: "+ count);
}
public static int GetNumOfCharacters(String userInput) {
int userCount = userInput.length();
return userCount;
}
OR
Function is not really needed,you can remove the function and do it like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
System.out.print("Number of characters: "+ userInput.length());
}
If you don't want to use predefined methods, you can do like this..
public static void main(String args[]){
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.println("You entered: "+userInput);
char a[]=userInput.toCharArray();
int count=0;
for(char c : a){
count++;
}
System.out.println("length of the string is:"+count);
}

Categories