Question:
Can someone help me with a java program?
al
2012-11-20 14:00:07 UTC
I keep havin the following error.

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at BeerSong.main(BeerSong.java:42)


import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class BeerSong {

public static void writePrintSong(String numberOfBeers) {
System.out.printf("%s bottles of beer on the wall,%n%n", numberOfBeers);
System.out.printf("%s bottles of beer,%n%n", numberOfBeers);
System.out.printf("Take one down, pass it around,%n%n");
}

public static void writePrintSongOneBeer(String numberOfBeers) {
System.out.printf("%s bottle of beer on the wall,%n%n", numberOfBeers);
System.out.printf("%s bottle of beer,%n%n", numberOfBeers);
System.out.printf("Take one down, pass it around,%n%n");
}

public static void writePrintSongZeroBeer(String numberOfBeers) {
System.out.printf("%s bottle of beer on the wall,%n%n", numberOfBeers);
}

public static void main(String[] args) {

String stanza1 = "";
String stanza2 = "";
String stanza3 = "";
String numberOfBeers = "";
int i = 0;

Scanner fileIn = null;
try {
fileIn = new Scanner(new FileInputStream("Beer.txt"));
}
catch(FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}

while(fileIn.hasNextLine()) {
for(i = 99; i >= 0; i--){
numberOfBeers = fileIn.next();
if(!numberOfBeers.equals("One") && !numberOfBeers.equals("Zero")) {
writePrintSong(numberOfBeers);
} else{
if(numberOfBeers.equals("One")) {
writePrintSongOneBeer(numberOfBeers);
} else {
if(numberOfBeers.equals("Zero")){
writePrintSongZeroBeer(numberOfBeers);
}
}
}

}



fileIn.close();

}


}

}
Three answers:
some guy named mike
2012-11-20 14:14:05 UTC
you should check your for loop again.

it runs 100 times. not 99.

so you're calling fileIn.next() 99 times, but on the 100th you get an exception because there is no next.
Kaydell
2012-11-21 00:51:02 UTC
I tried copying and pasting your code from Yahoo! Answers into my IDE, but Yahoo! Answers messess code up.



I see that you already have a couple of answers, so I won't go any further, but in the future, I suggest that when you have code that you want help with that you use PastBin.com to paste your code into and then in Yahoo! Answers, just paste in the URL



http://pastebin.com/
AnalProgrammer
2012-11-20 23:51:25 UTC
Why is your program so long? Also, what is the point of reading the file when your numbers are already in the for loop?

Why have you got three writePrintSong() methods when you can do it in one method that does all the workings out?

The for loop then just calls the one method.

for (int bottleCount = 99; bottleCount > 0; bottleCount--) {

printSong(bottleCount);

} //End for



Have fun.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...