Problems with non-static variable inputs and trying to run methods - java

I've done a bunch research into trying to solve this issue (for about 2.5 hours), but I'm still not able to compile my program. I have tried making the method not static, but when attempting to run it, it gives me this error:
"Error: Main method is not static in class prog6, please define the
main method as: public static void main(String[] args)"
When the main method is static, I get following error in a compiler
Error: "non-static variable input cannot be referenced from a static
context
usd = input.nextDouble();"
I'm sorry if this question comes off redundant, I don't mean to ask without looking for an answer on my own, but I've been working at this for hours now and I don't understand what I'm doing wrong.
Some extra info on this program: it's meant to take inputs from the user to find out what currency they want to convert to, and how much USD they would like to convert. Then, I would invoke a method in order to do the calculations and return them. (Any amount trying to be converted over $200, will need 5% fee.)
import java.util.Scanner;
public class prog6
{
Scanner input = new Scanner(System.in);
public static void main (String[] args)
{
char curr = 0;
double usd;
double result;
while (curr!='Q' || curr!='q') { //loop
System.out.println("What type of currency would you like to buy?");
curr = input.next().charAt(0);
System.out.println("How many dollars would you like to convert?");
usd = input.nextDouble(); //asking user for info needed to convert
if (usd>200) {
usd = (usd)*(0.95);
}
result = calc (curr,usd); //invoke the method
}
}
public double calc (char mCurr,double mUsd) //method
{
if (mCurr=='E' || mCurr=='e') {
return (mUsd)*(0.88);
}
else if (mCurr=='P' || mCurr=='p') {
return (mUsd)*(0.77);
}
else if (mCurr=='Y' || mCurr=='y') {
return (mUsd)*(113.17);
}
return 0;
}
}

The main method will need to be static. From there, create an instance of your class and call a non-static method from the static main method. eg..
public class Prog6 {
private Scanner input = new Scanner(System.in);
public static void main (String[] args) {
Prog6 prog6 = new Prog6();
prog6.start();
}
public void start() {
char curr = 0;
double usd;
double result;
// etc...
}
}
You could make the member variable static but it's better form to use regular non-static members and methods and call this from the static main method.

There are two ways to solve your prolem
Change the input variable to static;
or
In main method, prog6 myprog= new prog6(); and refer input as myprog.input ....

Related

Formatting double as a function parameter

I have a function that takes in a double as a paramater. However, if I input "8" when I call the function, it processes as "8.0".
I know that I can format it with String.format() and other methods, however the format that the number is inputted as is important to the result (8 has a different result than 8.0, and I have no idea inside of the function body which one was intended by the user).
I know that I can add a format parameter as well as the double, function(double d, DecimalFormat f), but that would make it much more tedious to use, and it is intended as a util function anyways. Any tips?
There are some ways you can solve this, depending on your problem.
Method overloading
If the user input is by code, you can handle different types using the same method name.
class Program {
public static void foo(int n) {
// The input is an integer
System.out.println(n);
}
public static void foo(double x) {
// The input is a double
System.out.println(x);
}
public static void main(String[] args) {
foo(8); // prints 8
foo(8.0); // prints 8.0
}
}
Handling strings
However, if the user input is by keyboard, for example, you can use RegEx.
class Program {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
if (input.matches("^\\d+\\.\\d+$")) {
// The input is a double
} else if (input.matches("\\d+")) {
// The input is an integer
} else {
// The input is something else
}
}
}

Java method taking 0 arguments and returning a double using if else statements with strings

I am trying to write a method which does not take any arguments and then returns a double variable. It is a postcode identifier so when a cost code is entered certain post codes need to return a double.
In my example below i need post codes that start with either "GH6 TXX" or "NC4 LXX". (X stands for any random character or digit) to return 50.0.
If any other postcode is entered then return 100.0.
However i am not getting any results back and just finding errors. I'm sure i have gone massive wrong somewhere as im not great with If Else statements within methods. Any help or knowledge on this would be great!
public class multiPostcodeRange {
//Declaring Variables
String pcode;
public multiPostcodeRange()
{
pcode = "XXX XXX";
}
public void multiPostcodeRange()
{
if (pcode("GH6 TXX", "NC4 LXX")) {
return 100.0; }
else {
return 50.0;}
} }
public class MultiPostcodeRange {
private String pcode;
public MultiPostcodeRange() {
pcode = "XXX XXX";
}
public double multiPostcodeRange() {
if (pcode.equals("GH6 TXX") || pcode.equals("NC4 LXX")) {
return 100.0;
}
else {
return 50.0;
}
}
}
To return double from a function you need to define a return type for the function.
public double multiPostcodeRange
You created a class with his methods (which btw you shouldn't name as the class, but give them unique names).
Then you have to create a new instance object of that class and call the method on a main function.
For example, at the end of your code:
`public static void main(String args[]){
multiPostcodeRange Obj = new
multiPostcodeRange();
Obj.meth1();
Obj.meth2();}`
NB remember to give those methods unique names!
Also change 2nd method body and type as AndyMan's answer

Java: passing variable one time but different values

I'm a Java newbie and I have this question.
Can I pass a variable to a method multiple times without creating a new object?
For example, if I have a variable x which is the user input, another variable called m and a method were: if x is "h" then m is "example1" else if x is "f" m is "example2".
If I write:
String x = Scanner.next();
And I create the object passing the x variable, when I write,
System.out.println(obj.m);
If the input was h It will print out "example1"
But if write down this after what i showed up:
x = Scanner.next();
System.out.println(obj.m);
Whatever character I write down the output will be "example 1"
If I type "f" the first time the output will be "example2"
But the second system.out.println() will print "example2" eventually if I typed "h" the second time
So is it possible to pass a variable only one time with a value that changes over time without creating a new object?
If I understand your question correctly, then yes, you can pass a variable to a method multiple times without creating a new object. Let's say you create a class like this:
public class Test {
public String m;
public void testMethod(String x) {
if ("h".equals(x)) {
m = "example1";
} else if ("f".equals(x)) {
m = "example2";
} else {
m = "other";
}
}
}
If you created an object from this class in a main method and pass in different values of x as the argument for testMethod(), the value of m would change:
public class MainClass {
public static void main(String[] args) {
Test obj = new Test();
String x = "h";
obj.testMethod(x);
System.out.println(obj.m); // prints example1
x = "f";
obj.testMethod(x);
System.out.println(obj.m); // prints example2
}
}
As I understood your question, I have added a solution that will create the object you mentioned one time and call the method inside it repeatedly as you enter values. This might help you
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ClassOfYourObject object = new ClassOfYourObject();
while (true) {
System.out.print("Enter letter : ");
String x = scanner.next();
object.yourMethodToPrint(x);
}
}
}
class ClassOfYourObject {
void yourMethodToPrint(String value) {
if (value.equals("h")) {
System.out.println("example1");
} else if (value.equals("f")) {
System.out.println("example2");
} else {
System.out.println("Invalid letter");
}
}
}

