I have the following code and I cannot understand why .hasNext() wont turn false. I am reading from a file called test.
My code:
package printing;
import java.io.File;
import java.util.Scanner;
public class Printer {
public int count() throws Exception{
int num = 0;
File f = new File("C:\\Users\\bob\\Desktop\\test.txt");
Scanner in = new Scanner(f);
while (in.hasNext()){
num++;
}
return num;
}
}
Main:
public class Main {
public static void main(String[] args) throws Exception{
Printer mine = new Printer();
System.out.println(mine.count());
}
}
File content:
4
4
6
3
8
8
8
What is wrong?
You need to consume the input from the Scanner
while (in.hasNext()){
in.next();
num++;
}
You didn't consume any of the input. hasNext() doesn't consume any input.
The scanner does not advance past any input.
Add a call to next() inside the while loop to consume the input.
Related
How can I read-in an integer in this following program? It doesn't work. It doesn't compile at the moment.
/**
* Main class of the Java program.
*
*/
import java.util.Scanner;
//...
class Scanner{
Scanner in = new Scanner(System.in);
int num = in.nextInt();
}
public class Main {
public static void main(String[] args) {
// we print a heading and make it bigger using HTML formatting
System.out.println("<h4>-- Binaere Suche --</h4>");
int anzahl = 0; int zahl;
}
}
import java.util.Scanner;
// This will print what you want but will not make it look bigger as it
// will get printed in console
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
// we print a heading and make it bigger using HTML formatting
System.out.println("<h4>--"+num+" --</h4>");
}
}
I am trying to read the following from a text file:
12
650 64 1
16 1024 2
My attempt:
import java.util.Scanner;
import java.io.*;
class Test{
public static void main(String[] args){
String filnavn = "regneklynge.txt";
Scanner innFil = null;
try {
File fil = new File(filnavn);
innFil = new Scanner(fil);
while (innFil.hasNextLine()) {
String linje = innFil.nextLine();
int tall = Integer.parseInt(linje);
System.out.println(tall);
}
} catch(FileNotFoundException e) {
System.out.println("Filen kunne ikke finnes");
}
}
}
The first number(12) Works fine, but then I get this
Exception in thread "main" java.lang.NumberFormatException: For input string: "650 64 1"
Suggestions:
You need two while loops, one nested inside of the other
the first one, the outer loop, you loop while (innFile.hasNextLine()) {...}
inside this loop you call String linje = innFile.nextLine(); once
Then create a 2nd Scanner object, Scanner lineScanner = new Scanner(linje);
and create a 2nd inner while loop that loops while (lineScanner.hasNextInt() {...}
inside of this loop, extract a single int via int tall = lineScanner.nextInt();
and put it into your ArrayList.
Be sure to call lineScanner.close(); after exiting the inner while loop and before exiting the outer loop.
As long as you are reading the full line:
String linje = innFil.nextLine();
You can't treat them as an Integer because it's already a String
int tall = Integer.parseInt(linje);
// linje now has this = "650 64 1"
So that provokes the Exception:
java.lang.NumberFormatException
Here is an approach to print the numbers:
import java.util.Scanner;
import java.io.*;
class Test{
public static void main(String[] args){
String filnavn = "regneklynge.txt";
Scanner innFil = null;
try {
File fil = new File(filnavn);
innFil = new Scanner(fil);
while (innFil.hasNextLine()) {
if (innFil.hasNextInt()) {
System.out.println(innFil.nextInt());
} else {
innFil.next();
}
}
} catch(FileNotFoundException e) {
System.out.println("Filen kunne ikke finnes");
}
}
}
In C i do this:
int main(){
int N = 0;
while(scanf("%d",&N) != EOF){ // <--- how to do this condition in java?
... Code ...
}
My input is some numbers: 10 20 5 9 7 6... and when i hit enter my output is some matrix.
Print with example
I know there is another topic, here, similar to this, but not solve my problem.
Any suggestion?
My problem is solved by Elliot, i just do this:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
int N = 0;
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
N = (int) scanner.nextDouble();
... code ...
}
}
Working fine.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
I'm hoping this is just a simple error here, I've looked up numerous other instantces of people getting the same error message but none of their solutions really seem to apply for me. I was just wondering if you guys could help me find the error in my code. I'm not even sure if it's functional because I can't get it to run, so I suppose it could be a logic error.
When I try to run the following cold I am met with fatal exception error occured. Program will exit.
Eclipse also gives me:
java.lang.NoSuchMethodError: main
Exception in thread "main"
Thank you very much for any assistance you can offer!
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JoPuzzle
{
public static Integer main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of soliders");
int soldiers = input.nextInt();
System.out.println("Please enter the how many soldiers are skipped before the next death");
int count = input.nextInt();
List<Integer> soldiersList = new ArrayList<Integer>(soldiers);
for (int i = 1; i <= count; i++) {
soldiersList.add(i);
}
int currentIndex = 0;
while(soldiersList.size() > 1) {
currentIndex = (currentIndex - 1 + count) % soldiersList.size();
soldiersList.remove(currentIndex);
}
return soldiersList.get(0);
} //end main
}//end class
We know that to execute any java Program we should have a main function. because this is a self callable by JVM.
And the signature of the function must be..
public static void main(String[] args){
}
but in your code it's seem like this...
public static Integer main(String[] args){
}
so its consider as a different function , so change your main return type..
The signature for main method is
public static void main(String[] args).
When you run your program the JVM will look for this method to execute. You need to have this method in your code
Your program does not contain the main method, change it to
public static void main(String[] args)
If you want to return an Integer object, then define a custom mehod and call that method inside the main method and handle that returned value.
Java main() function doesn't have a return-statement. This line
public static Integer main(String[] args)
should be
public static void main(String [] args)
Also since it has no return value, you should delete the return statement.
Java's main method should have below signature.
public static void main(String[] args){
..
..
}
Try to run this code and tell if it works.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JoPuzzle
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of soliders");
int soldiers = input.nextInt();
System.out.println("Please enter the how many soldiers are skipped before the next death");
int count = input.nextInt();
List<Integer> soldiersList = new ArrayList<Integer>(soldiers);
for (int i = 1; i <= count; i++) {
soldiersList.add(i);
}
int currentIndex = 0;
while(soldiersList.size() > 1) {
currentIndex = (currentIndex - 1 + count) % soldiersList.size();
soldiersList.remove(currentIndex);
}
// return soldiersList.get(0);
System.out.println(soldiersList.get(0));
} //end main
}//end class
I am writing some simple code to parse a file and return the number of lines but the little red box in eclipse won't go off so I assume I am triggering an infinite loop. Th Text file i am reading has only 10 lines...here's the code: What am I doing wrong?
import java.io.*;
import java.util.Scanner;
public class TestParse {
private int noLines = 0;
public static void main (String[]args) throws IOException {
Scanner defaultFR = new Scanner (new FileReader ("C:\\workspace\\Recommender\\src\\IMDBTop10.txt"));
TestParse demo = new TestParse();
demo.nLines (defaultFR);
int x = demo.getNoLines ();
System.out.println (x);
}
public TestParse() throws IOException
{
noLines = 0;
}
public void nLines (Scanner s) {
try {
while (s.hasNextLine ())
noLines++;
}
finally {
if (s!=null) s.close ();
}
}
public int getNoLines () {
return noLines;
}
}
You're not calling s.nextLine() in the while-loop:
should be:
while(s.hasNextLine()){
s.nextLine(); // <<<
noLines++;
}
You only check hasNextLine within your loop. This checks if another line is present but does not read it. Let it follow by nextLine and your code will work.
while(s.hasNextLine()){
s.nextLine();
noLines++;
}