It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I tried submitting this and an error pops up saying ** END OF FILE detected on input -- EXIT **.
I cant figure out what this means, just to be clear I am trying to set up a system so that data is input on a loop unless the value is 0. Thanks.
This is my code:
class Main
{
public static void main( String args[] )
{
int SN = 1;
while ( SN != 0)
{
System.out.print("#SN : " );
SN = BIO.getInt();
System.out.print("#CW : " );
int CW = BIO.getInt();
System.out.print("#EX : " );
int EX = BIO.getInt();
double Mark = CW + EX;
System.out.printf("SN= " + SN + "EX= " + EX + "CW= " + CW + "Mark= " + "%6.1f", (double) Mark / 2 );
}
}
}
This is the BIO code:
class BIO
{
private static final int EOF = -1;
private static final int NONE = -2;
private static int nextChar = NONE;
private static boolean EOFdetected = false;
public static String getLineBASE()
{
String line = ""; // Line read
int ch; // Read ch
try
{
ch = System.in.read(); // No next char
if ( ch == EOF )
{
System.out.println("**** END OF FILE " +
"detected on input -- EXIT ****" );
System.exit(-1);
}
while( ch != '\n' ) // Read loop
{
if ( ch == EOF )
{
EOFdetected = true;
return line; // exit
}
line = line + (char) ch; // form line
ch = System.in.read(); // next ch
}
return line; // return line
}
catch( IOException exp ) // Problem
{
System.exit(-1); // Exit **
}
return ""; // Blank line
}
public static String getLine()
{
String line = getLineBASE(); // Read line
//System.out.println( line );
return line;
}
public static String getString()
{
String line = getLine(); // Read line
return line.trim();
}
public static double getDouble()
{
String res = getLine(); // Read line
double value = 0.0; //
try
{
value = Double.parseDouble( res.trim() ); // Convert
}
catch ( NumberFormatException ex ) // Problem
{ // ignore
}
return value; // return
}
public static int getInt()
{
String res = getLine(); // Read line
int value = 0; //
try
{
value = Integer.parseInt( res.trim() ); // Convert
}
catch ( NumberFormatException ex ) // Problem
{ // ignore
}
return value; // return
}
}
try
{
ch = System.in.read(); //reads from keyboard.
if ( ch == EOF )
{
System.out.println("**** END OF FILE " +
"detected on input -- EXIT ****" );
System.exit(-1);
}
}
This snippet reads in input from the keyboard. If you want to read stuff from a file (Which I assume you are, since there is an EOF) look up the Scanner class. If this is not what you wanted, my apologies, I am only making assumptions.
Related
Basically what i am trying to do is read a file that contains some questions. The file is organized like this:
//The category of the question
Questions
//The question
Possible Answer
//Answer #1
//Answer#2
//Answer#3
//Answer#4
Right answer
//The right answer
Image
//The image path if it exists
This is for only one question. There are multiple questions like this.
private boolean readQuestion() {
try {
String line = this.reader.readLine();
if (line == null) {
return false;
}
String category = "";
String question = "";
String[] possibleAnswers = {
"",
"",
"",
""
};
String rightAnswer = "";
String image = "";
boolean imageQuestion = false;
if (line.compareTo("Category") == 0) {} else {
//read the category
category = this.reader.readLine();
}
if (line.compareTo("Question") == 0) {
//read the question (String question = ....)
question = this.reader.readLine();
}
line = this.reader.readLine();
if (line.compareTo("Possible answers") == 0) {
//read four lines with the possible answers(String [] possibleAnswers = ...)
for (int i = 0; i < 4; i++) {
possibleAnswers[i] = this.reader.readLine();
}
}
line = this.reader.readLine();
if (line.compareTo("Right answer") == 0) {
//read the right answer(String rightAnswer = ...)
rightAnswer = this.reader.readLine();
}
line = this.reader.readLine();
if (line.compareTo("Image") == 0) {
//read the image name
image = this.reader.readLine();
imageQuestion = true;
}
BaseQuestion question1 = new BaseQuestion(question, possibleAnswers, rightAnswer, category);
if (imageQuestion) {
ImageQuestion imageQuestion_1 = new ImageQuestion(question1, image);
this.questions.add(imageQuestion_1);
} else {
this.questions.add(question1);
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private void readFile() {
while (this.readQuestion());
}
i have made the readQuestion boolean so that it returns if there is another question following. The reader is also a BufferedReader object. The BaseQuestion is a class that has a category, a question, 4 possible answers and a right answer. The imageQuestion has all the attributes of the BaseQuestion but also an imagePath.
It's because you have a NullPointerException (during 3rd iteration of you loop) on your if stmt. because line = null
line = this.reader.readLine();
if (line.compareTo("Image") == 0)
java.lang.NullPointerException: Cannot invoke "String.compareTo(String)" because "line" is null
public static void main(String[] args) throws IOException {
Demo d = new Demo();
d.readFile();
System.out.println(d.questions.size());
for (Question q : d.questions) {
System.out.println(q.toString());
where Question is just a dummy interface
interface Question {}
class BaseQuestion implements Question { ... }
this is the output I'm able to get from your class:
2
BaseQuestion{question='', rightAnswer='', category='', possibleAnswers=[null, null, null, null]}
BaseQuestion{question='', rightAnswer='', category='//Answer #1', possibleAnswers=[null, null, null, null]}
to see output presented above add these methods to your BaseQuestion and ImageQuestion classes:
#Override
public String toString() {
return "ImageQuestion{" +
"image='" + image + '\'' +
", question1=" + question1 +
'}';
}
and
#Override
public String toString() {
return "BaseQuestion{" +
"question='" + question + '\'' +
", rightAnswer='" + rightAnswer + '\'' +
", category='" + category + '\'' +
", possibleAnswers=" + Arrays.toString(possibleAnswers) +
'}';
}
You are reading here same line twice:
if (line.compareTo("Category") == 0) {} else {
//read the category
category = this.reader.readLine();
}
if (line.compareTo("Question") == 0) {
//read the question (String question = ....)
question = this.reader.readLine();
}
there's a missing readLine() between Category and Questions that's why the current line doesn't match your desired input
if (line.compareTo("Category") == 0) {} else {
//read the category
category = this.reader.readLine();
}
line = this.reader.readLine();
if (line.compareTo("Question") == 0) {
//read the question (String question = ....)
question = this.reader.readLine();
}
... and what's the purpose of this piece of code? are you sure it works as expected?
if (line.compareTo("Category") == 0) {} else {
//read the category
category = this.reader.readLine();
}
I try to remove a space into a string which contains a int type value.
I read a .csv file with the scanner methode.
I use a Class to set/get the data.
I format data into the setter of the class.
Input data example:
String Pu_ht = "1 635,90";
Basic Example:
/**
* #param Pu_ht the Pu_ht to set
*/
public void setPu_ht(String Pu_ht) {
this.Pu_ht = Pu_ht.replace(",", ".").replace(".00", "");
}
Tried example:
/**
* #param Pu_ht the Pu_ht to set
*/
public void setPu_ht(String Pu_ht) {
this.Pu_ht = Pu_ht.replace(",", ".").replace(".00", "").replaceAll("\\s+", "");
}
Other example:
/**
* #param Pu_ht the Pu_ht to set
*/
public void setPu_ht(String Pu_ht) {
this.Pu_ht = Pu_ht.replace(",", ".").replace(".00", "").replaceAll(" ", "");
}
Output data example: 1 635.90
I tried a lots of things but nothing work for my case.
Best regards
EDIT:
My code:
public void requete_pommes() throws IOException, ClassNotFoundException, SQLException {
// open file input stream
BufferedReader reader = new BufferedReader(new FileReader(filename));
// read file line by line
String line = null;
Scanner scanner = null;
int index = 0;
List<Pommes> pomList = new ArrayList<>();
boolean firstLine = false;
while ((line = reader.readLine()) != null) {
if (!(line.equals(";;;;TOTAL HT"))) {
if (!(line.equals(";;;;"))) {
Pommes pom = new Pommes();
scanner = new Scanner(line);
scanner.useDelimiter(";");
while (scanner.hasNext()) {
String data = scanner.next();
pom.setNumero_compte("21826");
if ((index == 0)) {
pom.setReference(data);
} else if ((index == 1)) {
pom.setDesignation(data);
} else if ((index == 2)) {
pom.setQte(data);
} else if ((index == 3)) {
if(data.equals("1 635,90")){
data = data.replaceAll("\\s","");
System.err.println("data: " + data);
}
pom.setPu_ht(data);
} else if ((index == 4)) {
pom.setMontant_HT(data);
} else {
System.out.println("invalid data::" + data);
}
pom.setNumero_commande("1554");
index++;
}
index = 0;
pomList.add(pom);
requeteCorps = "(( SELECT codea FROM article WHERE tarif7 != 'O' AND tarif8 = 'O' AND pvente > 0 AND COALESCE(trim( reffou), '') != '' AND reffou = '" + pom.getReference() + "' ), " + pom.getQte() + " , " + pom.getPu_ht() + ", '" + kapiece + "', 'stomag','vendu', getnum('LCK')),";
ar.add(requeteCorps);
}
}
}
The value "1 635,90" probably stems from a locale specific format, and the "space" actually is a non-breaking space, \u00A0. This is done often to prevent in flexible width text representation a line break to happen inside a number.
s = s.replace("\u00A0", "");
String Pu_ht = "1 635,90";
System.out.println(Pu_ht.replace(",", ".").replace(".00", "").replaceAll("\\s+", ""));
just put the above codes in main method and execute. the output will be 1635.90,then examine your codes.
I am practicing to write a program that gets a text file from user and provides data such as characters, words, and lines in the text.
I have searched and looked over the same topic but cannot find a way to make my code run.
public class Document{
private Scanner sc;
// Sets users input to a file name
public Document(String documentName) throws FileNotFoundException {
File inputFile = new File(documentName);
try {
sc = new Scanner(inputFile);
} catch (IOException exception) {
System.out.println("File does not exists");
}
}
public int getChar() {
int Char= 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
Char += line.length() + 1;
}
return Char;
}
// Gets the number of words in a text
public int getWords() {
int Words = 0;
while (sc.hasNext()) {
String line = sc.next();
Words += new StringTokenizer(line, " ,").countTokens();
}
return Words;
}
public int getLines() {
int Lines= 0;
while (sc.hasNextLine()) {
Lines++;
}
return Lines;
}
}
Main method:
public class Main {
public static void main(String[] args) throws FileNotFoundException {
DocStats doc = new DocStats("someText.txt");
// outputs 1451, should be 1450
System.out.println("Number of characters: "
+ doc.getChar());
// outputs 0, should be 257
System.out.println("Number of words: " + doc.getWords());
// outputs 0, should be 49
System.out.println("Number of lines: " + doc.getLines());
}
}
I know exactly why I get 1451 instead of 1451. The reason is because I do not have '\n' at the end of the last sentence but my method adds
numChars += line.length() + 1;
However, I cannot find a solution to why I get 0 for words and lines.
*My texts includes elements as: ? , - '
After all, could anyone help me to make this work?
**So far, I the problem that concerns me is how I can get a number of characters, if the last sentence does not have '\n' element. Is there a chance I could fix that with an if statement?
-Thank you!
After doc.getChar() you have reached the end of file. So there's nothing more to read in this file!
You should reset your scanner in your getChar/Words/Lines methods, such as:
public int getChar() {
sc = new Scanner(inputFile);
...
// solving your problem with the last '\n'
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (sc.hasNextLine())
Char += line.length() + 1;
else
Char += line.length();
}
return char;
}
Please note that a line ending is not always \n! It might also be \r\n (especially under windows)!
public int getWords() {
sc = new Scanner(inputFile);
...
public int getLines() {
sc = new Scanner(inputFile);
...
I would use one sweep to calculate all 3, with different counters. just a loop over each char, check if its a new word etc, increase counts , use Charater.isWhiteSpace *
import java.io.*;
/**Cound lines, characters and words Assumes all non white space are words so even () is a word*/
public class ChrCounts{
String data;
int chrCnt;
int lineCnt;
int wordCnt;
public static void main(String args[]){
ChrCounts c = new ChrCounts();
try{
InputStream data = null;
if(args == null || args.length < 1){
data = new ByteArrayInputStream("quick brown foxes\n\r new toy\'s a fun game.\nblah blah.la la ga-ma".getBytes("utf-8"));
}else{
data = new BufferedInputStream( new FileInputStream(args[0]));
}
c.process(data);
c.print();
}catch(Exception e){
System.out.println("ee " + e);
e.printStackTrace();
}
}
public void print(){
System.out.println("line cnt " + lineCnt + "\nword cnt " + wordCnt + "\n chrs " + chrCnt);
}
public void process(InputStream data) throws Exception{
int chrCnt = 0;
int lineCnt = 0;
int wordCnt = 0;
boolean inWord = false;
boolean inNewline = false;
//char prev = ' ';
while(data.available() > 0){
int j = data.read();
if(j < 0)break;
chrCnt++;
final char c = (char)j;
//prev = c;
if(c == '\n' || c == '\r'){
chrCnt--;//some editors do not count line seperators as new lines
inWord = false;
if(!inNewline){
inNewline = true;
lineCnt++;
}else{
//chrCnt--;//some editors dont count adjaccent line seps as characters
}
}else{
inNewline = false;
if(Character.isWhitespace(c)){
inWord = false;
}else{
if(!inWord){
inWord = true;
wordCnt++;
}
}
}
}
//we had some data and last char was not in new line, count last line
if(chrCnt > 0 && !inNewline){
lineCnt++;
}
this.chrCnt = chrCnt;
this.lineCnt = lineCnt;
this.wordCnt = wordCnt;
}
}
this may be a simple fix and a silly question but I am still new to learning java. I am currently working on a code for class that bases on a text game. The code below is what was given to us out of our text book to work on the game. I changed the actual text in the text file mainly and did not do much to the code but I am receiving the following error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at BradySkuza58.getRoom(BradySkuza58.java:143)
at BradySkuza58.loadRoomsFromFile(BradySkuza58.java:90)
at BradySkuza58.main(BradySkuza58.java:39)
This is the code I used for the text game.
import java.util.Scanner;
class Room
{
int roomNumber;
String roomName;
String description;
int numExits;
String[] exits = new String[20];
int[] destinations = new int[20];
}
public class BradySkuza58
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
// initialize rooms from file
Room[] rooms = loadRoomsFromFile("textadventurerooms.txt");
//showAllRooms(rooms); // for debugging
// Okay, so let's play the game!
int currentRoom = 0;
String ans;
while ( currentRoom >= 0 )
{
Room cur = rooms[currentRoom];
System.out.print( cur.description );
System.out.print("> ");
ans = keyboard.nextLine();
// See if what they typed matches any of our exit names
boolean found = false;
for ( int i=0; i<cur.numExits; i++ )
{
if ( cur.exits[i].equals(ans) )
{
found = true;
// if so, change our next room to that exit's room number
currentRoom = cur.destinations[i];
}
}
if ( ! found )
System.out.println("Sorry, I don't understand.");
}
}
public static Room[] loadRoomsFromFile( String filename )
{
Scanner file = null;
try
{
file = new Scanner(new java.io.File(filename));
}
catch ( java.io.IOException e )
{
System.err.println("Sorry, I can't read from the file '" +filename + "'.");
System.exit(1);
}
int numRooms = file.nextInt();
Room[] rooms = new Room[numRooms];
// initialize rooms from file
int roomNum = 0;
while ( file.hasNext() )
{
Room r = getRoom(file);
if ( r.roomNumber != roomNum )
{
System.err.println("Reading room # " + r.roomNumber + ", but" + roomNum + " was expected.");
System.exit(2);
}
rooms[roomNum] = r;
roomNum++;
}
file.close();
return rooms;
}
public static void showAllRooms( Room[] rooms )
{
for ( Room r : rooms )
{
String exitString = "";
for ( int i=0; i<r.numExits; i++ )
exitString += "\t" + r.exits[i] + " (" + r.destinations[i] +")";
System.out.println( r.roomNumber + ") " + r.roomName + "\n" +exitString );
}
}
public static Room getRoom( Scanner f )
{
// any rooms left in the file?
if ( ! f.hasNextInt() )
return null;
Room r = new Room();
String line;
// read in the room # for errorchecking later
r.roomNumber = f.nextInt();
f.nextLine(); // skip "\n" after room #
r.roomName = f.nextLine();
// read in the room's description r.description = "";
while ( true )
{
line = f.nextLine();
if ( line.equals("%%") )
break;
r.description += line + "\n";
}
// finally, we'll read in the exits
int i = 0;
while ( true )
{
line = f.nextLine();
if ( line.equals("%%") )
break;
String[] parts = line.split(":");
r.exits[i] = parts[0];
r.destinations[i] = Integer.parseInt(parts[1]);
i++;
}
r.numExits = i;
// should be done; return the Room
return r;
}
}
line 39
Room[] rooms = loadRoomsFromFile("textadventurerooms.txt");
line 90
Room r = getRoom(file);
line 143
line = f.nextLine();
I did not attach the text file itself but I can if it is needed to find the error.
I'm guessing that your text file does not have as many lines are your program expects (you are trying to call nextLine() after already reaching EOF. Double check that your text file matches what you want. Not having the text file it is tough to give more detail. Based on where it is make sure that you are breaking out of that while loop. You can also check to see if there is another line by calling hasNextLine().
Add a line "%%" to your room definition file. Your parser requires that.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I start study programming, I made a simple code in java,
is a contest, every participant make bites to an apples, so the participant that bites are more weight wins!
but!! I need add in all code with java methods, functions... you know
please run the code for you understand more
any help? really thanks!
import java.io.*;
class reality_show_methods{
public static void main(String[] args)throws java.io.IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintStream out = System.out;
// VARIABLES
int counterParticipants = 1, numPart, numBoc;
double weightBoc, weightBocTotalMayor = 0;
String namePart, nameParticipantWinner = "";
// SETUP
out.print("Number of Participants ......................... ");
numPart = Integer.parseInt(in.readLine());
out.print("Number of Participants Bites: ....... ");
numBoc = Integer.parseInt(in.readLine());
// START
while (counterParticipants <= numPart) {
out.print("\nParticipant Name #" + counterParticipants + " ...................... ");
namePart = in.readLine();
int countBoc = 1;
double weightBocTotal = 0;
while (countBoc <= numBoc) {
out.print("Bite weight #" + countBoc + " of the Participant " + namePart + ": ");
weightBoc = Double.parseDouble(in.readLine());
weightBocTotal = weightBocTotal + weightBoc;
countBoc++;
}
if (weightBocTotalMayor < weightBocTotal) {
weightBocTotalMayor = weightBocTotal;
nameParticipantWinner = namePart;
}
counterParticipants++;
}
// SHOW WINNER
out.println("\nParticipant Winner: ................... " + nameParticipantWinner + " with Total Weight: " + weightBocTotalMayor);
}
}
Do you mean:
public static void myFunction()
{
// blah blah
}
I guess this would help you.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class BiteContest {
private class Participant{
private String name;
private double biteWeight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBiteWeight() {
return biteWeight;
}
public void setBiteWeight(double biteWeight) {
this.biteWeight = biteWeight;
}
}
ArrayList<Participant> participants = new ArrayList<Participant>();
int numBoc;
BufferedReader in;
PrintStream out;
BiteContest(){
in = new BufferedReader(new InputStreamReader(System.in));
out = System.out;
}
void addParticepents() throws IOException
{
boolean noMoreParticipants = false;
while( !noMoreParticipants )
{
out.print("Participant Name : ");
String name = in.readLine();
Participant participant = new Participant();
participant.setName(name);
participant.setBiteWeight(0);
participants.add( participant );
out.print("Want to add more participants [Y/N]: ");
String input = in.readLine();
//Get first character.
input = input.substring(0,1);
noMoreParticipants = "y".equalsIgnoreCase(input)?false:true;
}
}
void takeBiteCount() throws NumberFormatException, IOException {
out.print("\nNumber of Participants Bites : ");
numBoc = Integer.parseInt(in.readLine());
}
void contest() throws NumberFormatException, IOException
{
out.print( "\n\n------CONTEST STARTS------" );
for( Participant participant : participants )
{
out.print( "\n\n------------" );
out.print( "\nTaking Bites for " + participant.getName() + "\n" );
for( int i = 0; i < numBoc; i++ )
{
out.print("Bite weight #" + (i+1) + " of the Participant " + participant.getName() + " : ");
double weightBoc = Double.parseDouble(in.readLine());
participant.setBiteWeight( participant.getBiteWeight() + weightBoc );
}
}
}
String getTheWinner(){
Collections.sort( participants, new Comparator<Participant>() {
public int compare(Participant o1, Participant o2) {
return (int)(o2.getBiteWeight() - o1.getBiteWeight());
}
} );
// Client at the top will be the winner.
return participants.get(0).getName();
}
public static void main(String[] args) {
BiteContest contest = new BiteContest();
try {
contest.addParticepents();
contest.takeBiteCount();
contest.contest();
String winner = contest.getTheWinner();
System.out.println( "\n\n-------------------------\n" +
"The winner is : " + winner );
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}