I have a problem with the scanner. When I compile it, there are no problems. but when I want to run this program, I get an exception. Can any of you explain me the reason of this problem?
import java.util.Scanner;
public class CiagArytmetyczny {
public static void main(String[] args) {
Scanner s = new Scanner("System.in");
System.out.println("Podaj dlugosc ciagu: ");
int dl = s.nextInt();
int element = 2;
for(int i=1; i<=dl; i++) {
element=element+3;
System.out.println(element);
}
}
}
Podaj dlugosc ciagu:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at CiagArytmetyczny.main(CiagArytmetyczny.java:8)
Process completed.
You have a problem in this line
Scanner s = new Scanner("System.in");
You are passing a string to the Scanner constructor. According to the java docs (Scanner(String source)), a new Scanner that produces values scanned from the specified string will be returned. According to the rest of your program, a String with a number should be provided for the scanner to pick up in the following line.
int dl = s.nextInt();
If you intend to get input from the console, Please change the scanner initialization as follows.
There are few more constructors to Scanner, I suggest you have a look at the java docs.
Scanner s = new Scanner(System.in);
This will give the console input stream to the Scanner.
Related
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);
I'm studying Java classes and I'm trying to create a code where the user inputs how many objects (in this case "cube") they want to create.
In my main class I have this code written
System.out.println("Enter the amount of objects you want to create");
Scanner objNumInput = new Scanner(System.in);
int objNum = objNumInput.nextInt();
objNumInput.close();
Cube cubes[] = new Cube[objNum];
for (int i = 0; i < objNum; i++){
String cubeName = Cube.inputName();
double cubeLength = Cube.inputLength();
cubes[i] = new Cube(cubeName, cubeLength);
}
in my Cube class I have here:
public static String inputName(){
String cubeName;
Scanner input = new Scanner(System.in);
System.out.println("Enter the name: ");
cubeName = input.nextLine();
return cubeName;
}
public static double inputLength(){
double cubeLength;
Scanner input = new Scanner(System.in);
System.out.println("Enter the length: ");
cubeLength = input.nextDouble();
return cubeLength;
}
When I run it, I can input the number of "cubes" I want to create. Then, it keeps throwing an exception
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Cube.inputName(Cube.java:40)
at Main.main(Main.java:88)
what's wrong?
Do not close your Scanner, it will close System.in as well.
When a Scanner is closed, it will close its input source if the source implements the Closeable interface
As I understand (correct me if I'm wrong) the reason why you close your objNumInput is that you want to use it in two different methods.
I would suggest you to pass the Scanner as input parameter into your methods inputName and inputLength. Then you'll be able to reuse the same scanner without closing it in between.
public static String inputName(Scanner scanner){
String cubeName;
System.out.println("Enter the name: ");
cubeName = scanner.nextLine();
return cubeName;
}
public static double inputLength(Scanner scanner){
double cubeLength;
System.out.println("Enter the length: ");
cubeLength = scanner.nextDouble();
return cubeLength;
}
...
System.out.println("Enter the amount of objects you want to create");
Scanner objNumInput = new Scanner(System.in);
int objNum = objNumInput.nextInt();
//objNumInput.close(); <-- Do not close the scanner
Cube cubes[] = new Cube[objNum];
for (int i = 0; i < objNum; i++){
String cubeName = Cube.inputName(objNumInput);
double cubeLength = Cube.inputLength(objNumInput);
cubes[i] = new Cube(cubeName, cubeLength);
}
put objNumInput.close(); after for loop in your main method.The reason your program flashes by without pausing the second time because System.in is closed when you do objNumInput.close(); in the line number 3 of main method
closing a Scanner object will close the underlying stream.
-your code only works one time because System.in is getting closed. You cannot "open" System.in again. A closed stream cannot be reopened
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.
This question already has answers here:
Scanner NoSuchElementException
(2 answers)
Closed 7 years ago.
I am executing the below code to read a string from the input stream with the scanner object.
public class Test{
public static void main(String[] args) {
String userInput1 = getUserInput();
System.out.println(userInput1);
String userInput2 = getUserInput();
System.out.println(userInput2);
}
private static String getUserInput() {
System.out.println("Enter the String");
Scanner scanner = new java.util.Scanner(System.in);
String input = scanner.next();
scanner.close();
return input;
}
}
The first invocation to the method getUserInput succeeded without any issues.But he second invocaton threw NoSuchElementException.
Enter the String
test1
test1
Enter the String
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
There are two problems with the code
It assumes that there already has been input. A simple while(!scanner.hasNext()){} before the locations where you call scanner.next(); should work.
You are creating many scanners (this may or may not impact the code, but does impact efficiency)
Instead, the Scanner scanner = new Scanner(System.in); can be broken up into a declaration (Scanner scanner;) outside a method and then defined (scanner = new Scanner(System.in);) in the main method or initialization code.
i have tried this code snippet but could not able to figure out the reason for this the exception.
my code is:-
import java.util.*;
class ScannerTest
{
public static void main(String[]args)
{
String csv = "Sue,5,true,3";
Scanner sc = new Scanner(csv);
sc.useDelimiter(",");
int age = sc.nextInt();
System.out.println(age);
}
}
Output is:-
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
i am new to java so please help me out to know the reason for this exception.
in the javadoc example you can see how it works:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
your first token is a string. if you use next int it expects an integer.
you might want to use something like this (under the conditions that you know the structure of the csv and it doesn't change):
public static void main(String[]args)
{
String csv = "Sue,5,true,3";
Scanner sc = new Scanner(csv);
sc.useDelimiter(",");
sc.next();
int age = sc.nextInt();
System.out.println(age);
}
or
public static void main(String[] args) {
String csv = "Sue,5,true,3";
String ageString = csv.split(",")[1];
System.out.println(ageString);
}
...
to parse a string into int:
int age = Integer.parseInt(ageString);
The Javadoc of the nextInt method of Scanner states
Scans the next token of the input as an int. This method will throw
InputMismatchException if the next token cannot be translated into a
valid int value as described below. If the translation is successful,
the scanner advances past the input that matched.
As your first token is a String, this is what's going on. As in most cases in CSV's you will know what will be presented, you should read them one by one, and/or use the hasNextInt method and its friends to check whether what you expect is actually there.
The scanner is expecting an integer type but the first token is a String - "Sue", To fix, place:
sc.next(); // skip "Sue"
before the call to nextInt() to consume the String token.