I am trying to create a chatbot program but my issue is that, when I run the program, it exits right after the sentence is typed.
import java.util.*;
public class Mina{
public static void main(String[]args){
ai();
}
public static void ai(){
greeting();
conversation();
}
public static void greeting(){
System.out.println("Hello. I am Mina.");
}
public static void conversation(){
Scanner console = new Scanner(System.in);
String chat = console.nextLine();
if(!chat.equalsIgnoreCase("\bBye\b") || !chat.equalsIgnoreCase("\bBye.\b")){
keywords(chat);
}
}
public static void keywords(String word){
if(word.equalsIgnoreCase("\bHello\b") || word.equalsIgnoreCase("\bHello.\b")){
System.out.println("What do you want to talk about?");
keywords(word);
}else if(word.equalsIgnoreCase("\bMr. Smith\b") || word.equalsIgnoreCase("\bMr. Smith.\b")){
System.out.println("I bet he is a nice teacher.");
keywords(word);
}else if(word.equalsIgnoreCase("\bBye\b") || word.equalsIgnoreCase("\bBye.\b")){
System.exit(0);
}
return;
This is what I get:
Mina's Run
I previously had my code loop by placing keyword(); at the end of the method.
}else if(word.equalsIgnoreCase("\bBye\b") || word.equalsIgnoreCase("\bBye.\b")){
System.exit(0);
}
keyword(word);
return;
If anyone has any ideas on what I can possibly do to fix this problem, please help.
I have modified your code to make it work in a fashion where it will ask the user to input a new line until they say "Bye". This is achieved by using the while loop as shown:
import java.util.*;
public class Mina{
public static void main(String[]args){
ai();
}
public static void ai(){
greeting();
conversation();
}
public static void greeting(){
System.out.println("Hello. I am Mina.");
}
public static void conversation(){
Scanner console = new Scanner(System.in);
String chat = console.nextLine();
while(!(chat.equalsIgnoreCase("Bye") || chat.equalsIgnoreCase("Bye."))){
keywords(chat);
chat = console.nextLine();
}
System.exit(0);
}
public static void keywords(String word){
if(word.equalsIgnoreCase("Hello") || word.equalsIgnoreCase("Hello.")){
System.out.println("What do you want to talk about?");
}else if(word.equalsIgnoreCase("Mr. Smith") || word.equalsIgnoreCase("Mr. Smith.")){
System.out.println("I bet he is a nice teacher.");
}
}
}
Related
I'm trying to write a do loop that will continue to ask for a person’s name until the name "Bob" is entered. If the name is not Bob, the response should be “You’re not Bob”. If the name is Bob, the response should be “Hi Bob” (then the loop ends).
public class loopExtra3 {
public static void main(String[] args) {
String name;
name=Bob;
do {
System.out.println ("What is your name?");
if (name.equals("Bob") == false) {
System.out.println("You're not Bob");
}
if (name.equals("Bob") == true) {
System.out.println("Hi Bob");
}
} while (name.equals("Bob") == false);
}
}
Your code isn't even compiling, since it has to be name="Bob"; - if you fix this, your code works like a charme. But the main problem is that you aren't even asking for a input, so the code will run endlessly with a name which is not Bob.
With reading the input, everything works:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name;
do {
System.out.println("What is your name?");
name = sc.nextLine();
if (!name.equals("Bob")) {
System.out.println("You're not Bob");
}
else {
System.out.println("Hi Bob");
}
} while (!name.equals("Bob"));
}
}
So I want to create a menu where a user can choose to play two different games. I want to create a main method and be able to make a for loop or switch statements for the different game options or for the user to quit but I am not sure how I would call the classes so that the game runs when they choose it.
Can someone explain to me how I would go about this. Thanks!
import java.util.Scanner;
import java.util.Random;
public class RpsGame {
/* Valid user input: rock, paper, scissors */
public static void main(String[] args) {
System.out.print("Please Make Your Choice (Rock, Paper or Scissors): ");
try {
Scanner sc =
new Scanner(System.in);
String userInput =
sc.next();
if (isValid( userInput )) {
game( userInput );
} else {
print("Invalid user input!\nWrite rock, paper or scissors!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void print(String text) {
System.out.println( text );
}
public static boolean isValid(String input) {
if (input.equalsIgnoreCase("rock")) {
return true;
}
if (input.equalsIgnoreCase("paper")) {
return true;
}
if (input.equalsIgnoreCase("scissors")) {
return true;
}
return false;
}
public static void game(String user) {
String computer = computerResults();
//System.out.print("Please Make Your Choice: ");
print( user + " vs " + computer + "\n");
if (user.equalsIgnoreCase(computer)) {
print("Oh, Snap! Tied - No winners.");
} else {
if (checkWin(user, computer)) {
print("You won against the computer!");
} else {
print("You lost against the computer!");
}
}
}
public static String computerResults() {
String types[] =
{"rock", "paper", "scissors"};
Random rand = new Random();
int computerChoice = rand.nextInt(3);;
return types[computerChoice];
}
public static boolean checkWin(String user, String opponent) {
if ( (!isValid( user )) && (!isValid( opponent )) ) {
return false;
}
String rock = "rock", paper = "paper", scissors = "scissors";
if ( (user.equalsIgnoreCase( rock )) && (opponent.equalsIgnoreCase( scissors )) ) {
return true;
}
if ( (user.equalsIgnoreCase( scissors)) && (opponent.equalsIgnoreCase( paper )) ) {
return true;
}
if ( (user.equalsIgnoreCase( paper )) && (opponent.equalsIgnoreCase( rock )) ) {
return true;
}
return false;
//If no possible win, assume loss.
}
}
The easiest method that I am familiar with is using something called a Driver Class. A Driver Class is a class that is designed to run code from other classes - perfect for running two different games. Check this post if you need more info: What is a driver class? (Java)
Try something like this:
public class MyGameApp {
public static final String OPTION_1 = "1";
public static final String OPTION_2 = "2";
public static final String OPTION_EXIT = "3";
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
String userChoice = null;
do {
System.out.println("Choose an option: \n 1. Game 1\n2. Game 2\n3. Exit");
userChoice = sc.nextLine();
switch(userChoice) {
case OPTION_1:
/*
Calls a static method of a class, so there is no need of instantiate the class first.
*/
GameOne.start();
break;
case OPTION_2:
/*
In this case, create a new instance of the class GameTwo, and then call the method start().
*/
GameTwo game = new GameTwo();
game.start();
break;
default:
System.out.println("Wrong option, try again.");
}
while(!OPTION_EXIT.equals(userChoice));
}
}
class GameOne {
public static void start() { ... }
}
class GameTwo {
public void start() { ... }
}
I get a bunch of errors when the code within the "clearPets" method is not commented out. As long as I delete that code, the program will run otherwise.
How can the problems be fixed? I've only recently learned about creating and calling methods, and this is my first time using java.util.Arrays.
The errors in the console are:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Boolean
at java.util.Arrays.fill(Unknown Source)
at rf.uhh.clearPets(uhh.java:34)
at rf.uhh.optionOne(uhh.java:39)
at rf.uhh.main(uhh.java:20)
Here is the code I have:
public class uhh {
public static void main(String[] args){
System.out.println("Select a number");
System.out.println("1");
System.out.println("2");
System.out.print("Choice: ");
Scanner scnr = new Scanner(System.in);
String numberChoice = scnr.nextLine();
if( "1".equals(numberChoice) ) {
System.out.println("You chose 1");
optionOne(new boolean[][] { {false}, {true} });
}
scnr.close();
}
public static boolean[][] adoptPets( int cats, int dogs) {
boolean[][] pets = new boolean[cats][dogs];
return pets ;
}
public static void clearPets( boolean[][]pets) {
Arrays.fill(pets, false);
}
public static void optionOne(boolean[][] center) {
clearPets(center);
boolean[][] dogFaceMan = adoptPets(10, 10);
dogFaceMan[1][1] = true;
}
}
You are passing a 2D array into a method (Arrays.fill) that expects a 1D array.
Try this:
public static void clearPets( boolean[][]pets) {
for(int i = 0; i < pets.length; i++) {
Arrays.fill(pets[i], false);
}
}
I'm trying to complete this java program, but every time I try to compile it I get this error. Can someone figure out why my program is doing this. It seems that no matter what I do I still happen to get an error on my program. I tried everything I know to see if it would work. Please someone help me.
import java.util.Scanner;
public class Period
{
private static String phrase;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
// this is where the error is occuring at.
public Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
The 'Sorter' method is missing a return type. It should be:
public void Sorter(String newPhrase)
{
phrase = newPhrase.substring(0, newPhrase.indexOf("."));
}
The method is not called anywhere, so i am not sure if this is what you intended it to do.
add the void return type:
public void Sorter(String newPhrase) // HERE
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
There are a lot of errors in the above code - see below for some code that runs, though i can't be sure it does exactly what you want given the limited scope of the question.
I don't want to stray too far from the original question, but you should really consider using instance variables and encapsulating your data, rather than relying on static variables.
import java.util.Scanner;
public class Period
{
private static String phrase;
private static int[] alphabet = new int [27];
public static void main(String [] args)
{
System.out.println("Enter a sentence with a period at the end.");
Scanner keyboard = new Scanner(System.in);
phrase = keyboard.nextLine().toLowerCase();
Period period = new Period();
period.entryPoint();
}
public void Sorter(String newPhrase)
{
phrase = newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am writing a TicTacToe program and for some reason it is skipping the scanner.nextLine() for player 1, but is stopping for player 2. Entire code is as follows: Method in question is called "Names"
package tictactoe;
import static java.lang.System.*;
import java.io.*;
import java.util.Scanner;
public class TicTacToe {
static String p1name;
static String p2name;
static String p1marker;
static String p2marker;
public static Scanner qwe = new Scanner(in);
public static void title(){
out.println("\tTicTacToe by Ryan Hosford");
out.print("\n\n\n");
out.println("1)Start"+"\t\t" + "2)How to play\t\t" + "3)Quit ");
int title = qwe.nextInt();
if(title == 1)
Names();
else if(title ==2)
Info();
else if(title ==3)
Quit();
else
title();
}
public static void Names(){
out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
out.println("Player 1, What is your name?");
Setp1Name(qwe.nextLine());
out.println("Nice to meet you " + Getp1Name());
out.println("");
out.println("Player 2, what is your name?");
Setp2Name(qwe.next());
out.println("Nice to meet you " + Getp2Name());
qwe.next();
Markers();
}
public static void Markers(){
out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
out.println(Getp1Name()+", Would you like to X's or O's?");
Setp1Marker(qwe.next());
if(Getp1Marker().equals("X") || Getp1Marker().equals("x")){
Setp2Marker("O");
}
else if(Getp1Marker().equals("O") || Getp1Marker().equals("o")){
Setp2Marker("X");
}
else{
Markers();
}
out.println(Getp1Name() + " is playing with: " +Getp1Marker());
out.println(Getp2Name() + " is playing with: " + Getp2Marker());
out.println("");
out.println("Press enter to continue...");
qwe.nextLine();
Game();
}
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
title();
}
public static void Setp1Name(String player1name){
p1name = player1name;
}
public static String Getp1Name(){
return p1name;
}
public static void Setp2Name(String player2name){
p2name = player2name;
}
public static String Getp2Name(){
return p2name;
}
////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void Setp1Marker(String p1Mark){
p1Mark.toUpperCase();
p1marker = p1Mark;
}
public static String Getp1Marker(){
return p1marker;
}
public static void Setp2Marker(String p2Mark){
p2Mark.toUpperCase();
p2marker = p2Mark;
}
public static String Getp2Marker(){
return p2marker;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void Info(){
out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
out.println("TicTacToe is a game where you have to try and get 3 of your markers in a row; Be that diagonally, vertically, or horizontally.");
out.println("The two markers in TicTacToe are X and O");
out.println("The two players take turns placing one of their markers, and the game is over once a player gets 3 in a row.");
out.println("");
out.println("Press enter to continue...");
qwe.next();
title();
}
public static void Quit(){
out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
out.println("Quitting game...");
exit(0);
}
}
Maybe try to change:
public static void Setp1Name(String player1name){
p1name = player1name;
}
to:
public static void Setp1Name(){
p1name = qwe.nextLine();
}
and same for the other setName method.