I was wondering how I could check args.length within a method.
For example:
public static void commandLineCheck (int first, int second){
if (args.length==0){
//do something with first and second
}
}
public static void main(String[] args) {
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
commandLineCheck(first, second);
}
I get a "cannot find symbol: args" error when I do this. Right now, I'm thinking I need to pass args[] through the method as well. I've tried this but it then gives me an "" error. Is there a beginner-friendly solution to this?
EDIT: Thank you so much for the quick response guys! It worked!
Change your code like this (You need to pass the array's parameter to your check method)
public static void commandLineCheck (int first, int second, String[] args){
if (args.length==0){
//do something with first and second
}
}
public static void main(String[] args) {
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
commandLineCheck(first, second, args);
}
And it will work. However the following test (args.length==0)does not make much sense since you have already assumed that args.length is greater or equal to 2 by extracting two values from it inside the main method. Therefore when you get to your commandLineCheck method, this test will always be false.
You need to pass the String [] args to your commandLineCheck method. This is written the same way as you declare the array for your main method.
public static void commandLineCheck (String[] args){
if (args.length==0){
//do something with first and second
}
}
Also you probably want to change your main method and commandLineCheck method a bit.
public static void commandLineCheck(String [] args) {
/* make sure there are arguments, check that length >= 2*/
if (args.length >= 2){
//do something with first and second
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
}
}
public static void main(String[] args) {
commandLineCheck(args);
}
Related
I want to print the length of the first argument(args[0]) but getting ArrayOutOfBountException :
public class Main {
public static void main(String[] args){
args[0] = "Hello";
System.out.println(args[0].length());
}
}
Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.main(Main.java:3)
When you write the code,
public class Main {
public static void main(String[] args){
args[0] = "Hello";
System.out.println(args[0].length());
}
}
At this point args[0]="Hello";, If your args a String array is not initialized then, while execute I'm supposed to think that you may have used the command in such a way java Main to execute your basic program.
Which cause the error, You have not passed any argument through command line so your String[] args is not initialized yet and it is not able to store your String "Hello" inside array args[0] and you are trying to print an empty array and throw the Exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.main(Main.java:3)
Update Answer:
Now Yes, You can use that to verify the String args length before print.
public class Main {
public static void main(String[] args){
if(args.length !=0){
System.out.println(args[0].length());
}else{
args = new String[1]; //Initilize first
args[0] = "Hello"; //Store value in array element
System.out.println(args[0].length()); //Print it.
}
}
}
First, check if there is an argument. Then print the length. It's not a good idea to change the values in the argument array either. Something like
if (args.length > 0) {
System.out.println(args[0].length);
} else {
System.out.println(0);
}
should do it.
Here array of String does not have any initialized objects and args has 0 element. That's why it is recommended to check whether does args have any element or not. Then, proceed further accordingly. This is how code looks like.
public class Main {
public static void main(String[] args){
if(args.length !=0){
// do something
}else{
// args doesn't have element.
return ;
}
}
}
You need to check first if an argument is even present.If there is no argument passed and you try to access any element, it will throw ArrayIndexOutOfBoundsException. Also, you should avoid assign any hardcoded value to the elements in array. The code to access 1st element can be something like below:-
if(args.length>0){
System.out.println(args[0].length());
}
I have an algorithm in my textbook written in pseudocode which is then supposed to be "implemented to a Java method". It goes like this:
read min;
while not eoln do
read x
if x < min then
min <- x
end if
end while
print min;
Then I'm given this code:
import java.util.Scanner;
int min() {
Scanner input = new Scanner(System.in);
System.out.println("x=? (999 to end)");
int x = input.nextInt();
int min = x;
while (x!=999) {
System.out.println("x=? (999 to end)");
x = input.nextInt();
if (x < min) {
min = x;
}
}
return min;
}
I put everything below import.Scanner inside of the main method and inside of a class like this:
public class MyAlgorithm {
public static void main(String[] args) {
// code here
}
}
But then I get this error message in Terminal:
MyAlgorithm.java:7: error: ';' expected
int min() {
^
1 error
Am I missing something? If I put the semicolon there, the whole thing just won't work.
It seems like you put your min method inside of main, this is defining methods from within other methods which will not work properly and cannot compile. The main method is the commands you want to run as soon as you start your program, any other functions in the class should be declared outside of it, and if you want them to run in main you do a method call.
it should look something like this:
import java.util.Scanner;
public class MyAlgorithm {
int min() {
//(min code)
}
public static void main(String[] args) {
// code here
//corrected according to Uli's comment
MyAlgorithm m = new MyAlgorithm();
int result = m.min();
}
}
I suggest reading up on how java programs are structured. Here's an article on methods.
Don't put your method min() inside the main() method. In Java, you can not define a method inside a method. In Java, you need an object to call its methods (Except you make the methods static). So your final Code looks something like this.
import java.util.Scanner;
public class MyAlgorithm {
public static void main(String[] args) {
MyAlgorithm m = new MyAlgorithm ();
m.min();
}
int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
}
If you are allowed to use static methods, (which I don't think) you can use the following alternative:
static int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
public static void main(String[] args) {
int result = MyAlgorithm.min();
}
Why is it possible for a variable to call (initialise itself) a method that calls the same variable (seems a recursion)? I expected to see an endless recursion, but it compiles without errors. Any explanation?
class Forward {
static int test(){
return i;
}
static int i=test();
public static void main(String[] args) {
System.out.println(test()); //sout= 0
System.out.println(i); //sout =0
}
}
Another example. Why does referencing Backwards.j work while referencing j gives an error("illegal forward reference"):
class Backwards{
//static int i=j; //illegal forward reference;
static int i=Backwards.j; //reference through class works
static int j=i;
public static void main(String[] args) {
System.out.println(i);
System.out.println(j);
}
}
If you step through the code in your debugger you will see that i = test(); is only run once ever.
The previous value for i is 0 and that's the value test() returns before i has been initialised.
The java compiler can't detect every possible forward reference, only the simplest ones.
I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}
package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?
you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList
You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...
Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.
You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..
You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.