what is a console in java? - java

I am new to programming and learning Java.
I was looking at an old code and they used something called a console. When I copy-pasted the code, Java did not read anything called a console. Is a console basically a scanner? I searched online and they said it's for input, so should I just remove all consoles and write scanner there instead?
Scanner as in writing Scanner scan = new Scanner(System.in);
I am using the latest version of Java.
(Yes, this for a game of crazy eights)
This is just a part of the old code :
// The "CrazyEights" class.
import java.awt.*;
import hsa.Console;
public class CrazyEights
{
static Console c; // The output console
static int[] deck, player, computer; // card arrays
static int pile, suit; // discard pile, current suit (0-3)
static boolean deckEmpty;
public static void main(final String[] args)
{
// setup console
c = new Console(30, 100, "Crazy Eights");
intro(); // splash page, instructions
char playAgain;
do
{
c.setFont(new Font("Arial", java.awt.Font.PLAIN, 14));
game();
c.setCursor(30, 32);
playAgain = c.getChar();
} while ((playAgain == 'y') || (playAgain == 'Y'));
c.close();
}
}

The specific Console you are asking for is in your imports.
There is an import "import hsa.Console" on the top of your code. If you are not familiar with imports, as you say you are new to programming/Java, it signifies that when you write "Console" inside this file ("CrazyEights.java") you are referencing the "Console" defined in "hsa.Console".
Now, since this class is specific to your project, we can't know what it is and does. You will have to open it and see for yourself.
However, with a quick search, you are probably using "ReadyToProgram" IDE for Java by Holtsoft and Associates and that's what the prefix hsa stands for in "hsa.Console".
If you are not using that and just copy-pasted the code expecting it to work, it won't. That import is not in the standard Java library. You will need to find it, download it and add it to your project dependencies. If you did that just to start somewhere with Java and it is not essential to you, I would suggest leaving this block of code and moving somewhere else.

Related

Update Java multiple-line console output without adding new lines [duplicate]

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);
}
}
}

How can I repeat a method with a variable integer?

I just started learning how to program in Java a month ago. I am trying to make my robot (karel) put a beeper the amount of times that is indicated in the "put" integer only, not the total amount the object has. However, it is not a set number and karel.putBeeper(put); does not get accepted in the compiler due to the class not being applied to given types. Any help would be greatly appreciated, and I am starting to understand why Stack Overflow is a programmer's best friend lol. Note: I might not respond to to any helpful tips until tomorrow.
import java.io.*;
import java.util.*;
public class Lab09 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("Which world?");
String filename = input.nextLine();
World.readWorld(filename);
World.setSize(10,10);
World.setSpeed(6);
Robot karel = new Robot(1,1,World.EAST,0);
int pick=0;
int put=0;
for(int i=0; i<8; i++) {
while(karel.onABeeper()) {
karel.pickBeeper();
pick++;
karel.move();
}
for(i=0; pick>i; pick--) {
put++;
}
if(!karel.onABeeper()) {
karel.move();
}
while(karel.onABeeper() && put>0) {
karel.putBeeper(put);
}
}
}
}
If I got your question right, you're trying to putBeeper put times, which is done by the following code:
while (karel.onABeeper() && put > 0) {
karel.putBeeper(put);
}
The issue I see here is that you're not changing the value of put after calls to putBeeper, hence this while loop will never terminate: for instance, if the value of put was 5 during the first loop iteration, it will always remain 5, which is larger than 0. Also, as you've mentioned, putBeeper doesn't take any arguments, hence trying to pass put as an argument won't work - the compiler catches that error for you.
If your intent is to call putBeeper put times then what you can do is decrement put after every invocation of putBeeper - put will eventually reach 0, at which point you've called putBeeper exactly put times. And since you're just learn to program in Java, I'll leave the actual implementation to you as an exercise. Good luck!

Call upon method from user input

I am currently working on a project and I have been asked to create a puzzle type game based on a 2d array. I have created the methods which all work fine, but I dont quite know how to make it so that the user can call upon the methods via user input whilst the program is running.
I'd prefer not to upload my code as this is quite a big class and I don't want other class members to find this and copy my code.
Thanks :-)
Try a simple menu loop like this:
// scanner created outside the loop because it will be used every iteration
Scanner s = new Scanner(System.in);
while(true) {
System.out.print("Please choose an option: ");
// read some input and trim the trailing/ leading whitespaace
String input = s.nextLine().trim();
// check to see which move was called
if (input.equals("foo")) {
foo();
}
else if (input.equals("bar")) {
bar();
}
// break out of the menu loop
else if (input.equals("exit")) {
break;
}
// if none of the above options were called
// inform user of invalid input
else {
System.out.println("Invalid input");
}
}
// exit program
System.out.println("Goodbye!");
Just add in options as you need them
You can use GUI or console to give your command to your apllication for execution those methods.
offtop
this is quite a big class
I think you should divide one big class to some smaller classes(less them 100 lines).

