Reading numbers from file using Scanner - java

This is my simple program which counts the sum of the numbers in the file
int sum = 0;
try(Scanner s = new Scanner(new File(path)))
{
while (s.hasNextInt())
{
if (s.hasNextInt())
{
sum += s.nextInt();
}
else
{
s.next();
}
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println(sum);
Why it doesnt work if i do something like that:
Scanner s = new Scanner(path)
instead of
Scanner s = new Scanner(new File(path))

Your while loop loops only if s.hasNextInt() is true (because you wrote while (s.hasNextInt()). You then again check: if (s.hasNextInt().
This if is useless. Of course s.hasNextInt() is true. If it wasn't, the while loop wouldn't have looped!
It sounds like you want to do two things:
make that while (s.hasNext()) instead.
Fix your deplorable exception handling. Ditch the catch. Add throws IOException to the method (and to main if you want, psv main() can, and usually should, be declared as public static void main(String[] args) throws Exception. Less code, and errors with way more detail. Win-win.

Related

How to solve NoSuchElement in java?

It works well on Intellij.
However, NoSuchElement appears on the algorithmic solution site.
I know that NoSuchElement is a problem caused by trying to receive it even though there is no value entered.
But I wrote it so that the problem of NoSuchElement doesn't occur.
Because given str, the for statement executes. Given "END", the if statement is executed. And because it ends with "break;".
I don't know what the problem is.
Algorithm problem: Arrange the reverse sentence correctly.
My code for algorithmic problems
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
Output
!edoc doog a tahW
erafraw enirambus detcirtsernu yraurbeF fo tsrif eht no nigeb ot dnetni eW
END
Expected
What a good code!
We intend to begin on the first of February unrestricted submarine warfare
This happens when there is no input at all, for example when you hit Ctrl + d or run your code like echo "" | java Main.java.
To avoid this, check that the Scanner actually has input before trying to grab the next line. Pull scan out of the loop, there is no point to create a new Scanner for each line anyway. Then use hasNext to see if there is input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}

Scanner.next() taking in more than 1 word in loop

I am making a game in my java class, and I am trying to ask users what kind of difficulty they want to play. However, it seems that the IN.next() is taking in more than 1 word because it is in a loop. How do I get it to take only the first word?
public int configureDifficulty() {
String level = "1";
println("At what difficulty would you like to play at?");
println("Type 1 for easy, 2 for medium, 3 for hard.");
while (true) {
level = IN.next();
try {
return Integer.parseInt(level);
}
catch (NumberFormatException ex) {
println("Try again");
}
}
}
Console
At what difficulty would you like to play at?
Type 1 for easy, 2 for medium, 3 for hard.
test test test test test
Try again
Try again
Try again
Try again
Try again
How to make my program prints just one "Try Again" line, even if users type more than 1 word?
You can use nextLine method of Scanner to read input as String and then later convert it like you want. You can do something like this.
import java.util.*;
class GFG {
public static void main (String[] args) {
int d = configureDifficulty();
System.out.println(d);
}
public static int configureDifficulty() {
String level = "1";
System.out.println("At what difficulty would you like to play at?");
System.out.println("Type 1 for easy, 2 for medium, 3 for hard.");
Scanner in = new Scanner(System.in);
while (true) {
level = in.nextLine();
try {
return Integer.parseInt(level);
}
catch (NumberFormatException ex) {
System.out.println("Try again");
}
}
}
}
If you want to take care of words typed on the same line, you will have to use nextLine method in scanner. The method will return a string and then you will have to parse and write the logic.
What you want to read is an integer (1,2 or 3) to determine difficulty, so I suggest you to use scanner.nextInt() so that you don't need to do the parsing and the extra try-catch block.
Also, you haven't given your complete code(how scanner object is initialized and used in other places) but with whatever you have given, I don't see next() consuming more than one character. If it does and you don't want to replace it with scanner.nextInt(), use scanner.nextLine() instead. Hope this helps
public static void main(String[] args) {
String level = "1";
System.out.println("At what difficulty would you like to play at?");
System.out.println("Type 1 for easy, 2 for medium, 3 for hard.");
Scanner scan = new Scanner(System.in);
while(true)
{
System.out.println(scan.nextInt());
}
}

Difference between these two

I was trying to solve the problem on spoj but my answer is not accepting giving wrong answer i want to know difference between these two chunks of code.
Spoj accepting this
public class Test {
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader r = new java.io.BufferedReader(
new java.io.InputStreamReader(System.in));
String s;
while (!(s = r.readLine()).startsWith("42"))
System.out.println(s);
}
}
but Spoj not accepting this
class Test {
public static void main(String[] args) throws java.io.IOException {
new Test().universe();
}
public void universe() throws java.io.IOException {
System.out.println("Enter Number");
java.util.Scanner scan = new java.util.Scanner(System.in);
String input;
while (!(input = scan.next()).startsWith("42")){
System.out.println(input);
}
scan.close();
}
}
here's the problem http://www.spoj.com/problems/TEST/
The first snippet reads the file line by line whereas the other one reads token by token. If there are more than one token per line, the result may be different.
Finally, both codes take the risk of reading the file without checking there is still something to read. In the first case it could throw a NullPointerException and in the second case a NoSuchElementException.
The difference is that scan.next() is a blocking call - if there's no input, the call will wait until there is input.
You need to change your loop for the scanner to this:
while (scan.hasNext()) {
String input = scan.next();
if (input.startsWith("42")) {
System.out.println(input);
}
}
Next is reading next token, maybe you meant nextLine.
Also, you are printing "Enter number" in the latter.

JAVA Exception in thread main java.util.no such element

I encountered an error when executing my program.
I execute my program and fed data in an input file.
Contents of the input file
LIMIT
2
ADD 30 60
MUL -60 60
I got an exception error as follows.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Test.doLimit(Test.java:41)
at Test.checkResult(Test.java:24)
at Test.main(Test.java:15)
I googled and I believed that String input = sc.next(); inside the for loop should be causing the error.
May I know how to resolve this error?
My code is as attached below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
checkResult(input);
}
public static void checkResult(String input)
{
if(input.equals("LIMIT"))
{
//do stuff
doLimit();
}
else if(input.equals("SENT"))
{
//do stuff
}
else
{
//do stuff
}
}
public static void doLimit()
{
Scanner sc = new Scanner(System.in);
int numOfInput = sc.nextInt();
int x,y;
for(int i = 0; i < numOfInput; i++)
{
String input = sc.next();
x = sc.nextInt();
y = sc.nextInt();
if(input.equals("ADD"))
{
//add
}
else if(input.equals("SUB"))
{
//sub
}
else
{
//multiple
}
}
}
You should check if there is more input. You can see in the stack trace that nextInt is involved and if you look at the SDK you would see that this exception is thrown when
input is exausted.
anyway you problem is here :
int numOfInput = sc.nextInt();
so make sure you have valid input before asking for it :
if (sc.hasNextInt()) {
.
.
.
}
The default delimiter of the scanner is the whitespace. However, you plan to use as input for the first 2 lines the new line as delimiter and then either whitespace and new line, as it comes first. Maybe that is the problem. Try writing everything on one line, whitespace separated.
If you are sending the data through the input file, you have to provide that file in the Scanner() constructor.
What you have currently done is provided System.in.
EDIT :
Also, you have to open the Scanner on the file just once and use it throughout. In this case,
1) You are opening the scanner and reading the first line.
2) Then in the doLimit function, you again open the scanner and read the first line of the input file which is not an integer.
Hence, the error.

