could not figure out the exception in this code snippet of java - java

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.

Related

Program that returns input \t as *

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.

Parsing Ints to Strings from Scanner in Try Catch

I've been given a task that I have to create a Shopping List program. I've done this in Python, and it was relatively straight forward. However, in Java I've hit a bit of a roadblock.
These are my variables, I am aware of the issues with using statics in this way and that it would be best to avoid doing it.
private static Scanner input = new Scanner(System.in);
private static String list_add = "string"; //"string" is just a place holder
private static ArrayList listFull = new ArrayList();
private static ArrayList listPos = new ArrayList();
private static int userIn = 1; //1 is also being used as place holder
Which I use in:
private static void userInput() {
boolean isValid = false;
while (!isValid) {
isValid = true;
try {
userIn=Integer.parseInt(input.next());
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number!");
isValid = false;
}
}
}
The reasoning behind doing it this way is the less one needs to type the quicker the task can be completed. Which was working as nice philosophy up until I tried this. My previous attempt to solve this problem gave an infinite loop, and the second solution that came to mind returned a StackOverflowError. When I asked about avoiding the infinite loop, I was directed to another question (Endless loop while using "try and catch " block inside a "while loop") which I did not believe helpful to begin with, however found that it was (Thank you whoever marked that). I didn't get this solution to work, however, and I cannot see where I went wrong.
After trying different inputs to see if their was one specific type that killed it, these were the errors I received:
Test Case "strin":
Exception in thread "main" java.lang.NumberFormatException: For input string: "strin"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at DebuggingMethods.AllIn(DebuggingMethods.java:17)
at DebuggingMethods.Menu(DebuggingMethods.java:33)
at DebuggingMethods.main(DebuggingMethods.java:58)
Test Case "Ten":
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ten"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at DebuggingMethods.AllIn(DebuggingMethods.java:17)
at DebuggingMethods.Menu(DebuggingMethods.java:33)
at DebuggingMethods.main(DebuggingMethods.java:58)
Test Case int(10):
Which ran with the anticipated outcome.
I had thought that I was missing a module, so I did import java.lang.*; which did not change the error. If someone has a solution, please help me out. I can't find a question that already posted that explains what I am doing wrong. When I pulled it out of the Try-Catch it was working kind of.
Full Piece
import java.util.InputMismatchException;
import java.util.*;
import java.util.Scanner;
import java.lang.*;
public class TestOne {
private static Scanner input = new Scanner(System.in);
private static String list_add = "string";
private static ArrayList listFull = new ArrayList();
private static ArrayList listPos = new ArrayList();
private static int userIn = 1;
private static void userInput() {
boolean isValid = false;
while (!isValid) {
isValid = true;
try {
userIn=Integer.parseInt(input.next());
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number!");
isValid = false;
}
}
}
public static void main(String[] args) {
//titleMain();
userInput(); // For the sake of demonstration
}
}
You've got your exceptions mixed up. You're catching an InputMismatchException, which is what input.nextInt() would have thrown if the input were invalid. But you're actually using Integer.parseInt to parse the input, which throws NumberFormatException in case of invalid input. And since NumberFormatException isn't a subclass of InputMismatchException, it isn't caught and you end up dying with a stack trace.
You don't actually need to do anything with exception at all here. The Scanner can tell you if the next input is a valid integer or not and you can then actively decide what do about it. Think along these lines:
Scanner sc;
//...
System.out.println("Please enter a number");
while (!sc.hasNextInt()){
sc.nextLine(); // throw away the bad input
System.out.println("Please enter a valid number");
}
int theNum = sc.nextInt();

Java exception with scanner

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.

nextInt() in java

I have heard that nextInt() reads only the integers and ignores the \n at the end.
So why does the following code runs successfully?
Why there is no error after we enter value of a since \n must remain in the buffer ,
so use of nextInt() at b should give an error but it doesn't . Why?
import java.util.Scanner;
public class useofScanner {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int a = scanner.nextInt();
int b=scanner.nextInt();
System.out.println(a+b);
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
As another example, this code allows long types to be assigned from entries in a file myNumbers:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
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();
prints the following output:
1
2
red
blue

NoSuchElementException when trying to call kb.nextInt()

Quick question. Still fairly new to Java and my test class is giving me this error.
Please enter length of tail: Exception in thread "main" java.util.NoSuchElementException
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)
at LeftArrow.drawHere(LeftArrow.java:18)
at ArrowTest.main(ArrowTest.java:75)
Here is the code for the test class
public class ArrowTest
{
public static void main(String args[])
{
RightArrow right = new RightArrow();
LeftArrow left = new LeftArrow();
System.out.println("RightArrow Class: Calling drawHere()");
right.drawHere();
System.out.println("LeftArrow Class: Calling drawHere()");
left.drawHere(); //Error pointing to this line
// (at ArrowTest.main(ArrowTest.java:75))
}
}
And here is the code for the RightArrow and LeftArrow classes, just the relevant code. I commented the lines that the error was referring to.
public class RightArrow extends ShapeBase
{
public void drawHere()
{
int lengthTail, widthHead;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter length of tail: ");
lengthTail = kb.nextInt();
System.out.print("Please enter an odd numbered width of arrowhead: ");
widthHead = kb.nextInt();
}
public class LeftArrow extends ShapeBase
{
public void drawHere()
{
int lengthTail, widthHead;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter length of tail: ");
lengthTail = kb.nextInt(); //Error pointing to this line at LeftArrow.drawHere(LeftArrow.java:18)
System.out.print("Please enter an odd numbered width of arrowhead: ");
widthHead = kb.nextInt();
}
I commented out the right.drawHere() in the test class and it seemed to work okay. So I am fairly convinced it is because I am calling the same method from two classes derived from the same abstract class. Is there a way that I can fix this? Thanks for your help!
EDIT: I found that if I don't close the kb from the first arrow class called upon it does not throw this error. I can only assume its because of me closing System.in which is why it's causing a problem. Can anyone explain to me why making another instance of Scanner(System.in) doesn't just re-"open" System.in?
Before calling the nextInt method, you can use the hasNextInt() method on the scanner object to check if there is a value to get, which can be used to avoid exception. Try this:
if (kb.hasNextInt()){
lengthTail = kb.nextInt();
}
In your case, I think you are not providing enough inputs, which could lead to NoSuchInputException.
Have a look at the Scanner class doc for more information.
The problem is with Scanner object where while you calling right.drawHere() there you initialized the Scanner kb with System.in this will buffer through all data available in System.in left it empty for future use therefore it is throwing NoSuchElementException in left.drawHere().
Solution:
Make Scanner object kb as static and accessible for both LeftArrow and RightArrow

Categories

Resources