Hey everyone my name is Abraham Esparza and I am currently teaching myself JAVA. Currently I am trying to create a program that asks feedback from the user. I saw several examples of an “Old Mac Donald” program and I wanted to modify it so that it contains a custom method and prompts the user for feedback. I want the program to start with "Old Macdonald had a farm" and prompt the user to input "please enter EIEIO" if the user enter anything else other than "EIEIO" the program will ask them to try again. If the user types "EIEIO" the program moves to the rest of the song.
Please help.
here is what I have so far
package pkgnew.newthod;
import java.lang.String;
import java.util.Scanner;
public class NewNewthod {
public static void main(String[] args) {
System.out.println("Old MacDonald Had a Farm");
System.out.println( );
// print first verse with a method call
int EIEIO, User, message;
// print second and third verses (not done yet)
}
// This method prints the Old Macdonald line
public void User( ) {
System.out.println("Old Macdonald had a farm, E-I-E-I-O");
Scanner input = new Scanner(System.in);
String message = input.nextLine();
System.out.println(EIEIO(message));
}
public String EIEIO(String message){
System.out.printf("please enter EIEIO");
if (message.equals("E-I-E-I-O"))
return "please enter EIEIO";
return EIEIO(String (message));}
else // after the the user types EIEIO i want the program to proceed the next section, but i get illegal start of type
{
System.out.println("With a moo-moo here and a moo-moo there");
System.out.println("And on his farm he had a cow, E-I-E-I-O");
System.out.println("Here a moo there a moo");
System.out.println("Everywhere a moo-moo");
System.out.println( );{}
}
}
Your code quite messy and I can only offer advice but not an answer.
Re: Good Practice:
Use camelcase.
INDENT YOUR CODE.
Be as specific as you can regarding what your problem is.
Just solve little bits of your problem at a time. I see no reason to use Scanner() or overcomplicate things. Just keep it simple.
Always remember KISS and WIMP. (KISS is Keep It Simple Stupid) (WIMP is What Is My Problem) WIMP is my own invention for problem solving. ;D
Re: Your Code:
Your methods need to be static as they are in the same file as your main().
To call a method, just use the method name with parentheses, eg user();.
=====
"I'm currently trying to sort out your code and thought I'd whip this up quickly for your benefit. (It's your idea re-written my way)."
Hope this helps for now.
package oldMcDonald;
import javax.swing.JOptionPane;
public class MyAttempt {
public static void main(String[] args) {
callFirstLine();
callEiEiO();
System.out.println("And on his farm he had a cow, E-I-E-I-O,");
System.out.println("With a moo-moo here and a moo-moo there");
System.out.println("Here a moo, there a moo,");
System.out.println("Everywhere a moo-moo.");
callFirstLine();
callEiEiO();
}
public static void callFirstLine(){
System.out.println("Old McDonald had a farm,");
}
public static void callEiEiO() {
String input = "";
do{
input = JOptionPane.showInputDialog("Please Enter 'EiEiO': ");
}while (!"EiEiO".equals(input));
System.out.println(input);
}
}
Harmelodic is incorrect and unfortunately teaching you bad practices.
A method does not have to be static in order to be called in the same class as your main, further to this NEVER EVER do work in your main method, it is horrifically bad practice, not doing work in your main resolves the issue of having to have all static methods.
package oldMcDonald;
import javax.swing.JOptionPane;
public class MyAttempt {
public static void main(String[] args) {
MyAttempt matt = new MyAttempt();
matt.run();
}
public void run(){
callFirstLine();
callEiEiO();
System.out.println("And on his farm he had a cow, E-I-E-I-O,");
System.out.println("With a moo-moo here and a moo-moo there");
System.out.println("Here a moo, there a moo,");
System.out.println("Everywhere a moo-moo.");
callFirstLine();
callEiEiO();
}
public svoid callFirstLine(){
System.out.println("Old McDonald had a farm,");
}
public void callEiEiO() {
String input = "";
do{
input = JOptionPane.showInputDialog("Please Enter 'EiEiO': ");
}while (!"EiEiO".equals(input));
System.out.println(input);
}
}
Related
I have made two programs for an assignment. Now my professor wants me to put both programs into the same file and use a switch to create a menu where the user can use to choose what program they want to run. How do I do this? I will copy-paste both of my original programs below.
Program 1:
import java.util.Scanner;
public class ReadName {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please type in your full name: ");
String names = scanner.nextLine();
String[] namesSep = names.split(" ");
int lastString = namesSep.length - 1;
System.out.println(namesSep[0]);
System.out.println(namesSep[lastString]);
}
}
Program 2:
import java.util.Scanner;
public class FindSmith {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Type in your list of names: ");
String names = scanner.nextLine();
String[] namesSep = names.split(",");
for (int i=0; i<namesSep.length; i++) {
if (namesSep[i].contains("Smith")) {
System.out.println(namesSep[i]);
}
}
}
}
You have two classes that do work in a single main() method each.
Start with: moving the content of that main() methods into another static method within each class, like:
import java.util.Scanner;
public class ReadName {
public static void main(String[] args) {
askUserForName();
}
public static void askUserForName() {
Scanner scanner = new Scanner(System.in);
System.out.print("Please type in your full name: ");
...
}
}
Do that for both classes, and make sure that both classes still do what
you want them to do.
Then create a third class, and copy those two other methods into the new class.
Then write a main() method there, that asks the user what to do, and then
runs one of these two methods from there.
Alternatively, you could also do
public class Combo {
public static void main(String[] args) {
...
if (userWantsToUseClassOne) {
Readme.main(new String[0]);
} else {
FindSmith.main(...
In other words: as long as you keep your classes in the same directory, you can directly re-use what you already have. But it is much better practice to put your code into meaningful methods, like I showed first.
As you might know, each Java program only has a single entry point; defined by the method public static void main(String[] args). As each class can define this method only once and you have to specify the class the method is in in your META-INF.MF file, it is impossible to have multiple entry points.
So you have to implement the logic that controls the program flow and respects the user's choice on your own. You can e.g. ask the user via the command line what kind of subprogram they want to execute.
you can use multiple method instead of multiple class . and call all method from your main method should be solve your problem.....
public class Combo{
public void readName(){
// place here all code form main method block of ReadName class
}
public void findSmith(){
// place here all code form main method block of FindSmith class
}
public static void main(String[] args) {
Combo c = new Combo();
c.readName();
c.findSmith();
}
}
Rather than creating two classes, you can create single class with one main method. Where you can create 3 switch cases.
1) To call ReadName (RN)
2) To call FindSmith (FS)
3) To break the code (BR)
After every execution you can again call main method. (Optional) I have added that to continue the flow.
package test.file;
import java.util.Scanner;
public class Test {
private final static Scanner scanner = new Scanner(System.in);
//public class ReadName
public static void main(final String[] args) {
switch (scanner.nextLine()) {
case "FS" :
findSmith();
break;
case "RN" :
readName();
break;
case "BR" :
break;
default :
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
}
private static void findSmith() {
System.out.println("Type in your list of names: ");
final String names = scanner.nextLine();
final String[] namesSep = names.split(",");
for (int i = 0; i < namesSep.length; i++) {
if (namesSep[i].contains("Smith")) {
System.out.println(namesSep[i]);
}
}
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
private static void readName() {
System.out.print("Please type in your full name: ");
final String names = scanner.nextLine();
final String[] namesSep = names.split(" ");
final int lastString = namesSep.length - 1;
System.out.println(namesSep[0]);
System.out.println(namesSep[lastString]);
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
}
Welcome to this community! As #Stultuske comments, your better approach is convert your main methods to regular methods and invoke them depending on the user's input.
The steps you should follow are:
Join both main methods to a single class file.
Convert both main methods to regular methods:
Change their name from "main" to any other name. Usually, using their functionality as a name is a good practice. In your case, you can use the class names you already defined ("ReadName" and "FindSmith").
Remove their input parameter "args": as they are no more the main method of a class, they won't be reciving any args parameter, unless you specify it.
Define a new main method which reads from the scanner and call your new methods acordingly to the user input.
I'm struggling with a specific method which takes in a String parameter. The promptString method will print its parameter to the user as a prompt, and then return a String that is the result of reading the console via the nextLine() method. For this program you will use nextLine() exclusively.
I've prompted the user with a question using a parameter, and then used nextLine to read the string but after that I am a bit lost. How can I get the method to print to the console?
import java.util.*;
public class StarWarsName{
public static void main (String [] args) {
promptString("Enter your first name: ");
}
public static String promptString (String n) {
Scanner console = new Scanner(System.in);
String first = console.nextline();
return first.trim();
}
}
I think you are over-thinking this thing. Just print it to the console.
public static void main(String[]args){
String result = promptString("Enter your first name: ");
System.out.println(result);
}
FULL GITHUB FILES FOUND HERE
This is class Roulette.java
public static void main(String[] args) {
System.out.println("Welcome to roulette " + Casino.player());
}
This is class Casino.java
public static String player() {
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Please enter your name : ");
name = sc.nextLine();
return name;
}
When running Roulette.java it's not printing Casino.player() as a variable of your name, but running the function and asking for your name. I want to run Casino.java first,ask your name, then run roulette and welcome you with your name. NOT ASK YOUR NAME AGAIN.
Note: New to programming
The player() method in the Casino class prints out the message to input the users name. This will happen every time the method is called. To do what you want to do you need to create a conditional that checks if the player has already been set.
NOTE: This is not good practice or class design and in the future you should look into proper practice for class design and setting fields in a class. I would suggest posting this code on Code Review once you get it working to get a full answer on how this design can be improved.
Your Casino class should look something like this:
public class Casino {
private static String player = "";
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
this.player = sc.nextLine();;
}
return player;
}
}
Try something like this
String player = Casino.player();
System.out.println("Welcome to roulette " + player);
I made a simple chatbot that responds to certain prompts with string output in Java. I want this program to output it's responses to an element on an HTML based webpage, and read input from the a different element on the same page.
Does anyone know how I could accomplish this?
Here's the code if you're interested:
import java.util.Scanner;
public class botRun
{
#SuppressWarnings("resource")
public static void main(String[] args)
{
PepperBot bot = new PepperBot();
Scanner in = new Scanner(System.in);
String input = in.nextLine();
while(true)
{
if(bot.shouldRespond(input))
{
System.out.println(bot.getRespond(input));
}
input = in.nextLine();
}
}
}
all other methods, "shouldRespond(String x)" and getRespond(String x) are in a separate class for object "PepperBot()" and check if the bot should respond and get the appropriate response respectively.
Pretty much any solution will do, as long as it isn't costly.
First of all and before posting my question let me ask you people to stop downvoting my questions even if they seem stupid to you ,this site is an important place for me, it helps me a lot with my java doubts which are many,a question ban would be an heavy setback for me, so be helpful even by not answering!
Now for the question,
I have this method were i assign a value to a setter method with user input
public void addName() {
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add a citizen name?");
String answer = input.nextLine();
while (!answer.equals("y") || (!answer.equals("n"))) {
if (answer.equals("y")) {
String giveName = input.nextLine();
this.setName(giveName);
break;
} else if (answer.equals("n")) {
System.out.println("Not adding a name!");
break;
}else{System.out.println("Please choose y or n!");
answer = input.nextLine();}
}
}
this method is later called in main from object p1 and object p2 and being assigned a differend value for each one to the instance variable name
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Portugueses();
Pessoas p2 = new Alemaes();
p1.addName();
p2.addName();
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
but when i call the getName() method at the end of main both p1 and p2 have the same value!
Shouldn't each object get it´s own copy of an instance variable?
The Problem is in your addName()-function. Your running your loop(while (!answer.equals("y") || (!answer.equals("n")))) until a y or n is entered. So as soon as you enter it, your loop will stop.
In your loop your checking if the input that was made cotains a y or n. Now the problem should be clear. Your loop won't run with those two values entered, but inside the loop you want to check if one of those is entered.
Two little personal hints(everyone has another style): Don't use break; let your loops end themselfs. Do it with an boolean-variable and updating it's state.
The second hint would be to use one Scanner-Object. For example you could add a Scanner-parameter to your addName-function. Just init one in your MainClass.
Those hints and fixes of the problem applied to your code could look like that:
public void addName(Scanner input) {
System.out.println("Do you want to add a citizen name?");
String answer;
boolean isAnotherInputNeeded = true;
while (isAnotherInputNeeded) {
answer = input.nextLine();
if (answer.equals("y"))
{
System.out.println("What's the name?");
String giveName = input.nextLine();
this.setName(giveName);
isAnotherInputNeeded= false;
}
else if (answer.equals("n"))
{
System.out.println("Not adding a name!");
this.setName("No name entered");
isAnotherInputNeeded= false;;
}
else
{
System.out.println("Please choose y or n!");
}
input.reset();
}
}
And your MainClass:
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Pessoas();
Pessoas p2 = new Pessoas();
Scanner input = new Scanner(System.in);
p1.addName(input);
p2.addName(input);
System.out.println("You entered the following names:");
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
Hope that helps!