What am I doing wrong with this do loop? - java

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

Related

Chatbot won't respond

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

Calling Classes In Main Method

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() { ... }
}

Calling an object's method defined in List

I'm trying to call addContact method from main method using ArrayList called phone but its not working.
Here's the code:
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
public void addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
}
}
public class Main {
static void menu() {
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone;
while(true) {
menu();
int c = sc.nextInt();
if(c==1) {
phone.add().addContact();
//I'm trying to call addContact()
} else if(c==2) {
break;
}
}
}
}
Why I can't just call phone.add().addContact()?
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
}
public class Main {
static void menu()
{
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone = new Arraylist<A>();
while(true)
{
menu();
int c = sc.nextInt();
if(c==1)
{
System.out.println("Enter name:");
String name = sc.nextLine();
System.out.println("Enter number:");
int num = sc.nextInt();
phone.add(new A(name,num));
}
else if(c==2)
{
break;
}
}
}
}
Just removed you addContact and placed in in the while. Now i create a new Instance of A and add it to the list. This should work now. Please post more precise Questions in the future.
You need to create an instance of your list:
ArrayList<A> phone = new ArrayList<>();
ArrayList <A> phone;
Should be:
ArrayList phone = new ArrayList();
Also, the add() method in this line
phone.add().addContact();
should contain an A object to add to the ArrayList.
you need to return object of A
public A addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
return new A(name,num);
}
and
if(c==1)
{
phone.add(addContact);
}
Your problem starts here:
ArrayList <A> phone;
only declares that list; but doesnt define it. Thus you run into a NullPointerException when you try to run your code.
You need
ArrayList <A> contacts = new ArrayList<>();
instead. I took the freedom to give that variable a reasonable name, too. (this list is about storing contents, it is not storing phones; and it is also not a single phone ... just a list of contact information)
But there is more. You see, you are getting your abstractions wrong. Your Contact class (A is just a terrible name for that class) should not be dealing with a scanner to fetch its data.
Instead, you want to do something like:
class Contact {
private final String name;
private final int number;
Contact(String name, int number) {
this.name = name;
this.number = number;
}
and then, within your main method, you do something like:
boolean loop = true;
while (loop) {
... have user enter a name and a number
if (name.equals("STOP")) {
loop = false;
} else {
Contact contact = new Contact(name, number);
phones.add(contact);
}
}
I can't give the working code. Just check below points to make your program better.
Why you are creating constructor with arguments when you using add contact method.
Where you are created object for class A in class Main.
Try to check how to use ArrayList class. Because you are not using add() properly.

Is there a way to send variables from main class to subclass using user input JAVA

So I'm working on a (supposedly) simple java application that uses console inputs from a user, to change private variables in another class. Now I can change the value of the private variables in the EmpCls class directly from the main class by manually inputting a variable into the object, e.g.
EmpCls empObject1 = new EmpCls("josh"); but how do I get something like this
EmpCls empObject1 = new EmpCls(ctName); to work? where ctName is the variable that the user inputs. here's the relevant code from the main class:
import java.util.*;
public class NewWan {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
EmpCls empObject1 = new EmpCls(ctName);
String ctName = empObject1.getName();
System.out.println("enter name: ");
ctName = console.next();
}
}
And the subclass in question:
public class EmpCls {
private String name;
private String ext;
private int yearStarted = 0;
public EmpCls()
{
}
public EmpCls(String inName)
{
this.name = inName;
}
public void setEmpDetails(String inName) //, String inExt, int inYearStarted)
{
this.name = inName;
// this.ext = inExt;
// this.yearStarted = inYearStarted;
}
public String getName()
{
return this.name;
}
public int getYearStarted()
{
return this.yearStarted;
}
public String getExt()
{
return this.ext;
}
public void displayDetails()
{
System.out.println("Name: " + name);
System.out.println("Ext: " + ext);
System.out.println("Year Started" + yearStarted);
}
}
some parts of the code are commented just to enable easier trouble shooting, other parts are part of a different problem im working on.
You just need to reorder the statements a bit and remove the one that doesn't make sense:
public static void main(String[] args) {
System.out.println("enter name: ");
String ctName = console.next();
EmpCls empObject1 = new EmpCls(ctName);
}
Hum... just to organize your code in the good way ? You use variable before getting value, and before declare it... Strange way ^^
public static void main(String[] args) {
System.out.println("enter name: ");
String ctName = console.next();
EmpCls empObject1 = new EmpCls(ctName);
System.out.println("You just enter " + empObject1.getName());
}

