java println running function not returning function - java

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

Related

How to put multiple programs into one class?

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.

How do I find the smallest variable from a list of objects? (JAVA)

The code doesn't show any errors. However, I am getting an unexpected output. I am supposed to get the smallest number for age, but what I keep getting is the last value entered for age. Can you help me point out the mistakes in this code?
Maybe there is some logical error in the getYoungestPet() method?
package pet;
public class Pet
{
public static String petName;
public static int petAge, petWeight;
int youngestAge=9999;
static int test;
public static String setPetName()
{
return petName;
}
public int setPetAge()
{
return petAge;
}
public int setPetWeight()
{
return petWeight;
}
public int getYoungestPet() //probably an error here..?
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}
}
package pet;
import java.util.Scanner;
public class PetMain extends Pet
{
public static void main(String[] args)
{
System.out.println("How many pets do you want to enter? " );
Scanner data= new Scanner(System.in);
int petNumber=data.nextInt();
for (int i = 1;i<=petNumber; i++)
{
Pet PetObject = new Pet();
System.out.println("Please enter name for Pet " + i );
Scanner input = new Scanner(System.in);
petName= input.next();
System.out.println("Your pet's name is : " + petName);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Age" );
petAge= input.nextInt();
System.out.println("Your pet's age is : " + petAge);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Weight" );
petWeight= input.nextInt();
System.out.println("Your pet's weight is : " + petWeight);
System.out.println(" ");
System.out.println(PetObject.getYoungestPet());
}
}
}
The code is supposed to show the smallest age but it shows the latest entered age.
you should declare youngestAge as static variable. so that all of the petObject could share the same value.
static int youngestAge=9999;
your setter and getter methods are also not proper.
public static String setPetName()
{
return petName;
}
should be:
public static void setPetName(String name)
{
petName=name;
}
Also don't forget to set values into PetObject from main method.
...
petName= input.next();
PetObject.setPetName(petName);
...
There are many things that are problematic with this code.
But just to answer your question directly, think about how many pet objects there could be in this program if every time the for loop runs it recreates the pet object because it is inside the for loop.
however, simply moving it outside the for loop will not help because then you will simply keep resetting the values of the same pet object every time you run the for loop.
Consider making an array of pet objects.
Also, your code never actually accesses the pet objects instance variables
In addition, there are other problems with your use of static as others have pointed out.
cheers.
Each time you are creating a Pet, you are getting a different youngestAge with value 9999 for that object. So each time it is comparing the latest petAge with 9999 and giving you the latest petAge as your enterd petAge is less than 9999.
If you need to store the smallest age, then keep it in a static field. Cause, keeping an extra field to store the smallest age for all object is redundant for memory.
If you want your desired output with the existing design, then do this:
Make youngestAge static:
static int youngestAge=9999;
And also don't forget to make the method static too. There is no need to make it object property anymore, both the field variables, it is using, are static.
public static int getYoungestPet()
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}

Proper use of objects

I have this method addPerson (on the main) which is used to set the name of a person.
private static Person[] addPerson(Person _person[], int _minAge, int _id){
int personAge;
String personName;
Scanner scan = new Scanner(System.in);
System.out.println("What's his age?");
personAge = scan.nextInt();
if(personAge >= _minAge){
if(!_person[_id].getPerson().equals("")){
System.out.println("Person " + _person[_id].getPerson() + " already exists.");
}else{
System.out.println("Enter the name of the person");
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
_person[_id].setPerson(personName);
}
}else{
System.out.println("Person is not old enough");
}
return _person;
}
And here is the method setPerson in my custom class which is used to set the name of the person.
public void setPerson(String name){
System.out.println("Person added");
personName = name;
}
I know I should be doing the checking on whether that person already exists inside my setPerson method, but I am sort of confused with this. As you see I am expecting the user to input an integer, so I guess that I should check that right away to not get an error in case he inputs a string.
So my question is which should be checked within the same method and which on the method on my custom class?
Your code (and your question) is a bit confusing, but from what I can understand you want to know if you should check whether a person exists in the array in setPerson() or not?
Well, from what I can gather from your code, you should not do it in setPerson(), because that's a method in the Person class. The Person class shouldn't need to know anything about your array of Person objects.
So the way you're doing it now is probably your best bet.
Some general hints about the code:
There's no need to create a new Scanner, you can just use the one you have. So this
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
becomes this
personName = scan.next();
I would also suggest you use the name setName()instead of setPerson()for your method name, it doesn't make sense to have it named one way when what it's actually doing is something else.
I would do it this way. However I don't have java currently so I didn't test this snippet.
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
}
class Main {
private static final int minAge = 22;
private static Map<Person> addPerson(Map<Person> people, int id) {
if(people.containsKey(id)) {
// print that person with this id exists
return people;
}
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
if(age < minAge) {
// print that given age is invalid
return people;
}
String name = scanner.next();
people.get(id).setName(name);
return people;
}
}

Instance variable with the same value for different objects although different values were assigned

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!

New to Java, trying to create a program "Old Macdonald"

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

Categories