Display Selected Message String - java

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

Related

InputMismatch error trying to take integer as user input

I am trying to take an integer as user input and store it in a list until the user hits 'q'. At the moment the user inputs 'q', the loop gets terminated.
The code is showing an InputMismatch error:
import java.util.*;
public class SampleArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
int n;
List<Integer> array = new ArrayList();
while (true) {
n = sc.nextInt();
s = sc.nextLine();
if (s.equals("q")) {
break;
} else {
array.add(n);
}
}
Collections.sort(array);
System.out.println(array);
}
}
Just try this,
Inside your while loop to get input for a string use,
s = sc.next();
Instead of sc.nextLine();.
Are you trying to implement it like the example below?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
List<Integer> array = new ArrayList();
while (true) {
s = sc.nextLine();
if (s.equalsIgnoreCase("q")) {
break;
}
int num = Integer.parseInt(s);
array.add(num);
}
Collections.sort(array);
System.out.println(array);
}
}
Looks like q is trying to be stored as an int, so this should work:
All numbers stored as a String can be parsed as an int with the parseInt() method.
s = sc.nextLine();
if (!s.equals("q"))
{
array.add(Integer.parseInt(s));
}
else
{
break;
}

Java screen how to make the input line always be below

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.

My bot program accepts user input and then instead of replying, does nothing

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.

Returning and displaying contents of ArrayList in different class?

I'm working on a project where I will tally a Student's choices and add them to a count array (still working on this part). For now, I'm trying to retrieve the choices that have been sent and added to a Student ArrayList in my Student class.
Student class:
public class Students {
private String name;
private ArrayList<Integer> choices = new ArrayList<Integer>();
public Students(){
name = " ";
}
public Students(String Name){
name = Name;
}
public void setName(String Name){
name = Name;
}
public String getName(){
return name;
}
public void addChoices(int Choices){
choices.add(Choices);
}
public ArrayList<Integer> getChoices(){
return choices;
}
Here is my main driver class:
public class P1Driver {
public static void main(String[] args) throws IOException{
ArrayList<Students> students = new ArrayList<Students>();
String[] choices = new String[100];
int[] count;
Scanner scan1 = new Scanner(new File("Choices.txt"));
Scanner scan2 = new Scanner(new File("EitherOr.csv"));
// Scan the first file.
int choicesIndex = 0;
while(scan1.hasNextLine()){
String line = scan1.nextLine();
choices[choicesIndex] = line;
choicesIndex++;
}
scan1.close();
// Scan the second file.
int studentIndex = 0;
while(scan2.hasNextLine()){
String line = scan2.nextLine();
String [] splits = line.split(",");
students.add(new Students(splits[0]));
for(int i = 1; i < splits.length; i++){
students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
}
studentIndex++;
}
scan2.close();
// Instantiate and add to the count array.
int countIndex = 0;
for(int i = 0; i < students.size(); i++){
if(students.get(i).getChoices(i) == -1){
}
}
The last part is where I am now. It's nowhere near done obviously (I'm right in the middle of it) but during my construction of a for loop to get the choices from the students, I'm getting an error that says, "The method getChoices() in the type Students is not applicable for the arguments (int)." Can someone explain what this means, where me error is, and possibly how to fix it? Thanks all.
getChoices(int i) is not a method you've defined.
if(students.get(i).getChoices(i) == -1){
}
getChoices() returns a list, so you can just use the get method on the list:
if(students.get(i).getChoices().get(i) == -1){
}
Alternatively, make a getChoice method:
public Integer getChoice(int i){
return choices.get(i);
}
Have you tried getChoices()[i] instead of getChoices(i)

Why is this code getting a Java NoSuchElement exception?

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

Categories

Resources