Printing individual parts of an array in a Java Gui app

OK, so I created a console app that, among other things, takes an array of numbers and prints them out one by one, line by line. Now, I have to take the class that I created for that console app, and pop it into a separate GUI app we're creating. I have all of the other methods working fine, but for the life of me I cannot get the array method to print out correctly. It just gives me the last number I typed into the text field. I'm hoping someone can give me a nudge to help me figure this part out so I can move along, and get to the whole SpringLayout stuff, (the main part of the new assignment) I am limited in what I can show you here because this is a current assignment, so I will have to stick to this stuff as specifically as I can. And please, don't just post the code as an answer, (because then I can't use it), thanks.
Here's what I had for my original project for the array method:
int [] getArray(int x)
{
breakUpNum(x);
return numAry;
}
From there, inside my new class I have this, in an attempt to get it to print:
private class ButtonTest implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
Lab1 tester = new Lab1();
int[] test4 = tester.getArray(num);
for(int i = 0; i < test4.length; i ++)
{
crossTest.getArrCross.setText("" + test4[i]);
}
}
}
Any help pointing me in the right direction would be greatly appreciated, thanks!
setText does just that, sets the text you pass to as the current text content, it does not append it.
If you were to use JTextArea, you could use it's append method...however, for a JTextField you need to have a different approach.
Now you could use getArrCross.setText(getArrCross.getText() + test4[i])...but to quite frank, that's rather inefficient, as each call to setText is going to stage a paint event...
StringBuilder sb = new StringBuilder(128);
for(int i = 0; i < test4.length; i ++)
{
sb.append(test4[i]);
}
crossTest.getArrCross.setText(sb.toString());
Now, if you want to separate each element, you need to add
if (sb.length() > 0) {
sb.append(", ");
}
Before sb.append(test4[i]);
The last bit of actionPerformed in the for loop isn't working right. setText replaces the current text with its argument, and it doesn't seem like you want to do that. To fix it, replace the line in the for loop with this:
crossTest.getArrCross.setText(crossTest.getArrCross.getText() + test4[i]);

how to Save a jpanel containing combo-boxes and text-boxes in java netbeans?