Is it possible to call the main(String[] args) after catching an exception?

I'm working on a Serpinski triangle program that asks the user for the levels of triangles to draw. In the interests of idiot-proofing my program, I put this in:
Scanner input= new Scanner(System.in);
System.out.println(msg);
try {
level= input.nextInt();
} catch (Exception e) {
System.out.print(warning);
//restart main method
}
Is it possible, if the user punches in a letter or symbol, to restart the main method after the exception has been caught?
You can prevent the Scanner from throwing InputMismatchException by using hasNextInt():
if (input.hasNextInt()) {
level = input.nextInt();
...
}
This is an often forgotten fact: you can always prevent a Scanner from throwing InputMismatchException on nextXXX() by first ensuring hasNextXXX().
But to answer your question, yes, you can invoke main(String[]) just like any other method.
See also
(Java) Opinion: Preventing Exceptions vs. Catching Exceptions
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Note: to use hasNextXXX() in a loop, you have to skip past the "garbage" input that causes it to return false. You can do this by, say, calling and discarding nextLine().
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
System.out.println("int, please!");
sc.nextLine(); // discard!
}
int i = sc.nextInt(); // guaranteed not to throw InputMismatchException
Well, you can call it recursively: main(args), but you'd better use a while loop.
You much better want to do this:
boolean loop = true;
Scanner input= new Scanner(System.in);
System.out.println(msg);
do{
try {
level= input.nextInt();
loop = false;
} catch (Exception e) {
System.out.print(warning);
//restart main method
loop = true;
}
while(loop);

Categories