How to apply modifications with init() method into toString()?

I have a problem when I want to display via toString() method the result of my program.
The result is "0.0" for my second input and I want the value I've entered.
public void init()
{
System.out.println("Enter name: ");
Scanner input = new Scanner(System.in);
if (input.hasNextLine())
{
setName(input.nextLine());
}
System.out.println("Enter number (double): ");
Scanner input2 = new Scanner(System.in);
if (input2.hasNextDouble())
{
setNumber(input2.nextDouble());
}
}
My toString method:
public String toString()
{
return this.name + " - " + this.number;
}
Edit:
import java.util.*;
import java.lang.*;
public class Branche
{
private String name;
private double number;
public Branche()
{
}
public String getName()
{
return this.name;
}
public double getNumber()
{
return this.number;
}
public void setName(String n)
{
this.name = n;
}
public void setNumber(double c)
{
this.number = c;
}
public String toString()
{
return this.name + " - " + this.number;
}
public void init()
{
System.out.println("Enter name: ");
Scanner input = new Scanner(System.in);
if (input.hasNextLine())
{
setName(input.nextLine());
}
System.out.println("Enter number (double): ");
Scanner input2 = new Scanner(System.in);
if (input2.hasNextDouble())
{
setNumber(input2.nextDouble());
}
}
}
TestClass:
import java.util.*;
public class TestBranche
{
public static void main(String [] args)
{
Branche b1 = new Branche();
b1.init();
System.out.println(b1);
}
}
I have tested the code below and it is working, Please check your setname() and setNumber() function.
And you need only one Scanner object to take inputs, No need to create multiple Scanner objects
public class NewClass {
String name;
double number;
public void init() {
System.out.println("Enter name: ");
Scanner input = new Scanner(System.in);
if (input.hasNextLine()) {
setName(input.nextLine());
}
System.out.println("Enter number (double): ");
if (input.hasNextDouble()) {
setNumber(input.nextDouble());
}
}
void setName(String name) {
this.name = name;
}
void setNumber(double number) {
this.number = number;
}
public String toString() {
return this.name + " - " + this.number;
}
public static void main(String args[]) throws Exception {
NewClass obj = new NewClass();
obj.init();
System.out.println(obj);
}
}
OUTPUT
run:
Enter name:
abc
Enter number (double):
89.78
abc - 89.78
BUILD SUCCESSFUL (total time: 7 seconds)
I'm going to guess your problem is here:
if (input2.hasNextDouble())
setNumber(input2.nextDouble());
}
It's likely that the scanner does not have a valid double.
Some fixes:
// identation
public void init() {
// You don't need and shouldn't open two scanners
final Scanner input = new Scanner(System.in);
// Makes your code clear by separating statements
System.out.println("Enter name: ");
String iName = input.nextLine();
setName(iName);
System.out.println("Enter number (double): ");
double iNumber = input.nextDouble();
setNumber(input2.nextDouble());
}
And this is how setNumber should look:
public void setNumber(double number) {
this.number = number;
}
I've propositaly skiped the hasNext() methods since you are not providing any kind of retrial code (if your user inputs something else but a double -> number would not be set).
How to guarantee that the user entered something that can be parsed as double:
public double readDouble(String message, Scanner sc) {
Double result = null;
do {
System.out.print(message + " (double): ");
String input = sc.nextLine();
try {
result = Double.valueOf(input);
} catch (NumberFormatException e) {
System.err.println("* ERROR: Input is not a number");
}
} while (result == null);
return result;
}
Usage:
double iDouble = readDouble("Enter number", sc);
This code avoids the many gotchas of hasNextDouble() and nextDouble(); for instance, a user can't attempt something like:
> Enter number (double): 123 something
Which would pass the hasNextDouble test but leave something on the stream.

Categories

Resources