I am creating an application which helps solving problems of an accounting book. The application has 12 chapters. All chapters contains 15-20 problems. The problem is displayed in a JPanel containing various combo-boxes and formatted-text boxes. suppose i solved a problem half and want to save so that next time i can load that half solved question.
Saving should be done by clicking save from menubar. And loading by load from the menubar
All menubars and problem sheet are working but i am not able to save any thing. I was using jFilechooser...
Is their any way to do that?
How to save a panel with filled combo-boxes items and text-boxes. And is their any way to know that user has made any changes in any items so that on closing the problem i can again ask to save it first and then exit.
Thanks in advance.
Some of my codes:
private void openBtnMouseClicked(java.awt.event.MouseEvent evt) {
opening();
}
public void opening() {
JFileChooser chooser=new JFileChooser();
int choice=chooser.showOpenDialog(this);
javax.swing.JComboBox[] sourceALE = {aaCombo, baCombo, caCombo, daCombo, eaCombo, faCombo, gaCombo, haCombo, iaCombo, jaCombo, kaCombo,
alCombo, blCombo, clCombo, dlCombo, elCombo, flCombo, glCombo, hlCombo, ilCombo, jlCombo, klCombo,
aeCombo, beCombo, ceCombo, deCombo, eeCombo, feCombo, geCombo, heCombo, ieCombo, jeCombo, keCombo};
javax.swing.JTextField[] sourceP = {aeval1, beval, ceval, deval, eeval, feval, geval, heval, ieval, jeval, keval};
String [] comboboxes={"aaCombo", "baCombo", "caCombo", "daCombo", "eaCombo", "faCombo", "gaCombo", "haCombo", "iaCombo", "jaCombo", "kaCombo","alCombo", "blCombo", "clCombo", "dlCombo", "elCombo", "flCombo", "glCombo", "hlCombo", "ilCombo", "jlCombo","klCombo","aeCombo", "beCombo", "ceCombo", "deCombo", "eeCombo", "feCombo", "geCombo", "heCombo", "ieCombo", "jeCombo", "keCombo"};
if(choice==JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
System.out.println("Hey");
Scanner scanner = new Scanner(new FileReader(file));
while ( scanner.hasNextLine() ){
Scanner scan = new Scanner(scanner.nextLine());
scan.useDelimiter("=");
if ( scan.hasNext() ){
String item=scan.next();
int value=scan.nextInt();
String color=scan.next();
for(int g=0;g<comboboxes.length;g++){
if(item.equals(comboboxes[g])) {
if(value<3)
sourceALE[g].setSelectedIndex(value);
if(color.equals("red"))
sourceALE[g].setForeground(red);
if(color.equals("green"))
sourceALE[g].setForeground(green);
if(color.equals("blah"))
sourceALE[g].setForeground(blah);
}
}
}
scan.close();
}
scanner.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(q1.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void opening() {
JFileChooser chooser=new JFileChooser();
int choice=chooser.showOpenDialog(this);
javax.swing.JComboBox[] sourceALE = {aaCombo, baCombo, caCombo, daCombo, eaCombo, faCombo, gaCombo, haCombo, iaCombo, jaCombo, kaCombo,
alCombo, blCombo, clCombo, dlCombo, elCombo, flCombo, glCombo, hlCombo, ilCombo, jlCombo, klCombo,
aeCombo, beCombo, ceCombo, deCombo, eeCombo, feCombo, geCombo, heCombo, ieCombo, jeCombo, keCombo};
javax.swing.JTextField[] sourceP = {aeval1, beval, ceval, deval, eeval, feval, geval, heval, ieval, jeval, keval};
String [] comboboxes={"aaCombo", "baCombo", "caCombo", "daCombo", "eaCombo", "faCombo", "gaCombo", "haCombo", "iaCombo", "jaCombo", "kaCombo","alCombo", "blCombo", "clCombo", "dlCombo", "elCombo", "flCombo", "glCombo", "hlCombo", "ilCombo", "jlCombo","klCombo","aeCombo", "beCombo", "ceCombo", "deCombo", "eeCombo", "feCombo", "geCombo", "heCombo", "ieCombo", "jeCombo", "keCombo"};
if(choice==JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
System.out.println("Hey");
Scanner scanner = new Scanner(new FileReader(file));
while ( scanner.hasNextLine() ){
Scanner scan = new Scanner(scanner.nextLine());
scan.useDelimiter("=");
if ( scan.hasNext() ){
String item=scan.next();
int value=scan.nextInt();
String color=scan.next();
for(int g=0;g<comboboxes.length;g++){
if(item.equals(comboboxes[g])) {
if(value<3)
sourceALE[g].setSelectedIndex(value);
if(color.equals("red"))
sourceALE[g].setForeground(red);
if(color.equals("green"))
sourceALE[g].setForeground(green);
if(color.equals("blah"))
sourceALE[g].setForeground(blah);
}
}
}
scan.close();
}
scanner.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(q1.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("OUT");
}
}
1) It is good design to separate your data from the presentation. Are you doing this already? What I mean is you should be looking to store answers in an object outside of the jPanel class. (As 'Hovercraft Full Of Eels' suggested)
2) Consider making the data objects Serializable objects. If you're not planning on storing the data across a network or anything complicated/peculiar this should work out for you as it will facilitate save/load operations
3) Once you have your data separate from the GUI a check for changes becomes very easy. Assume that on any operation that takes you away from the page it "saves" its state. If the current state is different from the saved state then prompt the user to save (if it doesn't by default)
I have to wonder if you've created this program primarily as a NetBeans-generated GUI without first creating the non-GUI guts of the program. So first I have to ask, have you divided out your program logic from your GUI code a la MVC (model-view-controller) or one of its many variants? If not then this should be your first order of business, since in truth the saving and recovery of the data should have nothing to do with its GUI representation.
The key to solving your problem is going to be good object-oriented programming design. Consider for instance creating a non-GUI Question class that has several fields including a String question field, an ArrayList of possibleAnswers and a field String for the correctAnswer. Consider having an ArrayList of these Questions (ArrayList) for each chapter and a collection of the Chapters. Then you will need to figure out the best way for you to save the questions and the users answers. This may be via serialization, XML (JAXB?), or my recommendation: a database.
Only after you've figured out all of this should you worry about how to integrate a GUI around your non-GUI logic code which will be the GUI's "model".
Edit
Replies to your comments:
Sorry i havent provided enough info of my project. I m doing it in NETBEANS 7 GUI.I guess netbeans java programs are MVC
Sorry, no. If all you do is create a GUI with NetBeans you will be creating an unwieldy god-class. To have good MVC you must design it that way from the beginning. Again that means creating your program logic before creating the GUI which in your case includes creating multiple non-GUI classes as I've indicated above. There is no "automatic" MVC in NetBeans.
I may be wrong as i dont know much about MVC.
Yes, unfortunately you're wrong. Please read about it: Model-View-Controller. This will help you with your current and future design.
As of now i am able to save and retrieve. But i want your suggestion on that. It is quite hardcoded for each question.
And that should probably be fixed as you do not be hard-coding the questions. In fact the question text shouldn't even be part of the code but part of the data. Consider having the question in a comma-delimited text file or database.
i tried to answer 5 components and save it in notepad. And on loading it i am able to get all those components filled. Its working. But its quite hard coded and yes of course bad programming. But i have some time limitations so can you suggest anything similar to this logic. if by some function or method i could know all the components variable name present in my JPanel. like all the 15-20 combo-box and same no of text-box. I could make a function which can be common for all
Sorry, I wish I could, but I can't, not unless you first fix your design issues. Good luck!

Categories