Program not working?

The question is to find the number of days between two dates.example-input-26/3/2000 and 12/8/2014.the output will be the no of days in between these two dates.
There is an error saying "identifier expected" and i=1 is highlighted.Also I am not sure whether the program is completely correct.
import java.util.*;
class yearst
{
int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
int i,s,s1,s2,s3,k,diy,m,m1,m2,d1,d2,y1,y2,y;
i=1;s1=0;s2=0;s3=0;diy=365;
void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
ob.leap(i+1)
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
ob.leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
ob.leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s)
}
}
Please help.
Your program is a bunch of errors. First, you are calling class variables in main method without declaring them static or initializing them in constructor. Second, you are calling leap() which is method of a class from object of Scanner. It is not possible. The program will never compile nor run this way. I have modified your code to make it compilable and runnable. But one thing is for sure. Its logic is incorrect. It is giving wrong output as you want to calculate number of days between two dates. That is your job. I removed its errors. Now it is running. Here you are :-
import java.util.*;
class yearst
{
static int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
static int i=1,s,s1=0,s2=0,s3=0,k,diy=365,m,m1,m2,d1,d2,y1,y2,y;
static void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
//i=1;s1=0;s2=0;s3=0;diy=365;
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
leap(i+1);
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s);
}
}
All the Best :)
Only declarations and static blocks allowed out of the methods. The below executable statement must be either in static block or in constructor
int i=1,s1=0,s2=0,s3=0,diy=365;
So, I recommend you move above code to constructor.
yearst(){
i=1;s1=0;s2=0;s3=0;diy=365;
}
A few things:
You'll need to initialize your variables inside a constructor, as initializing inside a class isn't allowed
Have you checked out the Date class in Java? It might be more useful for this case.
According to convention, class names should start with a capital letter

Try and Catch into a method

I'm trying to put a try-catch into a procedure type method but I'm 95% sure it has to be a function type. What I'm trying to accomplish is to make my code shorter in the main. One of the biggest things I thought of was to put a try-catch into a method and call the method.
The thing is, it will validate the input if it is a integer or not- it even catches the exceptions the problem is that it doesn't "remember" the validated input once it continues on with the program/calculates. Here's the part of the code I'm having trouble with.
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
And here is the entire program:
import java.util.Scanner;
public class ch7exercise1
{
public static double compound(double oA, double cI)
{
return roundCent((oA*(Math.pow((1+(percent(cI))),10))));
}
public static double percent(double interest)
{
return interest/100.0;
}
public static double roundCent(double amount)
{
return ((Math.round(amount*100))/100.0); //100.0 is mandatory.
}
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
#SuppressWarnings("unused")
public static void main(String[] args)
{
boolean f = true;
boolean f2 = true;
double origAmount = 0;
double compInterest = 0;
double total = 0;
Scanner iConsole = new Scanner(System.in);
System.out.println("10 year Compound Interest Claculator\n");
System.out.println("Input amount of money deposited in the bank");
tryCatchNum(origAmount);
System.out.println("Input compouded interest rate. (If the compound interest is 3% input 3)");
tryCatchNum(compInterest);
total = compound(origAmount,compInterest);
System.out.println("$"+total);
}
}
Java arguments are passed by value. You're passing 0 to the tryCatchNum method. A copy of the value is passed to the method. This method assigns a new value to its own copy, and then returns. So the original value is still 0.
You must not pass anything to the method. Instead, the method must return the value it has validated. Also, consider using a more appropriate method name:
public double readDoubleValue() {
...
return value;
}
And in the main method:
double origAmount = readDoubleValue();
Since double is a primitive in Java it is passed by value to the method, therefore when you alter the value of the primitive the changes to the method parameter are not reflected in the original variable passed into the method call.
Read the cup story on Java ranch which explains pass by value and pass by reference.
http://www.javaranch.com/campfire/StoryCups.jsp
The next story to read is the Pass By Value story on Java Ranch.
http://www.javaranch.com/campfire/StoryPassBy.jsp
You should alter your method so that it returns a double which is assigned to value in the main method of your program.
I am also very curious as to why you are using a while loop that checks true. I think it is highly likely your program will encounter an infinite loop if the value entered cannot be converted to a double.

Categories

Resources