I'm getting an error at the 2nd class c.getResponse
The method getResponse(String) is undefined for the type BotTest
If anyone wants to see what the assignment was heres the pdf:
http://www.cs.stonybrook.edu/~tashbook/fall2013/cse110/project-1.pdf
import java.util.*;
public class ChatBot {
public String getResponse(String input) {
int i = 0;
int found = input.indexOf("you", i);
if (found == -1)
return "I'm not important. Let's talk about you instead.";
int x = longestWord(input).length();
if (x <= 3) {
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
if (x == 4) {
return "Tell me more about" + " " + longestWord(input);
}
if (x == 5) {
return "Why do you think" + " " + longestWord(input) + " "
+ "is important?";
} else if (x > 5) {
return "Now we are getting somewhere. How does" + " "
+ longestWord(input) + " " + "affect you the most";
}
else
return "I don't understand";
}
private String longestWord(String input) {
String word, longestWord = "";
Scanner turtles = new Scanner(input);
while (turtles.hasNext()) {
word = turtles.next();
if (word.length() > longestWord.length())
longestWord = word;
}
return longestWord;
}
}
Second Class to test the code
import java.util.*;
public class BotTest {
public static void main(String[] args) {
Scanner newturtles = new Scanner(System.in);
System.out.println("What would you like to talk about?");
String input = newturtles.nextLine();
BotTest c = new BotTest();
while (!input.toUpperCase().equals("GOODBYE")) {
System.out.println(c.getResponse(input));
input = newturtles.nextLine();
}
}
}
getResponse is defined for ChatBot not BotTest
ChatBot c = new ChatBot();
The Class BotTest indeed does NOT have the .getResponse(String) function. ChatBot does though.
Related
I wanna make a condition if somebody input a word the program will return "That is a string" if it is an integer the program will return "That is an integer ". What's wrong with my if condition ?
package folder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
while (skaner.hasNext()){
if (skaner.next() != int) {
System.out.println("That is a string" + skaner.next());
}
else {
System.out.println("That is an integer " + skaner.next());
}
}
skaner.close();
}
}
Here skaner.next() will return a String object whereas int is a primitive data type and therefore both are not comparable. To check if token returned by skaner.next() is an int or not, you can use Integer.parseInt(skaner.next()) which converts String to int and throws a NumberFormatException if input is not a valid integer.
package folder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
while (skaner.hasNext()){
String x = skaner.next();
try {
int y = Integer.parseInt(x);
System.out.println("That is an integer " + y);
}
catch(NumberFormatException e) {
System.out.println("That is a string " + x);
}
}
skaner.close();
}
}
Check this link for reference.
I have looked and cant find the information I am looking for. My code is functioning as I expect it to but I have one bit of code that I would like to improve.
The problem is that I can not call a void method within a print statement like this:
System.out.print("Water is a " + printTemp(temperature) + " at" + temperature + " degrees.";
printTemp(temperature is a void method so this won't work, as a result I found a work-around but it is not ideal:
System.out.print("\nWater is a ");
printTemp(temperature);
System.out.print(" at");
System.out.printf(" %.0f", temperature);
System.out.print(" degrees.\n");
here is the full code:
import java.util.Scanner;
public class printTemp {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the temperature: ");
Double temperature = input.nextDouble();
// takes the state of the water from the printTemp method and
// the temperature to return a formatted output to the user
System.out.print("\nWater is a ");
printTemp(temperature);
System.out.print(" at");
System.out.printf(" %.0f", temperature);
System.out.print(" degrees.\n");
}
public static void printTemp(double temperature) {
String returnMessage = "null" ;
if (temperature < 32 )
returnMessage = "solid";
else if (temperature > 212)
returnMessage = "gas";
else
returnMessage = "liquid";
System.out.printf(returnMessage);
}
}
This is for school thus there are conditions that must remain, printTemp MUST be a void method and the variable temp must remain a DOUBLE.
What about to put the following code snippet
...
System.out.print("Water is a " + returnMessage + " at" + temperature + " degrees.");
to the printTemp method as the last line? Then in the main outputs nothing and you just write:
...
printTemp(input.nextDouble());
Use a class variable to hold the Temperature String word and use the void method to set it.
public class PrintTemp {
private static String TempStr = "";
public static void main(String[]args) {
[...]
printTemp(temperature);
System.out.print("Water is a " + TempStr + " at" + temperature + " degrees.");
}
public static void printTemp(double temperature) {
if (temperature < 32 )
TempStr = "solid";
else if (temperature > 212)
TempStr = "gas";
else
TempStr = "liquid";
}
}
Sorry for the delay guys!
Here is the solution.
import java.util.Scanner;
public class printTemp {
public static void main(String[]args) {
//Read in the temperature from the user
Scanner input = new Scanner(System.in);
System.out.print("\nPlease enter the temperature: ");
//Call and insert the input into the printTemp method.
printTemp(input.nextDouble());
}
public static void printTemp(double temperature) {
//Decide whether the water is in a soild, liquid or gaseous sate.
String returnMessage = "null";
if (temperature < 32 )
returnMessage = "solid";
else if (temperature > 212)
returnMessage = "gas";
else
returnMessage = "liquid";
//Print to the user.
System.out.print("\nWater is a " + returnMessage);
System.out.printf(" at %.0f degrees.%n\n", temperature);
}
}
UPDATE
public class PrintTemp {
public static void main(String[] args) {
double temperature = 35;
StringBuilder returnMessage = new StringBuilder();
printTemp(temperature, returnMessage);
System.out.print("Water is a " + returnMessage + " at " + temperature + " degrees.");
}
public static void printTemp(double temperature, StringBuilder returnMessage) {
if (temperature < 32)
returnMessage.append("solid");
else if (temperature > 212)
returnMessage.append("gas");
else
returnMessage.append("liquid");
}
}
This is the easiest way to have printTemp modify the message without actually returning it and without using additional classes / beans.
But this does work only for objects (not primitive type) and amongst objects it does not work for Strings because in Java they are treated as a special case. (That is why I had to use a StringBuilder, StringBuffer would work too)
I'm doing a library system which once I input a book name, and found inside the array, the out put would be "the book was returned" . But every time I input the name of one the books listed in the array, it still say that "the book is out of order". How can I solve this problem?
import java.util.Scanner;
public class NewClass {
public static void main (String args[]){
Scanner book = new Scanner(System.in);
String [] library = new String [4];
library [0] = "Brazil";
library [1] = "Japan";
library [2] = "China";
library [3] = "India";
String bookEntry = " ";
int day;
int x = 2;
int penalty;
for (int i = 0; i < library.length; i++){
System.out.println("Insert name of the book: ");
bookEntry= book.next();
if (bookEntry == library[i]){
System.out.println("The book was returned");
}else if (bookEntry != library[i]){
System.out.println("The book is out of order");
System.out.println("\n" + bookEntry.toUpperCase()+ " " + "is out since: ");
day = book.nextInt();
if (day > x){
penalty = day*20;
System.out.println("Total fine: " + penalty);
}else{
System.out.println("Not yet due.");
}
}
}
}
}
In Java, you don't compare 2 strings by ==.
Instead you use, .equals() method of class String.
== -> is a reference comparison, i.e. both objects point to the same memory location
.equals() -> evaluates to the comparison of values in
the objects
More on this here
Corrected code below :
import java.util.Scanner;
public class NewClass {
public static void main(String args[]) {
Scanner book = new Scanner(System.in);
String[] library = new String[4];
library[0] = "Brazil";
library[1] = "Japan";
library[2] = "China";
library[3] = "India";
String bookEntry = " ";
int day;
int x = 2;
int penalty;
System.out.println("Insert name of the book: ");
bookEntry = book.next();
boolean present = false;
for (int i = 0; i < library.length; i++) {
if (bookEntry.equals(library[i])) {
present = true;
break;
}
}
if (present) {
System.out.println("The book was returned");
} else {
System.out.println("The book is out of order");
System.out.println("\n" + bookEntry.toUpperCase() + " " + "is out since: ");
day = book.nextInt();
if (day > x) {
penalty = day * 20;
System.out.println("Total fine: " + penalty);
} else {
System.out.println("Not yet due.");
}
}
}
}
Working code here
UPDATE : I have changed the code.
I am relatively new to Java. And I am a Student in the second semester.
The following has been my last task, and I have already presented it. Everything was fine, and the task that was neccessary for me to accomplish has been completely fulfilled.
The task over the semester was making a little game (My choice was guess a number game), and the tasks were simply build upon eachother. (e.g. use at least 5 functions, at least 3 classes, show all four examples of OOP and make a Computer Player)
So having that said I do not mean for people to solve these task because as you will see they have been completed.
Just one additional thing gives me trouble.
I use a Linked list to store the guessed numbers and recall them when needed.
So finally my question is:
How would I go about switching the Linked list with an Array?
Here the code:
Here the Run Class:
package fourfive;
public class Run {
/*
The Game Initializing class!
>>>> "game.getNumPlayers()" //can be uncommented if you want to play
if left commented, you can watch the bots fight to the death.
------------------------------------------------------
game.setBotPlayers //Same as getNumPlayers - defines how many (Bot) players you want to add
------------------------------------------------------
game.setTopNum() // defines the maximum range of numbers
which you want to guess. Starting from 0!
-----------------------------------------------------
*/
public static void main(String[] args){
Game game = new Game(0);
//game.getNumPlayers();
game.setBotPlayers(100);
game.setTopNum(2000);
game.start();
}
}
Game Class:
package fourfive;
import java.util.Random;
import java.util.Scanner;
public class Game {
/*
Some Variables being defined here.
*/
private static Scanner input = new Scanner(System.in);
private int MAX_Tries;
private int TOP_Num;
private int numPlayers;
private int numBots;
private boolean gameWinner = false;
private Random rand = new Random();
private int num;
private Participants[] players; //inheritance 1
private Participants currentPlayer; //polymorphism 1
public Game(int numPlayers) {
this(numPlayers, 10);
}
public Game(int numPlayers, int maxTries) {
this(numPlayers, maxTries, 1000);
}
public Game(int numPlayers, int maxTries, int topNum) {
MAX_Tries = maxTries;
TOP_Num = topNum;
this.numPlayers = numPlayers;
resetPlayers();
resetTheNumber();
}
/*
Inheritance Example 1
The following is a piece of inheritance. Whereas an array of Players whenever of the type
"Participants". Which is then resolved into the type "Human" and that is being inherited from
"Participants". And whenever Bots or Human players are joined, they will be joined within
the same array
*/
public void resetPlayers() {
players = new Human[numPlayers + numBots];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Human(i + 1);
}
for (int i = numPlayers; i < (numBots + numPlayers); i++) {
players[i] = new Computer(i + 1, TOP_Num);
}
}
public void setNumPlayers(int numPlayers) {
this.numPlayers = numBots;
resetPlayers();
}
public void setBotPlayers(int numBots) {
this.numBots = numBots;
resetPlayers();
}
public int getMaxTries() {
return MAX_Tries;
}
public void setMaxTries(int maxTries) {
this.MAX_Tries = maxTries;
}
public int getTopNum() {
return TOP_Num;
}
public void setTopNum(int topNum) {
this.TOP_Num = topNum;
resetTheNumber();
resetPlayers();
}
private void resetTheNumber() {
num = rand.nextInt(TOP_Num);
}
public void start() {
resetPlayers();
System.out.println("Welcome to the Guess a Number Game!\n");
System.out.println("Guess a number between 0 and " + (TOP_Num - 1) + "!");
currentPlayer = players[0];
System.out.println("The num " + num);
/*
Polymorphism example.
Any object that can pore than one IS-A test is considered to be Polymorphic.
In this case we are setting up a condition in which any given player has
the ability to win, which is depicted from the "isCorrect()" Method.
*/
while (!gameWinner && currentPlayer.getNumTries() < MAX_Tries) {
for (int i = 0; i < players.length; i++) {
//currentPlayer = players[i];
players[i].guess();
if (isCorrect()) {
gameWinner = true;
printWinner();
break;
} else
printWrong();
}
if (!gameWinner) {
printTriesLeft();
}
}
if (!gameWinner)
printLoser();
}
public boolean isCorrect() {
return currentPlayer.getLastGuess() == num;
}
public void printWinner() {
if (currentPlayer instanceof Computer)
System.out.println("Sorry! The Bot " + currentPlayer.getPlayerNum() + " got the better of you, and guessed the number: [" + num + "] and won! Perhaps try again!");
else
System.out.println("GG Player " + currentPlayer.getPlayerNum() + "you guessed the Number [" + num + "] right in just " + currentPlayer.getNumTries() + " tries!");
}
public void printLoser() {
System.out.println("Too Sad! You didn't guess within " + MAX_Tries + " tries! Try again!");
}
public void printWrong() {
String word = "too high";
if ((Integer.compare(currentPlayer.getLastGuess(), num)) == -1)
word = "too low";
System.out.println("Nope! " + word + "!");
}
public void printTriesLeft() {
System.out.println(MAX_Tries - currentPlayer.getLastGuess() + " tries left!");
}
public void getNumPlayers() {
System.out.print("Enter number of Persons playing => ");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter the number of Players => ");
}
numPlayers = input.nextInt();
System.out.print("Enter number of Bots! =>");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter number of Bots! =>");
}
numBots = input.nextInt();
resetPlayers();
}
}
Participants class:
package fourfive;
import java.util.LinkedList;
public abstract class Participants extends Run {
protected int numTries;
protected int playerNum;
protected LinkedList<Integer> guesses;
abstract void guess();
public int getLastGuess(){
return guesses.peek();
}
public int getPlayerNum(){
return playerNum;
}
public int getNumTries(){
return guesses.size();
}
}
Now the Human class: (basically the human player)
package fourfive;
import java.util.LinkedList;
import java.util.Scanner;
public class Human extends Participants {
protected static Scanner input = new Scanner(System.in);
public Human(int playerNum) {
numTries = 0;
this.playerNum = playerNum;
guesses = new LinkedList<Integer>();
}
public void guess(){
System.out.print("Player " + playerNum + "guess =>");
while(!input.hasNextInt()){
input.nextLine();
System.out.println("Invalid input!");
System.out.print("Player " + playerNum + "guess =>");
}
guesses.push(input.nextInt());
}
}
And Last the Computer class:
package fourfive;
import java.util.Random;
public class Computer extends Human {
protected static Random rand = new Random();
protected int maxGuess;
Computer(int playerNum) {
super(playerNum);
maxGuess = 1000;
}
Computer(int playerNum, int topNum){
super(playerNum);
maxGuess = topNum;
}
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
guesses.push(guess);
}
public int getMaxGuess() {
return maxGuess;
}
public void setMaxGuess(int num) {
maxGuess = num;
}
}
You would initialize the Array with a fixed size, e.g. 4 and resize if needed. For this, you need an extra attribute to store the fill level of the array.
int[] guesses = new int[4];
int guessFilling = 0;
[...]
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
if (guessFilling == guesses.length) {
resizeGuesses();
}
guesses[guessFilling++] = guess;
}
private void resizeGuesses() {
int[] newGuesses = new int[guesses.length > 0 ? 2 * guesses.length : 1];
System.arraycopy(guesses, 0, newGuesses, 0, guesses.length);
guesses = newGuesses;
}
I have an assignment where the user is asked for baby name using a scanner. Then it reads through files names.txt and meanings.txt and returns the popularity of the name for each decade ranging from 1890 - 2010 then it prints out the meaning. Some names have multiple meanings and some are used in both genders. The assignment states to print only the first line where the name is found. I am having trouble only returning the first line in which the name is found. PLEASE HELP ME!
import java.io.*;
import java.util.*;
public class BabyNames4 {
public static void main(String[] args) throws FileNotFoundException {
printIntro();
Scanner console = new Scanner(System.in);
System.out.print("Name: ");
String searchWord = console.next();
Scanner fileScan = new Scanner(new File("names.txt"));
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan);
}
}
Scanner fileScan2 = new Scanner(new File("meanings.txt"));
String dataLine2 = find(searchWord, fileScan2);
if (dataLine2.length() > 0) {
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
}
}
public static void printIntro() {
System.out.println("This program allows you to search through the");
System.out.println("dada from the Social Security Administration");
System.out.println("to see how popular a particular name has been");
System.out.println("since 1890");
System.out.println();
}
public static String find(String searchWord, Scanner fileScan) {
while (fileScan.hasNextLine()) {
String dataLine = fileScan.nextLine();
String dataLineLC = dataLine.toLowerCase();
if (dataLineLC.contains(searchWord.toLowerCase())) {
return dataLine;
//} else { runs a continuous loop
//System.out.println(search" not found.");
}
}
return "";
}
public static void printName(String dataLine) {
Scanner lineScan = new Scanner(dataLine);
String name = lineScan.next();
String gender = lineScan.next();
String rank = "";
while (lineScan.hasNext()) {
rank += lineScan.next() + " ";
}
System.out.println(name + (" ") + gender + (" ") + rank);
}
public static void printMeaning(String dataLine2) {
Scanner lineScan2 = new Scanner(dataLine2);
String name2 = lineScan2.next();
String gender2 = lineScan2.next();
String language = lineScan2.next();
String meaning = "";
while (lineScan2.hasNext()) {
meaning += lineScan2.next() + " ";
}
System.out.println(name2 + (" ") + gender2 + (" ") + language + (" ") + meaning);
}
}
It looks like sushain hit it with his comment.
The loop:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
could be changed to:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
break;
}
This way you do not find the second definition and do not print it.
In this loop, you don't need to find the next line, correct?
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan); // remove this line
}
}
If you remove the next find to dataLine and remove the while blocks in both instances where you search the file, you won't need a break, and you'll only end up printing one instance.
Do this:
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
printName(dataLine);
}