Please help me with this HW assignment. I am supposed to modify the EchoNumber class which extends the Echo class to count the number of characters in every line in a text file in addition to displaying the text. Here is the Echo class:
import java.util.Scanner;
import java.io.*;
public class Echo{
String fileName; // external file name
Scanner scan; // Scanner object for reading from external file
public Echo(String f) throws IOException
{
fileName = f;
scan = new Scanner(new FileReader(fileName));
}
// reads lines, hands each to processLine
public void readLines(){
while(scan.hasNext()){
processLine(scan.nextLine());
}
scan.close();
}
// does the real processing work
public void processLine(String line){
System.out.println(line);
}
}
Here is the EchoNumber class, notice where it says "Your code goes here":
import java.io.*;
public class EchoNumber extends Echo
{
// the current line number
private int lineNumber;
public EchoNumber (String datafile) throws IOException
{
super( datafile);
lineNumber=1;
}
// Prints a line with a leading line number and a trailing line length
// Overrides the processLine method in Echo class
public void processLine(String line){
/* your code goes here */
}
}
Here is the EchoTester class:
import java.io.*;
import java.util.Scanner;
public class EchoTester
{
public static void main(String[] args)
{
// uses try/catch to handle IOExceptions in main
try
{
String fileName;
Scanner nameReader = new Scanner(System.in);
System.out.println("Enter a file name");
fileName = nameReader.nextLine();
EchoNumber e = new EchoNumber(fileName);
e.readLines();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
And finally the .txt file:
The best things in life are free
A stitch in time saves nine
Still waters run deep
He teaches ill who teaches all
You can not take it with you when you die
Better untaught than ill taught
Do not cross your bridges before you come to them
Soon learnt soon forgotten
Even a worm will turn
It was the last straw that broke the camels back
The way to a mans heart is through his stomach
If the stone fall upon the egg alas for the egg If the egg fall upon the stone alas for the egg
Where there is a will there is a way
Marry in haste and repent at leisure
One tongue is enough for a woman
If you wish good advice consult an old man
The best advice is found on the pillow
All clouds bring not rain
You can not tell a book by its cover
No news is good news
Bad news travels fast
Live and let live
Birds of a feather flock together
Now is the time
For all good men who actually have the time
To come to the aid of the country in which they live
The output is supposed to be something like:
1 The best things in life are free-32
2 A stitch in time saves nine-27
3 Still waters run deep-21
4 He teaches ill who teaches all-30
5 You can not take it with you when you die-41
6 Better untaught than ill taught-31
7 Do not cross your bridges before you come to them-49
8 Soon learnt soon forgotten-26
9 It was the last straw that broke the camels back-48
Except without spaces between each line. For some reason it fuses into one paragraph if I did not separate each line.
Something like this:
public void processLine(String line){
System.out.println(lineNumber + " " + line + "-" + line.length());
++lineNumber;
}
I haven't tested it, so if it isn't 100% correct, I'll leave it as an exercise for you to complete, but it should put you on the right track. Good luck.
THIS is the correct code. It is important that lineNumber++ is below the print statement!
System.out.println(lineNumber + " " + line + "-" + line.length());
lineNumber++;
Related
First let me clear out i am new to programming and hope that i am using the right terminology.
I using the System.out.print(""); Method to print to the Windows Console:
System.out.print("Backspace b"); //Output: Backspace b
So the cursor is now "behind" the b, if i type in System.out.print("\b"); the curser moves one to the left, deleting the "b". -->
System.out.print("Backspace b"); //Output: Backspace b
System.out.print("\bh"); //Output: Backspace h
Now if i Type in System.out.print("\n\bh"); the output isn't Backspace bh but:
"Backspace b
h"
How can i manage that the cursor goes back one line "up" and to it's far right. Something line a "minus \n" or "not \n", so that it reads Backspace bh?
Is there something like that in Java?
It's impossible without third party libraries. I've done extensive research on this as I've been working on console games for the past week and from what I can tell you can either require JNI, JNA, Jansi, or JLine which will require Jansi or JNA. Personally I recommend JLine as all the others will require you to write C or C++.
If you say want to go up so many lines you could do something like this with JLine.
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.InfoCmp;
import java.io.IOException;
public class CursorStuff
{
static Terminal terminal;
public static void main(String[] args) throws IOException
{
terminal = TerminalBuilder.terminal();
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("This line will get overwritten by the terminal path");
goBackLines(3);
System.out.println("back 3 overwriting 2");
}
public static void goBackLines(int remove)
{
for(int i = 0; i < remove; i++)
{
terminal.puts(InfoCmp.Capability.cursor_up);
}
}
}
I do not get what is wrong, It would be great help if anyone would explain it to me so that I (or you) can fix it.
The error that keeps occurring for many of my programs is:
File: F:\Java Work\Classexample3.java [line: 40]
Error: reached end of file while parsing
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Classexample3 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String answer;
System.out.println("What kind of beverage do you want? (hot or cold)");
answer = br.readline();
if (answer.equals("hot")) {
System.out.println("Please choose an item from the list below:");
System.out.println("- tea \n- coffee");
answer = br.readline();
if (answer.equals("tea")) {
System.out.println("You have purchased a hot tea:");
} else if (answer.equals("coffee")) {
System.out.println("You have purchased a hot coffee");
answer = br.readline();
}
} else if (answer.equals("cold")) {
System.out.println("Please choose an item from the list below:");
System.out.println("- bubble tea \n- pop");
answer = br.readline();
if (answer.equal("bubble tea")) {
System.out.println("You have purchased a cold bubble tea");
} else if (answer.equals("pop")) {
System.out.println("You have purchased a cold pop");
} else {
System.out.println("This item is not on the list");
}
}
}
You are missing a } at the end to close the class.
You're missing a } to close the corresponding public class Classexample3 {. The error is exactly as it states - the Java compiler expects the class declaration to be closed at some point, but the file ended without doing so.
That error means something wasn't closed like a closing bracket is missing. Looks like the closing bracket for your Classexample3 class is missing at the bottom of your code.
Once you close your class with an missing }, you will a lot of other errors.
First, br.readline() should be br.readLine()
Second, answer.equal("bubble tea") should be answer.equals("bubble tea")
These things matter and if you use an IDE, it will make your life as a Java developer a lot easier :)
I started studying Java not too long ago, I am currently trying to make a little game to see if I got the things I saw right.
I want to make a "game" that let's you choose between two dialogue options which have different consequences.
This is the code I used:
package programs;
import java.util.Scanner;
public class Programma1_0 {
public static void main(String[] args) {
System.out.println(
"You wake up in a laboratory. You don't remember ever being there. You actually don't remember anything.");
System.out.println("A door opens, a girl comes towards you.");
System.out.println("Girl:<<Hi, I see you woke up. How are you feeling?>>");
System.out.println("(Write Good or Bad)");
Scanner first = new Scanner(System.in);
String firstch = first.nextLine();
if (firstch.equals("Good")) {
System.out.println("Great, we have a lot to explain.");
} else if (firstch.equals("Bad")) {
System.out.println("You should be alright in an hour or so. You've slept for a long time.");
} else {
System.out.println("(I told you to write Good or Bad)");
}
}
}
So far it's working as intended. The only problem is that if I write something other than Good or Bad i get the message "(I told you to write Good or Bad)" and the program terminates. Is there a way to automatically restart it? If i put more choices in, I want the program to automatically restart from the question where it terminated (So I don't play through half of the game, get a question wrong and have to restart the program from the start), is that possible?
Thanks.
You can accomplish this by putting this before your if statement.
while (true) {
if (firstch.equals("Good") || firstch.equals("Bad"))
break;
else {
System.out.println("(I told you to write Good or Bad)");
firstch = first.nextLine();
}
}
Then you can also remove the last else part of your if statement.
Now it will continue asking for a new input till it gets either "Good" or "Bad"
You can simply put your if-else statement inside the do-while loop, that way you can loop through until you get correct response
int i = 0;
do {
System.out.println("(Write Good or Bad)");
firstch = first.nextLine();
if (firstch.equals("Good")) {
System.out.println("Great, we have a lot to explain.");
i = 0;
} else if (firstch.equals("Bad")) {
System.out.println("You should be alright in an hour or so. You've slept for a long time.");
i = 0
} else {
System.out.println("(I told you to write Good or Bad)");
i = 1;
}
} while (i == 1);
You can partition your program into separate methods. Here I created a method called retrieveAnswer() which its only task to create a Scanner and get input. This method will return a String as seen in the public static String header.
Another method I created was entitled getResult() which takes a String argument and will now compare the String passed from
String firstch = retrieveAnswer();
getResult(firstch);
If the result goes to the else block, it will call retrieveAnswer() and pass the value returned to getResult() as seen in getResult(retrieveAnswer()) which will then restart the whole process.
There are multiple solutions to this, but I just took the recursion route instead. Good luck with Java! If you are confused, look more into methods as they are VERY essential in programming.
import java.util.Scanner;
public class Source {
public static void main(String[] args) {
System.out.println(
"You wake up in a laboratory. You don't remember ever being there. You actually don't remember anything.");
System.out.println("A door opens, a girl comes towards you.");
System.out.println("Girl:<<Hi, I see you woke up. How are you feeling?>>");
System.out.println("(Write Good or Bad)");
String firstch = retrieveAnswer();
getResult(firstch);
}
public static String retrieveAnswer(){
Scanner first = new Scanner(System.in);
String firstch = first.nextLine();
return firstch;
}
public static void getResult(String firstch){
if (firstch.equals("Good")) {
System.out.println("Great, we have a lot to explain.");
} else if (firstch.equals("Bad")) {
System.out.println("You should be alright in an hour or so. You've slept for a long time.");
} else {
System.out.println("(I told you to write Good or Bad)");
getResult(retrieveAnswer());
}
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Alright, allow me to elaborate on my dilemma.
I'm making a Console Game with Java. It's not going to be super simple, but I don't want it to be really advanced either. I'm just trying to test my skills using the basics that I've learned. I've started a few times, but constantly ran into the same "problem".
It's not exactly a problem though, just something I could do better. The best way to explain it is to just show some example code.
Here is my Main class. We'll call it "Main.java".
package com.mattkx4.cgamedev.main;
public class Main {
public static void main(String[] args) {
}
}
Ok, now let's make a new method in our Main.java. We'll call this method "Start". Our Main class now looks like so:
package com.mattkx4.cgamedev.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
}
public static void start() {
System.out.println("This is the start.");
Scanner s = new Scanner(System.in);
System.out.println("Enter \"NEXT\" to continue.");
String in = s.nextLine();
if(in.equalsIgnoreCase("NEXT")) {
}else{
System.out.println("Please input \"NEXT\".");
start();
}
}
}
Now we'll add two more methods. We'll call them "middle" and "end". Our finished class now looks like so:
package com.mattkx4.cgamedev.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
start();
}
public static void start() {
System.out.println("This is the start.");
Scanner s = new Scanner(System.in);
System.out.println("Enter \"NEXT\" to continue.");
String in = s.nextLine();
if(in.equalsIgnoreCase("NEXT")) {
middle();
s.close();
System.exit(0);
}else{
System.out.println("Please input \"NEXT\".");
start();
}
}
public static void middle() {
System.out.println("This is the middle.");
System.out.println("Let's move on to the end.");
end();
}
public static void end() {
System.out.println("This is the end.\nFinishing up, and heading back to the start() method to close program.");
}
}
What I've written here is in my opinion a very inefficient program. Inefficient to code with that is. There's has to be another way to doing this program, rather than calling methods inside of other methods to move along the program.
A summary of my question: Is the above code the most efficient way to write a console game?
Thanks in advance! If you have any questions I'll be happy to answer them.
-Matthew
There are many kinds of answers to your question. I'll just enumerate some basic things.
Your design is linear and completely rigid. Unflexible. Most applications like this, rather than chaining any methods or the like, store a state somehow. This is often achieved with an enum. It's important to understand how state-based programming works. So you might have something like:
public enum GameState {
LOAD, START, STOP, BEGIN, MIDDLE, END, GAME_OVER // ... and so on
}
You're using a bunch of static methods. This is certainly not what you want to do. It completely abandons any object-orientation. If you're making a game world, you will, ideally, have a class for every distinct object in your world, and they will be arranged in a logical hierarchy, by extends-ing each other or implements-ing different interfaces.
You will need to learn concurrency. Your user input will almost necessarily come asynchronously to the rendering of your game, if it has any sophistication at all. At the very, very least, you'll probably at least need Swing to create a GUI.
So, just with those three very basic notes, you will need to study up on object-orientation, polymorphism, concurrency, and all the various data structures available to you. Your example, to be frank, has the sophistication of a Java 101 project. (I'm not saying that to be mean.) If you plan to make a real game, you'll need a lot more of the basics under your belt before you can make real headway.
It's good that you're thinking big, and it's good that your goals for programming are big. But break that big dream up into manageable chunks. It will get your farther, faster, and it will also prevent you from getting discouraged.
Best of luck to you!
As a side note, if you start coding up some simple games (even something as simple as a console-based Hangman or Tic-Tac-Toe), please come around to the Code Review Beta. We'll be more than happy to give you a detailed review of your code and help you along the path to becoming a veteran programmer! It's a good community with a lot of very constructive criticism. I've both helped people there (with Java) and received a good amount of help as I learned Python.
Well, I don't quite get what this has to do with performance or optimization. But normally you use classes and methods to structure your program.
That being said, there is a huge mistake in your start method. You should axoid the unnecessary recursion and use a loop instead, and remove the exit call:
public static void start() {
System.out.println("This is the start.");
Scanner s = new Scanner(System.in);
System.out.println("Enter \"NEXT\" to continue.");
String in = s.nextLine();
if(in.equalsIgnoreCase("NEXT")) {
middle();
s.close();
System.exit(0);
}else{
System.out.println("Please input \"NEXT\".");
start(); // <-- recursion!
}
}
Better do it like this:
public static void start() {
System.out.println("This is the start.");
Scanner s = new Scanner(System.in);
System.out.println("Enter \"NEXT\" to continue.");
while ( !s.nextLine().equals("NEXT")) {
System.out.println("Please input \"NEXT\".");
}
middle();
// you probably also want to put "end();" here - it is not called in the original code
s.close();
}
I guess what you are trying to build up is an main skeleton of the application. I suggest to search for "Game Loop". There a lots of good articles down there about that.
For a general solution, the algorithm is, at big scales, more or less like this:
while (notExit()) {
event = getNextEvent(); // this can be the user keyboard input or mouse
renderGame(); // display the graphics on the screen
doGameLogic(event); // do the game logic according to the events occurred
}
Later, you must take into account how many times per seconds you draw on the screen (FPS) and how many times you compute changes (Physic Frames per second).
Any analogy to the GUI programming is just pure coincidence. I was joking, it is not coincidence, is a fact that GUI and Game Programming shared a thread that fulfill the role of event dispatch thread.
For more information i suggest to read this tutorials : http://sol.gfxile.net/gp/index.html.
Hope it helps!
It really depends on the type of application/game how you want to structure it.
In this case, you may find it useful to have some kind of control method which runs the functions in the correct order and has your "flow" logic.
In a more complicated game this method would deal with user input that directs them to different rooms/levels/etc. And you may even have smaller control methods that deal with sub parts.
For instance,
You could have a playGame method that calls registerPlayer(), which would process getting the player's name and any other information. When that method returns then playGame would call a levelOne() method and so on and so forth.
Just try to break it up into logical units for your game!
solution from top of my head,
create class
class Location{
public Location( String locationId, String desctiption, List<String> exit){
//populate fields
}
private final String locationId;
private final String desctiption;
private final List<String> exits;
//getters ommited
}
then you could have 3 locations;
start = new Location("START","This is the start.",Arrays.asList("middle"));
middle= new Location("middle","This is the middle.\nLet's move on to the end.",Arrays.asList("end"));
end= new Location("end","This is the end.",null);
now your launcher class
public class Game {
Map locations = new HashMap();
public Game() {
locations.put("START", new Location("START", "This is the start.",
Arrays.asList("middle")));
locations.put("middle",
new Location("middle",
"This is the middle.\nLet's move on to the end.",
Arrays.asList("end")));
locations.put("end", new Location("end", "This is the end.", null));
}
public static void main(String[] args) {
Game game = new Game();
game.start();
}
private void start() {
visitLocation(locations.get("START"));
}
public void visitLocation(Location location) {
System.out.println(location.getDescription());
if (location.getExits().isEmpty()) {
return;
}
Scanner s = new Scanner(System.in);
String in = "";
do {
System.out.println("Choose exit from location : ");
for (String exit : location.getExits())
System.out.print(exit + " ");
in = s.nextLine();
} while (!location.getExits().contains(in));
s.close();
visitLocation(locations.get(in));
}
}
this is still not best but i think it will give you some ideas,
I'm doing a simple program regarding methods.
But I have one problem. Everything is already working except when looping.
When I choose to loop again. The program skips on inputting the name. And proceeds directly to the year and section.
Here's the code:
public static void main(String[] args) {
do{
System.out.println("Input info:");
name=stringGetter("Name: ");
yearandsec=stringGetter("Year and section: ");
sex_code=charGetter("Sex code: " + "\n" + "[M]" + "\n" + "[F]:");
scode=intGetter("Scholarship code: ");
ccode=intGetter("Course code: ");
units=intGetter("Units: ");
fee_per_unit=doubleGetter("Fee per unit: ");
misc=doubleGetter("Miscellaneous: ");
display();
switches(scode, units, fee_per_unit, misc);
System.out.println("Another?");
dec=rew.nextInt();
}while(dec==1);
}
Here's the method getting the value for name together with the year and section:
public static String stringGetter(String ny){
String sget;
System.out.println(ny);
sget=rew.nextLine();
return sget;
}
I'm really annoyed with this problem, and I don't have any idea on how to fix this. Please help. thanks
Here is a simpler and more complete program that reproduces the error:
public static Scanner rew = new Scanner(System.in);
public static void main(String[] args) {
int dec;
do {
System.out.println("Input info:");
String name=stringGetter("Name: ");
String yearandsec=stringGetter("Year and section: ");
dec=rew.nextInt();
} while(dec==1);
}
public static String stringGetter(String ny){
System.out.println(ny);
return rew.nextLine();
}
The problem is that after calling nextInt() the call to nextLine() reads up to the new line after the int (giving a blank line), not up to the next new line.
If you change dec to a String and change dec=rew.nextInt(); to dec=rew.nextLine(); then it will work fine. Here is a complete example that you can copy and paste into a blank file to see that it works correctly:
import java.util.*;
public class Program
{
public static Scanner rew = new Scanner(System.in);
public static void main(String[] args) {
String dec;
do {
System.out.println("Input info:");
String name = stringGetter("Name: ");
String yearandsec = stringGetter("Year and section: ");
dec = stringGetter("Enter 1 to continue: ");
} while(dec.equals("1"));
}
public static String stringGetter(String ny){
System.out.println(ny);
return rew.nextLine();
}
}
You may also want to consider adding proper parsing and validation to your program. Currently your program will behave in an undesirable way if the user enters invalid data.
The line:
dec = rew.nextInt();
Is reading an int value from the input stream and is not processing the newline character, then when you come back to point where you get the name at which point a new line is still in the Reader's buffer and gets consumed by the stringGetter returning an empty value for name.
Change the line to do something like:
do {
//....
s = stringGetter("Another (y/n)? ");
} while ("y".equals(s));
Well you haven't told us what "rew" is, nor what rew.nextInt() does. Is it possible that rew.nextInt() is waiting for the user to hit return, but only actually consuming one character of the input - so that the next call to rew.nextLine() (for the name) just immediately takes the rest of that line? I suspect that's what's happening because you're using System.in - usually reading from System.in only gives any input when you hit return.
(It's possible that this is also only a problem on Windows - I wonder whether it consumes the "\r" from System.in as the delimiter, leaving "\n" still in the buffer. Not sure.)
To test this, try typing in "1 Jon" when you're being asked whether or not to continue - I think it will then use "Jon" as the next name.
Essentially, I think using Scanner.nextInt() is going to have issues when the next call is to Scanner.nextString(). You might be better off using a BufferedReader and calling readLine() repeatedly, then parsing the data yourself.