My problem is:
When i scan for user input in this method
public static void listenForCommand() {
#SuppressWarnings("resource")
final Scanner s = new Scanner(System.in);
System.out.print(">");
final String line = s.nextLine();
String[] args = new String[line.split(" ").length-1];
for (int i = 1; i < line.split(" ").length; i++)
args[i-1] = line.split(" ")[i];
commandEntered(line.split(" ")[0], args);
}
then there is "> "
but if something gets printed or logged then it looks like this
https://imgur.com/a/M5TE51b (i cant use Image format because it says: "You need at least 10 reputation to post images." and i dont have 10 repuation.)
So how do i fix this? Are there some apis or libraries for this? I want that it looks like spigot or bukkit.
My Command Listener Class:
When the console gets input, it will split the first word in to the command and everything else are the args. Then it asks for every registered command in the main if there is a command registered with entered commandname.
package at.gebes.utils.command;
import java.util.Scanner;
import at.gebes.bot.Bot;
public final class CommandListener {
public static String[] commandNames = new String[1000];
public static String[] commandDescriptions = new String[1000];
private static CommandExecutor[] CommandClasses = new CommandExecutor[1000];
public static int counter = -1;
public static void registerCommand(final String CommandName, final String CommandDescription, final CommandExecutor CommandClass) {
counter++;
commandNames[counter] = (CommandName);
commandDescriptions[counter] = (CommandDescription);
CommandClasses[counter] = CommandClass;
}
public static void listenForCommand() {
#SuppressWarnings("resource")
final Scanner s = new Scanner(System.in);
System.out.print(">\n");
final String line = s.nextLine();
//final String line = System.console().readLine();
String[] args = new String[line.split(" ").length-1];
for (int i = 1; i < line.split(" ").length; i++)
args[i-1] = line.split(" ")[i];
commandEntered(line.split(" ")[0], args);
}
public static void commandEntered(final String cmd, final String[] args) {
if (counter < 0) {
return;
}
boolean commandExists = false;
try {
for (int i = 0; i <= counter; i++) {
if (commandNames[i].equalsIgnoreCase(cmd)) {
CommandClasses[i].onCommand(commandNames[i], args);
commandExists = true;
break;
}
}
} catch (final NullPointerException e) {
e.printStackTrace();
}
if (!commandExists) {
Bot.getLogger().info("Unknown Command. Try \"help\" for a list of commands.");
}
}
}
In that case you have to take record of current screen in any String type variable and then have to clear screen every time user inputs, then show the recorded screen and then the input line...
I think you got my point.
Related
I have no idea how to properly write line of code adding class field to an ArrayList
public class Main {
public static void main(String[] args) throws IOException
{
zapisz("BazaDanych.txt");
Scanner scanner = new Scanner(System.in);
FilmExtended filmExtended = new FilmExtended();
ArrayList<FilmExtended> bazaFilmow = new ArrayList<>();
int i = 0;
while(scanner.nextInt()!= 0)
{
boolean check = true;
do
{
System.out.println("Podaj tytuł fimu: ");
String temp = scanner.nextLine();
if (temp.matches("[a-zA-Z]{2,}"));
{
bazaFilmow.add(i,filmExtended.setTytul(temp));
check = false;
}
}while (check);
}
}
You don't increment your index i. It's always 0. You have to put i++; in your do while loop
public class Main {
public static void main(String[] args) throws IOException
{
zapisz("BazaDanych.txt");
Scanner scanner = new Scanner(System.in);
List<FilmExtended> bazaFilmow = new ArrayList<>();
//remove index
while(scanner.nextInt() != 0)
{
boolean check = true;
do
{
System.out.println("Podaj tytuł fimu: ");
String temp = scanner.nextLine();
if (temp.matches("[a-zA-Z]{2,}"));
{
FilmExtended filmExtended = new FilmExtended(); //create new instance
filmExtended.setTytul(temp);
bazaFilmow.add(filmExtended); //use add without index or else need to increment your index
check = false;
}
} while (check);
} }
You have to add i++; in the do while loop
Two ways to fix it:
filmExtended.setTytul(temp) should return this.
i++ or remove i
I created a bot and used a snippet of code I invented called "simplify" to dramatically shorten java commands.
Only problem is, the bot program I made with it doesn't work. It's supposed to search the user input for keywords and reply accordingly, but all it really does is accept user input and then turn off. What did I do wrong?
import java.util.*;
public class bot{
//"simplify" and "bot" created by #genisome, All rights reserved.
System.out.println(in);
}
public static void print(String in){
System.out.println(in);
}
public static void print(double in){
System.out.println(in);
}
public static void print(long in){
System.out.println(in);
}
public static void print(boolean in){
System.out.println(in);
}
public static void print(float in){
System.out.println(in);
}
//scan below
public static void scan(int dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextInt();
}
public static void scan(String dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.next();
}
public static void scan(double dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextDouble();
}
public static void scan(float dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextFloat();
}
public static void scan(boolean dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextBoolean();
}
public static void random(int min, int max, int dumpinto){
Random x = new Random();
dumpinto = x.nextInt(max) + min;
}
public static void main (String[] x){
int score;
String[] badcomputerresponse = {"that sucks, sorry", "sorry about that", "bummer", "shit", "aw, damn"};
String[] goodcomputerresponse = {"awesome.", "me too", "great", "cool", "I'm not bad myself"};
String[] goodwords = {"good", "fine", "dandy", "awesome", "cool", "swell", "great", "amazing", "ok", "okay", "well", "happy", "thrilled"};
String[] badwords = {"shitty", "terrible", "sad", "bad", "crappy", "terrible", "sucky", "up shit creek", "pathetic", "miserable", "badly", "terribly", "miserably"};
String input = "";
print("Hey there, how are you doing?");
scan(input);
for (int counter = 0; counter < goodwords.length; counter++){
if (input.contains(goodwords[counter])){
if (input.contains("not")){
sadanswer(badcomputerresponse);
}
else{
happyanswer(goodcomputerresponse);
}
}
}
for (int count2 = 0; count2 < badwords.length; count2++){
if (input.contains(badwords[count2])){
if (input.contains("not")){
happyanswer(goodcomputerresponse);
}
else{
sadanswer(badcomputerresponse);
}
}
}
}
public static void sadanswer(String[] badcomputerresponse){
int randomanswer = 0;
random(0, badcomputerresponse.length, randomanswer);
print(badcomputerresponse[randomanswer]);
}
public static void happyanswer(String[] goodcomputerresponse){
int randomanswer = 0;
random(0, goodcomputerresponse.length, randomanswer);
print(goodcomputerresponse[randomanswer]);
}
}
edit: thank you people who gave me help instead of downvoting me.
To the people who downvoted me, you stink!
First you define a bunch of scan methods like this:
public static void scan(String dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.next();
}
Then you call it like this:
String input = "";
print("Hey there, how are you doing?");
scan(input);
That function does not do what it looks like it does. String dumpinto is an input parameter to the method. You can't write output to it. Once the method is done executing, the value that you typed in is lost. After you call scan(input);, the input variable still contains "". (Print it out or use a debugger to verify.)
Your scan method needs to return a value. Better yet, get rid of those methods altogether and just use one Scanner object to get input from the user.
So I'm writing a basic MasterMind game that is... mostly functional. However, its exhibiting odd behavior and I'm unsure why.
The idea is that what defines a Code and its behavior is one file, the gameplay is another, and the Main just creates a new game and starts playing. When I initialize the game, the computer creates a new random string of 4 (the "secret code"), as expected; but then once I get input for the User guess, it seems to rewrite the secret code into whatever I've input. Further, my methods for evaluating matches don't work at all, but considering that the secret code keeps changing means that it's not being set to begin with, and I'm unsure why.
All three classes below. Why is my class variable in Game not setting properly and accessible to the other methods?
Main.java
class Main {
public static void main(String[] args) {
Game newGame = new Game();
newGame.play();
}
}
Code.java
import java.util.Random;
import java.util.HashMap;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Set;
import java.lang.Math;
import java.lang.StringBuilder;
class Code {
private static HashMap<String,String> PEGS;
private static ArrayList<String> pegStrings;
protected static String secretCodeString;
public static void main(String[] args) {
}
public Code(String input){
this.secretCodeString = input;
}
public Code(){
randomize();
}
//literally just creates the peghash
public static void setPegs(){
PEGS = new HashMap<String,String>();
PEGS.put("C","c");
PEGS.put("Y","y");
PEGS.put("R","r");
PEGS.put("P","p");
PEGS.put("O","o");
PEGS.put("G","g");
}
//turns the pegs ito something randomize can use
public static ArrayList<String> makePegArray(){
setPegs();
pegStrings = new ArrayList<String>();
Collection<String> pegValues = PEGS.values();
Object[] pegObjects = pegValues.toArray();
for (int i = 0; i < pegObjects.length; i++){
pegStrings.add(pegObjects[i].toString());
}
return pegStrings;
}
// sets Class Variable secretCode to a four letter combination
public static Code randomize(){
secretCodeString = new String();
Random rand = new Random();
int randIndex = rand.nextInt(makePegArray().size());
for (int i = 0; i < 4; i++){
randIndex = rand.nextInt(makePegArray().size());
secretCodeString = secretCodeString.concat(makePegArray().get(randIndex));
}
Code secretCode = parse(secretCodeString);
return secretCode;
}
public static Code parse(String input) {
setPegs();
makePegArray();
String[] letters = input.split("");
StringBuilder sb = new StringBuilder();
for (String letter : letters) {
if (pegStrings.contains(letter)) {
sb.append(letter);
} else {
System.out.println(letter);
throw new RuntimeException();
}
}
String pegListString = sb.toString();
Code parsedCode = new Code(pegListString);
//System.out.println(parsedCode);
return parsedCode;
}
public int countExactMatches(Code guess){
String guessString = guess.secretCodeString;
int exactMatches = 0;
String[] guessArray = guessString.split("");
String[] winningCodeArray = (this.secretCodeString).split("");
for(int i = 0; i < 4; i++){
if(guessArray[i] == winningCodeArray[i]){
exactMatches++;
}
}
return exactMatches;
}
public int countNearMatches(Code guess) {
String guessString= guess.secretCodeString;
HashMap<String,Integer> guessCount = new HashMap<String,Integer>();
HashMap<String,Integer> secretCodeCount = new HashMap<String,Integer>();
Set<String> codeKeys = guessCount.keySet();
int matches = 0;
int keys = guessCount.keySet().size();
String[] keyArray = new String[keys];
for(int i = 0; i < guessString.length(); i++) {
//removes character from string
String codeCharacter = String.valueOf(guessString.charAt(i));
String guessShort = guessString.replace(codeCharacter,"");
//counts instances of said character
int count = guessString.length() - guessShort.length();
guessCount.put(codeCharacter, count);
}
for(int i = 0; i < secretCodeString.length(); i++) {
//removes character from string
String winningString = this.secretCodeString;
String winningCodeCharacter = String.valueOf(winningString.charAt(i));
String winningCodeShort = guessString.replace(winningCodeCharacter,"");
//counts instances of said character
int count = winningString.length() - winningCodeShort.length();
secretCodeCount.put(winningCodeCharacter, count);
}
for (int i = 0; i < keys; i++) {
codeKeys.toArray(keyArray);
String keyString = keyArray[i];
if (secretCodeCount.containsKey(keyString)) {
matches += Math.min(secretCodeCount.get(keyString), guessCount.get(keyString));
}
}
int nearMatches = matches - countExactMatches(guess);
return nearMatches;
}
}
Game.java
import java.util.Scanner;
class Game {
protected static Code winningCode;
public static void main(String[] args){
}
public Game(){
winningCode = new Code();
}
protected static Code getGuess() {
Scanner userInput = new Scanner(System.in);
int count = 0;
int maxTries = 5;
while(true){
try {
String codeToParse = userInput.next();
Code guess = Code.parse(codeToParse);
return guess;
} catch(RuntimeException notACode) {
System.out.println("That's not a valid peg. You have " + (maxTries - count) + " tries left.");
if (++count == maxTries) throw notACode;
}
}
}
protected static void displayMatches(Code guess){
int nearMatches = winningCode.countNearMatches(guess);
int exactMatches = winningCode.countExactMatches(guess);
System.out.println("You have " + exactMatches + " exact matches and " + nearMatches + " near matches.");
}
protected static void play(){
int turnCount = 0;
int maxTurns = 10;
System.out.println("Greetings. Pick your code of four from Y,O,G,P,C,R.");
while(true){
Code guess = getGuess();
displayMatches(guess);
if (guess == winningCode) {
System.out.print("You win!!");
break;
} else if (++turnCount == maxTurns) {
System.out.print("You lose!!");
break;
}
}
}
}
On every guess, you call Code.parse, Code.parse creates a new Code (new Code(pegListString);) and that constructor sets the secretCodeString and because that's static, all instances of Code share the same variable. You need to avoid mutable static members.
Another tip is to either have a method return a value, or mutate state (of either its input, or its own instance, this), but avoid doing both.
"Why is my class variable rewriting itself after an unrelated method runs?"
Because, actually, it is not unrelated. The "mess" that you have created by declaring variables and methods as static has lead to unwanted coupling between different parts of your code.
It is difficult to say what the correct solution is here because your code has gotten so confused by the rewrites that it is hard to discern the original "design intent".
My advice would be to start again. You now should have a clearer idea of what functionality is required. What you need to do is to redo the object design so that each class has a clear purpose. (The Main and Game classes make sense, but Code seems to be a mashup of functionality and state that has no coherent purpose.)
I have traced through this code and can't figure out how to fix it. When running the code why wouldn't the user be prompted for input rather than Java determining that there is no input? Error trace below.
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
int array_size = GetArraySize();
//System.out.println(array_size);
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String next_string = GetNextString();
System.out.println(next_string);
}
}
//public static String[] SortInsert(String nextString){
//}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
input.close();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
input.close();
return next_string;
}
Here is the error --
How many items are you entering?: 2
Enter the next string:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at SortAsInserted.GetNextString(SortAsInserted.java:40)
at SortAsInserted.main(SortAsInserted.java:10)
The simple answer is when you close Scanner -- underlying input stream also closes:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()
To fix this create Scanner once in main:
public class SortAsInserted {
static Scanner input;
public static void main(String[] _) {
input = new Scanner(System.in);
....
input.close();
}
Remove input.close(); from the code
Removing the scanner.close() method from two functions will solve your problem.
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
int array_size = GetArraySize();
//System.out.println(array_size);
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String next_string = GetNextString();
System.out.println(next_string);
}
}
//public static String[] SortInsert(String nextString){
//}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
//input.close();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
// input.close();
return next_string;
}
}
I'm working on a method that goes through all of my array messages and displays the selected message. I'm new to Java so I'm still trying to figure out methods and Arrays. When I run this, it says that it's successful but it doesn't display anything. Can someone help me figure this out.
package chatbox;
import java.util.Scanner;
public class ChatBox
{
public static void main(String[] args)
{
String chatMessages[] = new String[10];
//declare arrays
chatMessages[0]= "Pepperoni";
chatMessages[1]= "Olives";
chatMessages[2]= "Cheese";
chatMessages[3]= "Onions";
chatMessages[4]= "Bacon";
chatMessages[5]= "Tomato sauce";
chatMessages[6]= "Bell peppers";
chatMessages[7]= "Mushrooms";
chatMessages[8]= "Sausage";
chatMessages[9]= "Beef";
}
Scanner scan = new Scanner (System.in);
public Scanner chatCannedMessage(String chatMessages)
{
for (int i=0;i<chatMessages.length;i++){
System.out.println(chatMessages[i]); //Prints Message
}
System.out.println("Select a message");
String chatMessage = scan.next();
scan.nextLine();
return scan;
}
}
As PM 77-1 said, you never invoked your shoutOutCannedMessage method and also never print out or return any string.
I tried to minimize changes to your code, and I think this might be what you intended to do.
import java.util.Scanner;
public class ShoutBox {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
String messages[] = new String[10];
//declare 10 arrays
messages[0] = "Pepperoni";
messages[1] = "Olives";
messages[2] = "Cheese";
messages[3] = "Onions";
messages[4] = "Bacon";
messages[5] = "Tomato sauce";
messages[6] = "Bell peppers";
messages[7] = "Mushrooms";
messages[8] = "Sausage";
messages[9] = "Beef";
String m = new ShoutBox().shoutOutCannedMessage(messages);
System.out.println(m);
}
public String shoutOutCannedMessage(String[] messages) {
for (int i = 0; i < messages.length; i++) {
System.out.println(i+". "+messages[i]); //Should print the messages
}
System.out.println("Select a message");
int idx = scan.nextInt();
String message = messages[idx];
return message;
}
}