so I am learning how to pass files as argument in java. I am trying to implement a scheduling algorithm in java but my issue is the console shows the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
Since I am totally new to this, I am not sure where I am doing wrong. I can get the program to scan the input text file normally using an object from the scanner class but when I try and pass it as an argument, I get the above error. How do I fix this error? The program below is not the full program but big enough to compile and show the error I am getting. I am using an online IDE atm and I have a 'file.txt' that contains integer values I want. I believe the error's got something to do with the args statement. Can anyone help me fix this please?
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
int i=0,j=0;
if(args.length<1)
{
System.out.println("ERRRRRRRORRRRRR!");
}
File file = new File(args[0]);
Scanner scan = new Scanner(new File(args[0]));
int n= scan.nextInt();
int process_id[] = new int[n];
int burst_time[] = new int[n];
int arrival_time[] = new int[n];
n=0;
while(n<3){
process_id[i]= scan.nextInt();
burst_time[i]= scan.nextInt();
arrival_time[i]= scan.nextInt();
n++;
i++;
}
}
}
you need to 'return' out of main when args.length<1.
Your code detects the empty args but do nothing with it.
either you need to put your logic in else part or you need to stop program in if condition by return or System.exit(0);
Related
I need to pull integers from a text file and sum them up. I came up with this but I keep getting an error. What am I missing? I need to use a scanner class.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class txtClass {
public static void main(String[] args) throws FileNotFoundException {
File txtFile = new File(//text file path//);
Scanner scan = new Scanner(txtFile);
int length = 0;
while(scan.hasNextLine()) {
scan.nextLine();
length++;
}
int array[] = new int [length];
array[length++] = scan.nextInt();
System.out.println(array.toString());
int h = 0;
for (int i = 0; i<array.length; i++)
{
h +=array[i];
}
scan.close();
System.out.print(h);
}
}
As suggested, a lot of the code is not really needed. But presumably the 'error' you get is array index out of bounds. Here:
int array[] = new int [length];
array[length++] = scan.nextInt();
So you allocate an array and immediately access off the end of the array. Let's assume length is 42. Therefore, the allocated array elements have indexes 0 to 41. You try and assign something to array[42]. I'm not sure what you're trying to do with that line.
The alternative guess (which we would not need to guess had you mentioned the actual error message) is that your counting lines leaves the scanner positioned at end of file. so the scan.nextInt() call in the assignment gets you an I/O error.
In any case, the core of the solution is something like
int sum = 0;
while (scan.hasNextInt())
sum += scan.nextInt();
No array is needed.
You wrote in your question
I keep getting an error
That would be NoSuchElementException which is thrown by this line of your code:
array[length++] = scan.nextInt();
This is because you have already scanned the entire file and therefore there is no next int.
Remember that in order for people to help you with errors thrown by your code, you need to post the actual exception and the stack trace as well as your code.
You don't need to save all the numbers in the file in an array in order to get the sum of all the numbers. However if you also want to save all the numbers but you don't know in advance how many there are, you can use a List.
Here is a minimal example of how to read the file – which I assume contains only numbers separated by whitespace – and calculate the total. Of-course you need to replace text file path with the actual path to the text file.
File txtFile = new File("text file path");
try (Scanner scan = new Scanner(txtFile)) {
int total = 0;
while (scan.hasNextInt()) {
total += scan.nextInt();
}
System.out.println("Total: " + total);
}
catch (FileNotFoundException xFileNotFound) {
xFileNotFound.printStackTrace();
}
Note that the above code uses try-with-resources.
The code is supposed to read an unidentified number of inputs from the keyboard and return any tabs as *. My program seems to work when I run it in eclipse and get no errors. When I turn in the code on the submission website, this is the error I get.
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1589) at replaceHW.main(replaceHW.java:9)
import java.util.Scanner;
public class replaceHW {
public static void main(String[] args) {
//write a program that converts all TABS in your code
//with STARS i.e. *
Scanner in = new Scanner(System.in);
String ans;
while(!(ans = in.nextLine()).equals(""))
System.out.println(ans.replace("\t","*"));
}
}
Your problem is simple: nextLine() works in tandem with hasNextLine(): the correct code is:
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextLine()) {
String line = in.nextLine();
if (!"".equals(line)) {
System.out.println(ans.replace("\t","*"));
}
}
The try-with-resources is best practice. But be wary than with System.in, it will close it when done.
hasNextLine() will try to read has much input is needed to find a line.
I've been googling this but I still don't understand why this doesn't work. The user would enter an array of integers and I need to find how many elements are in that array.
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt()) {
n++;
s.next();
}
System.out.println(n);
I looked up if using variable outside the scope works, and I've been answers saying that if you're gonna use the variable outside the scope, you should declare and initialize outside the scope (in this case, the while loop). However, this still doesn't work for me. My code right now won't even print "0". Any help would be greatly appreciated.
When you read from command line you have to signal EOF (end of file), otherwise how will your program know if you have stopped entering your elements or not? On windows you can press Ctrl-D and your scanner will stop reading, for example.
You can break out of the loop with the condition that a word is entered, such as "exit" since you want to get an int count. Your code works to count the number of integers entered into a scanner, but you never declared an array to hold all the values.
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList array = new ArrayList(); //declare your array
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt())
{
n++;
s.next();
array.add(s);//store the array value
if (s.hasNext("exit"))//allow an exit to the loop
break;
}
System.out.println(array.size()); //better, use the size of the array
}
}
Your code works fine.
Check this link. https://ideone.com/vrnoEz
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt()) {
n++;
s.next();
}
System.out.println(n);
}
}
I am trying to get input from the Scanner class, but every time I call it, it crashes the entire program. When trying to catch the exception and print the message, nothing shows up, so I am not even sure what the root of the problem is. Some background info is that this class is being called by the main method, which also has a Scanner that was running, but is closed before this class's method is called.
public class UserHandler {
static Scanner userInput1 = new Scanner(System.in);
static void addInterface() throws IOException, FileNotFoundException{
boolean addMore = true;
while(addMore){
System.out.println("Please enter restaurant name: ");
String name = userInput1.next();
if(!FileHandler.containsName(name)){
System.out.println("Name already exists!");
}else{
String[] tags = new String[5];
System.out.print("\nPlease enter tags seperated by spaces: ");
for(int i = 0; i < tags.length; i++){
if(userInput1.hasNext()){
tags[i] = userInput1.next();
}
else{
break;
}
}
FileHandler.addName(name,tags);
}
}
}
}
I have tried several times, and was not able to reproduce this issue. I am assuming it is something to do with syntax, or something that is just not called properly. Either way I have spent quite some time trying to fix it, but to no avail.
I suppose that you get the access to the command-line from the first call to the Scanner(System.in), then you close it and when you try to access it the second time you receive IllegalStateException.
Try to use the same instance of the Scanner(System.in) in both situation.
For more info refer to http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
I am new to java and netbeans. I am trying to write a program that requires user input. This is my code:
public class Arrays {
public static void main(String[] args){
}
private double[] readNumbers(){
final Input in = new Input();
System.out.print("How many numbers will you enter?: ");
final int count = in.nextInt();
final double[] list = new double[count];
for (int i = 0; i < count; ++i){
System.out.print("Enter next number: ");
list[i] = in.nextDouble();
}
return list;
}
}
In line final Input in - new Input(); Netbeans underlines Input saying that it cannot find symbol. However I practically copied this code from the textbook so I don't understand what the problem is. I thought maybe I needed to import java.io, but that did not solve the problem. Really sorry if this is a stupid question, but any help would be really appreciated.
Thank you!
Looks like your text book has some class definition that you forgot to import to your project.
If you like to , change your code like,
final Input in = new Input();
to
final Scanner in = new Scanner(System.in);
If you don't want to change your code, then look few pages up and down the pages from where you got this code, you should see Class named Input , some what similar to this :
class Input{
public int nextInt(){
Scanner sc=new Scanner(System.in);
return sc.nextInt();
}
public double nextDouble(){
Scanner sc=new Scanner(System.in);
return sc.nextDouble();
}
}
Which is basically, an extra unnecessary work.
Include that in your project, and it should run fine.
Your code attempts to create an instance of class Input, but you don't include code for class Input. Resolve that (try the previous page in the book!) and your code will probably work.
Input may be a wrapper class for java.util.Scanner:
You could replace:
final Input in = new Input();
with
final Scanner in = new Scanner(System.in);