I'm trying to take input by using code int rs=Integer.parseInt(args[0]); but it throw exception ArrayOutOfBondException. Please help me code is below.I need to take input only one time in commandline argument
package techgig;
import java.util.*;
public class Techgig {
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
public static void main(String[] args) {
Vector v = new Vector();
// TODO code application logic here
System.out.println("Amount Mark has:");
System.out.println("=============================");//here is the code
int rs=Integer.parseInt(args[0]);
// int rs=50;
System.out.print("===============================");
//int a=0;
int count=0;
int min=0,temp,totalamount=0;
System.out.print("\nToys Available:{");
for(int a=0;a<ta.length;a++)
{
if(a!=0)
{
System.out.print(",");
}
System.out.print(ta[a]);
}
System.out.print("}\n");
System.out.println("Buy Maximum toys with maximum left");
for(int i=0;i<ta.length;i++)
{
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[j]<ta[i])
{
temp=ta[j];
ta[j]=ta[i];
ta[i]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
for(int k=0;k<ta.length;k++)
{
totalamount=min;
// System.out.print("\t"+ ta[k]);
min=min+ta[k];
if(min >rs)
{
break;
}
count=count+1;
v.add(ta[k]);
}
int sav=0;
sav=rs-totalamount;
//System.out.println("Amount Mark has:"+rs);
System.out.println("Output:{"+v.size()+","+sav+"}");
System.out.println("Explanation");
System.out.println("Maximum number of toys="+v.size()+""+v);
System.out.println("Saving="+sav);
}
}
You need to pass command line arguments while running java program.
If you don't pass any command line arguments then args will be empty array, that is with length 0. And accessing 0th element from empty array will throw ArrayIndexOutOfBoundsException.
If you want to use args[0] you need to pass command line arguments to the program. If you're running your program from an IDE, you will get the exception that you get.
Let the name of the class having your main method is MyClass.java Then you must run your program from command line like
java MyClass 12
Where 12 is the command line argument which you are passing to your program(you may try with different argument)
Note: When you will not pass any argument but access the args in your program then you will see this exception originating
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());
}
So i have been at this same example problem for a week now. I know that it may
seem easy, but i am finding that the more i look at it or alter it, the more
confused i get. I feel like i am making this a lot more difficult than it
needs to be. The array that i loaded displays correctly in the Try-Catch section, but i need to display it in its own method, which i call listOfAges(). What would this look like? Any responses are appreciated, please help.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray;
int ageCount = 0;
int age;
String filename = "ageData.dat";
anArray = new int[50];
/* The file has 50 numbers which represent an employee's age */
try {
Scanner infile = new Scanner(new FileInputStream(filename));
while (infile.hasNext()) {
age = infile.nextInt();
ageCount += 1;
System.out.println(ageCount + ". " + age + "\n");
/*
* When i run just this, the output is correct...
*
* But i don't want the output here, i just want to gather
* the information from the file and place it at the bottom inside
* the method displayAges().*/
}
infile.close();
} catch (IOException ex) {
ageCount = -1;
ex.printStackTrace();
}
public void listOfAges() {
System.out.print(" I want to display the data gathered from ageData.dat in this method ");
System.out.print(" Also, i receive this error message when i try: 'Illegal modifier for parameter listOfAges; only final is permitted' ")
}
}
}
First, you have to store your values in your array:
while (infile.hasNext()) {
age = infile.nextInt();
anArray[ageCount] = age;
ageCount += 1;
}
Your next problem is that you defined your listOfAges() method inside your main() method. The definition must be outside. You also need to pass your array as an argument to your method so that you can iterate over the array values to print them:
public void listOfAges(int[] ages) {
// use a loop here to print all your array contents
}
So I'm assuming you want to display each element in the array in your method. Your first problem is that the main method is static and you're trying to call a method that isn't static (listOfAges). Change this by simply adding the word static to the method to make it static. You also put this method in the main method. You'll need to move it outside of the brackets.
Second, to display the content you need to loop through it but the array you're holding the data in needs to be outside of the main method. Instead of having
int[] anArray;
In the main method, delete that and move it above the declaration of the main method. You'll also need to make it a static variable.
static int[] anArray;
Finally in the listOfAges, add the code to loop through it.
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray.length + ". " + anArray[i]);
}
I'm not 100% sure what you're asking but here:
At
} infile.close(); } catch (IOException ex) { ageCount = -1; ex.printStackTrace(); }
In your While.infile loop you're closing your while loop on the } infile.close() instead of opening a new one. So just change it to { infile.close (); } instead...
Since I'm not sure what you're exactly asking this will be the best answer I can give youx , hope I helped.
i´m almost freaking out because of the following problem:
public class FileMate {
public static void main(String[] args) {
Walker walker = new Walker();
int mode = Integer.parseInt(args[0]);
Checker.mode = mode;
List<String> drives = new ArrayList<String>();
for (int i=1; i == args.length; i++) {
drives.add(args[i]+":\\");
}
for (String path : drives) {
walker.walk(path);
}
}
}
The first argument is an integer and gets succesfully assigned to "mode".
But the part where the drive letters should be assigned to the list "drives" getting skipped at runtime.
I already debugged it step by step and the args array contains the mode and the 2 drive letters.
The for loop condition must be true for the loop to run, not for it to stop. Change your condition to:
i < args.length
Incidentally, you may want to check the length of the args array before you start accessing it, just in case the user didn't provide any arguments.
I am trying to run this program but I cannot, the compiler is sending me a ".class" error.
Can somebody help me with my problem and if it is possible a general tip about ".class" error?
Here is the program:
import java.io.*;
class Bus
{
private int kostos;
private int plithos;
private int typepiv;
Bus(int x,int y,int z)
{
kostos=x;
plithos=y;
typepiv=z;
}
public void KB(int[] x)
{
try{
for(int i=1;i<5;i++)
{
if(typepiv==2)
{
plithos=plithos+plithos/2;
kostos=kostos-kostos/2;
}
if(typepiv==3)
{
plithos=plithos-plithos/5;
kostos=kostos-kostos*25/100;
}
if(typepiv==1)
{
plithos=plithos;
kostos=kostos;
}
x[i]=plithos*kostos;
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
class testBus
{
public static void main(String args[])
{
String leof[]=new String[4];
int leof1[][]=new int[4][3];
for(int i=1;i<5;i++)
{
System.out.println("dwste onoma leoforiou");
leof[i]=UserInput.getString();
System.out.println("dwste kostos thesis enilika");
leof1[i][1]=UserInput.getInteger();
System.out.println("dwste plithos thesewn");
leof1[i][2]=UserInput.getInteger();
System.out.println("dwste tupos epibath gia enilikes=1,gia
paidia=2,gia suntaksiouxous=3");
leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
----->leof2.KB(KostEnoik);
System.out.print("onoleo");
System.out.print(" ");
System.out.print("plithos");
System.out.print(" ");
System.out.print("kost(EURO)");
System.out.print("typepiv");
System.out.print(" ");
System.out.print("apotelesma kostEnoik");
for(int g=1;g<5;g++)
{
System.out.print(leof[g]);
System.out.print(leof1[g][2]);
System.out.print(leof1[g][1]);
System.out.print(leof1[g][3]);
System.out.print(KostEnoik[g]);
}
}
}
the compiler message says :
testBus.java:56:error:cannot find symbol
leof2.KB(KostEnoik);
symbol:bariable leof2
location:class testBus
1 error
Remove the array brackets [] when invoking KB
leof2.KB(KostEnoik);
and remove the preceding enclosing brace }.
Aside: Java naming conventions indicate that variables start with a lowercase letter e.g. kostEnoik. Also consider giving the method KB a meaningful name, e.g. calculateCost
Read Java naming conventions
concern is with your access
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it is defined i.e. outside for loop and scope is upto for loop and that's why the compiler will not be able to find that varialble .
leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it's defined (in this particular case, the for loop) and that's not allowed.
method KB takes an int array as argument, but you don't have to add the [] when passing the argument. The correct line is
leof2.KB(KostEnoik);
However, there's something pretty odd with you logic: you're repeatedly (for loop) setting leof2, but only the last iteration of the loop will have any effect. I'm almost certain that that's not what you actually want, but the correct answer to where Bus leof2 should actually be defined depends on the correction of that issue.
leof2.KB(KostEnoik); this is the main culprit. whether you have imported UserInput.
Also try to go through the Java Basics
any method can be invoked using object when it is non static or class name when it is static. Please consider this link
Get leof2 object out side the For Loop.
Don't type [] when you pass the array as argument "leof2.KB(KostEnoik[]);".
I have a problem in NetBeans with Command-Line Arguments, when run this code it says
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Note I put an argument in command line for NetBeans
public class NewEmpty1
{
public static void main(String arg[]){
System.out.println(arg[0]);
}
}
What is wrong ?
goto Project-Property-Run here you will see the option
main class
arguments
now make sure you are accessing the correct main class....after this option you have button to browse the class path. select it and then select the arguments finally you should be able to run the program...cheers!
Ashish
You have not passed any arguments..
And if you have passed arguments then it may be because you are invoking another class main method in the same package
the best way would be to iterate..
for(string s:arg)
System.out.println(s);
or
for(int i=0;i<arg.length();i++)
System.out.println(arg[i]);
subscript the string beyond its index is undefined.
this is your case. args[] is empty.
check this How to pass cmd line argument
public class NewMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int argslen=args.length;
int argsValue[] = new int[argslen];
for (String i:args) {
int d = 0;
argsValue[d]=Integer.parseInt(i);
System.out.print(argsValue[d]+"\t"+"\n");
}
}
}