Get method returns null - java

So I tried to make a Hanger program in Java, and when I try to get to output a variable using a get method, it returns null. I first set up a Scanner object, then I set a String to the value the user inputs, then I use a set method to set the String to a new variable, finally, I call that new variable using the get method. It returns null, and I don't know why.
import java.util.Scanner;
public class Hanger
{
public String word;
public Hanger(){}
public void setWord(String new_word)
{
new_word = word;
}
public String getWord()
{
return word;
}
public static void main(String[] args)
{
Scanner input_names = new Scanner(System.in);
Scanner input_word = new Scanner(System.in);
Hanger word1 = new Hanger();
System.out.println("Please enter Player 1's name.");
String name1 = input_names.nextLine();
System.out.println("Please enter Player 2's name.");
String name2 = input_names.nextLine();
System.out.println("Are your names " + name1 + " and " + name2 + "?");
String names_correct = input_names.nextLine();
switch (names_correct)
{
case "no":
{
System.out.println("Please enter Player 1's name.");
name1 = input_names.nextLine();
System.out.println("Please enter Player 2's name.");
name2 = input_names.nextLine();
System.out.println("Are your names " + name1 + " and " + name2 + "?");
names_correct = input_names.nextLine();
}
case "No":
{
System.out.println("Please enter Player 1's name.");
name1 = input_names.nextLine();
System.out.println("Please enter Player 2's name.");
name2 = input_names.nextLine();
System.out.println("Are your names " + name1 + " and " + name2 + "?");
names_correct = input_names.nextLine();
}
default:
{
break;
}
}
System.out.println("Let's begin! " + name1 + ", please type a word that " + name2 + " will try to guess.");
String input_word1 = input_word.nextLine();
word1.setWord(input_word1);
System.out.println("Is " + word1.getWord() + " correct?");
}
}

It should be this.word=new_word in your setWord method of Hanger class

Related

Is there a way to make my code not case sensitive and shortcut words?

I'm trying to make it so when a user inputs an option its not case sensitive and they don't have to type the full option. I cant figure out how to do it.
package com.unspoken;
import java.util.Scanner;
import java.awt.*;
public class Main {
public static void main(String[] args) {
String play = "Play a game";
String internet = "Explore the internet";
String calculator = "Use the calculator";
String quit = "Quit Untouched";
String pickedEvent = "Unpicked";
Scanner scanner = new Scanner(System.in);
System.out.println("Hello, My name is Ghost. What's your name?");
String name = scanner.nextLine().trim();
System.out.println("Hello " + name + ". What would you like to do today?");
while (!pickedEvent.equals("Picked")) {
System.out.println(play);
System.out.println(internet);
System.out.println(calculator);
System.out.println(quit);
pickedEvent = scanner.nextLine();
switch (pickedEvent) {
case "Play a game":
System.out.println("Okay " + name + ", Loading games.");
pickedEvent = "Picked";
break;
case "Explore the internet":
System.out.println("Okay " + name + ", Loading the internet.");
pickedEvent = "Picked";
break;
case "Use the calculator":
System.out.println("Okay " + name + ", Loading calculator.");
pickedEvent = "Picked";
break;
case "Quit Untouched":
System.out.println("Are you sure you want to quit Untouched " + name + "?");
String quitAnswer = scanner.nextLine().trim();
if(quitAnswer.equalsIgnoreCase("Yes")){
System.out.println("Okay goodbye " + name + ", Have a nice day.");
break;
}else if(quitAnswer.equalsIgnoreCase("No")){
System.out.println("What would you like to do today " + name + "?");
continue;
}
}
}
}
}
try something like this
switch (pickedEvent.toUpperCase()) // changing to uppercase
{
case "PLAY A GAME": // select on uppercase
// ...
}
You can assign numbers to identify the tasks
String play = "1.Play a game";
String internet = "2. Explore the internet";
String calculator = "3. Use the calculator";
String quit = "4. Quit Untouched";
and ask user to enter number instead of typing in complete string
System.out.println("Hello " + name + ". What would you like to do today?, pick number");
and use the numbers in switch case instead of string, change pickedEvent to int
int pickedEvent = 0;
while (pickedEvent != 4) {
System.out.println(play);
System.out.println(internet);
System.out.println(calculator);
System.out.println(quit);
pickedEvent = Integer.parseInt(scanner.nextLine());
switch (pickedEvent) {
case 1:
System.out.println("Okay " + name + ", Loading games.");
break;
case 2:
System.out.println("Okay " + name + ", Loading the internet.");
break;
case 3:
System.out.println("Okay " + name + ", Loading calculator.");
break;
case 4:
System.out.println("Are you sure you want to quit Untouched " + name + "?");
String quitAnswer = scanner.nextLine().trim();
if(quitAnswer.equalsIgnoreCase("Yes")){
System.out.println("Okay goodbye " + name + ", Have a nice day.");
break;
}else if(quitAnswer.equalsIgnoreCase("No")){
System.out.println("What would you like to do today " + name + "?");
continue;
}
}
}
Here is a program that selects an option from an array of choices using a case insensitive prefix match. It does not solve your whole problem, but shows how you can do this kind of selection.
public class PartialMatch
{
public static void main (String[] args)
{
PartialMatch app = new PartialMatch ();
app.execute ();
}
private String[][] choices = {{"alpha", "A"}, {"beta", "B"}, {"alphabet", "C"}};
private void execute ()
{
check ("a");
check ("b");
check ("alpha");
}
private void check (String input)
{
String choice = selectChoice (input);
if (choice == null)
{
System.out.printf ("For input '%s' no selection was found %n%n", input);
}
else
{
System.out.printf ("For input '%s' the choice is '%s' %n%n", input, choice);
}
}
private String selectChoice (String input)
{
String result = null;
for (int n = 1; n <= input.length () && result == null; n++)
{
result = findChoice (input, n);
}
return result;
}
private String findChoice (String input, int n)
{
String result = null;
String needle = input.substring (0, n).toLowerCase ();
for (String[] option : choices)
{
String key = option[0];
if (key.length () >= n)
{
if (key.toLowerCase ().equals (input.toLowerCase ()))
{
System.out.printf ("Option %s is an exact match%n", key);
return option[1];
}
if (key.substring (0, n).toLowerCase ().equals (needle))
{
System.out.printf ("Option %s matches at length %s %n", key, n);
if (result != null)
{
System.out.printf ("Key '%s' is ambiguous %n", needle);
return null;
}
result = option[1];
}
}
}
return result;
}
}

Can i take userinput in a method java class?

public static void userinput() {
System.out.print("Enter your name : ");
Scanner d = new Scanner(System.in);
String username = d.next();
System.out.print("\nEnter your Age : ");
Scanner a = new Scanner(System.in);
int Age = a.nextInt();
System.out.print("\nEnter your roll number : ");
Scanner b = new Scanner(System.in);
int rollno = b.nextInt();
System.out.print("\nEnter your city : ");
Scanner c = new Scanner(System.in);
String city = c.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
return (0);
}
Is this the correct way to take input from a user in the method?
Here is the corrected version :
public static void userinput() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name : ");
String username = sanner.nextLine();//as next() reads only a word
System.out.print("\nEnter your Age : ");
int age = Integer.parseInt(scanner.nextLine());//as nextInt() does not read the \n which may cause next string inputs to be null
System.out.print("\nEnter your roll number : ");
int rollno = Integer.parseInt(scanner.nextLine());
System.out.print("\nEnter your city : ");
String city = scanner.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
//a void function doesn't compulsorily need a return statement
}
Also only one Scanner is enough!

Java: Retrieving information of an ArrayList with unique ID only prints out info of last element added to it

First I'll tell you what my problem is and below there's the code:
When I run my Class1 I can register my first object, which is given an unique ID. After that I register my second object, which also has a unique ID. Then I try retrieving my first objects information by asking for the ID of the first object. The problem now is, that the following will always be printed out, when I ask for the first object, which was added to the ArrayList: "The ID is wrong. You can't retrieve the objects information." However, when I try retrieving my second object (the object added last to the ArrayList), then it will print out the information just as I want.
My question is, why I only have access to the last object added to the ArrayList and what can I do to print the first objects information with its unique ID?
Here's Class1:
import java.util.Scanner;
import java.util.*;
public class Class1 {
public static void main(String[] args){
Class1 class1 = new Class1();
class1.presentoptions();
class1.createObject();
}
Scanner sc = new Scanner(System.in);
String name;
String ID;
double salary;
Class2 class2;
final String END_LINE = System.lineSeparator();
public void presentoptions(){
class2 = new Class2();
while (true){
System.out.println("=== Welcome === ");
System.out.println("Choose an option below: ");
System.out.println(" ");
System.out.println("1. Register an object. ");
System.out.println("2. Retrieve an objects information. ");
System.out.println("3. Quit this program. ");
int option = sc.nextInt();
switch (option) {
case 1:
System.out.println("What type of object? " + END_LINE
+ " - Worker. " + END_LINE);
// other objects
String type = sc.nextLine();
createObject(); // creating the specified employee
break;
case 2:
class2.retrieveObject();
break;
case 3:
System.out.println("You've quitted the program.");
System.exit(0);
default:
System.out.println("Error. Please try again.");
break;
}
}
}
public void createObject(){
class2 = new Class2();
System.out.println("Write the name of the object (worker): ");
String typeofobject = sc.nextLine();
UUID uniqueID = UUID.randomUUID();
String x = "" + uniqueID;
System.out.println("The new ID of the " + typeofobject + " is: " + uniqueID + ".");
System.out.println();
System.out.println("What's the name of the new " + typeofobject + "?");
name = sc.nextLine();
System.out.println("What's the salary of the new " + typeofobject + "?");
salary = sc.nextDouble();
Employee employee = new Employee(x, name, salary);
switch (typeofobject) {
case "Worker":
class2.registerObject(employee);
break;
default:
System.out.println("You missspelled the type of object. Run the program again.");
break;
}
}
}
Here's Class2:
import java.util.Scanner;
import java.util.ArrayList;
class Class2 extends Class1{
Scanner input = new Scanner(System.in);
ArrayList<Employee> employees = new ArrayList<Employee>();
final String END_OF_LINE = System.lineSeparator();
public void registerObject(Employee employee){
employees.add(employee);
}
public void retrieveObject() {
System.out.println("Which objects information do you want to retrieve? Type in his/her ID.");
String inputNewID = input.nextLine();
for(Employee employee: employees){
if(inputNewID.equals(employee.getID())){
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
} else {
System.out.println("The ID is wrong. You can't retrieve the objects information.");
}
}
}
}
At last, the Employee class:
import java.util.*;
public class Employee {
protected String ID;
protected String name;
protected double grossSalary;
final String END_OF_LINE = System.lineSeparator();
public String getID() {
return ID;
}
public Employee (String ID, String name, double grossSalary){
this.ID = ID;
this.name = name;
this.grossSalary = grossSalary;
}
}
Thanks.
You have the line
class2 = new Class2();
in your createObject() method. But class2 is where you have the ArrayList of employees. So you're just blowing away the old ArrayList each time you call createObject().
I think you can just get rid of that line.
Notice the for Loop:
for(Employee employee: employees){
if(inputNewID.equals(employee.getID())){
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
} else {
System.out.println("The ID is wrong. You can't retrieve the objects information.");
}
}
it will print FOR EACH Object in the employees list wherever it equals to the inputNewID or not, i think the intention was to print in ONCE.
you can get the wanted behavior using a boolean flag:
boolean isEmployeeFound = false;
for(Employee employee: employees){
if(inputNewID.equals(employee.getID())){
isEmployeeFound = true;
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name:"+employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
}
}
if(!isEmployeeFound){System.out.println("The ID is wrong. You can't retrieve the objects information.");}
Also as others mentioned get rid of the class2 = new Class2() line in createObject function.
The problem is with the if/else in the for loop of Class2, or more specifically with the else. On the 1st element of the loop the else will be triggered giving the message. One way to handle this would be to add a boolean to check if the ID is found and change the else block to an if check after the loop like this:
boolean idFound = false;
for(Employee employee: employees){
if(inputNewID.equals(employee.getID())){
idFound = true;
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
}
}
if(! idFound) {
System.out.println("The ID: " + inputNewID + " is not found. You can't retrieve the objects information.");
}

line of Java is printing duplicates

case 2:
System.out.println("Please enter Book ID: ");
String userinput2 = sc.next();
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
System.out.println("BookID: " + myBooks.get(i).getBookID() + "\nTitle: "
+ myBooks.get(i).getTitle() + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("Please enter new details of book");
System.out.println("Title: ");
String userinput7 = sc.next();
myBooks.get(i).setTitle(userinput7);
System.out.println("Author: ");
String u1 = sc.next();
myBooks.get(i).setAuthor(u1);
myBooks.get(i).setOnLoan(false);
myBooks.get(i).setNumLoans(0);
System.out.println("---------------------------------------------------");
System.out.println("The book has been successfully updated");
System.out.println("Book ID: " + myBooks.get(i).getBookID() + " " + "\nTitle: "
+ myBooks.get(i).getTitle() + " " + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("---------------------------------------------------");
}
else { System.out.println("Please enter a correct bookID");
}
}
I'm having a problem with my validation check. If the user enters a bookID that doesn't exist, instead of printing out "please enter a correct bookID" once, it prints it out 4 times, which amounts to the number of objects i have in the array list. Is there a way to sort this?
Your else statement is in the middle of the for statement
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
[[do stuff]]
}
else { System.out.println("Please enter a correct bookID");
}
}
It looks like it should be in the middle of the if statement
if (myBooks.get(i).getBookID().contains(userinput2)) {
for (int i=...) {
[[do stuff]]
}
}
else { System.out.println("Please enter a correct bookID");
}

Inputting and validating the email address in JAVA

I have written the below code but i am unable to make it loop if the input entered is false.Kindly help me.
System.out.println("Please enter your email address ex:xyz#gmail.com");
String emailaddress=name.nextLine();
String email_regex = "[A-Z]+[a-zA-Z_]+#\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
String testString = emailaddress;
Boolean b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
System.out.println("Email address is " +emailaddress);
Here goes the 3 functions :
public class abc{
public static void main(String[] args){
inputEmail();
}
public boolean checkEmailvalidity(String emailaddress){
String email_regex = "[A-Z]+[a-zA-Z_]+#\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
boolean b = testString.matches(email_regex);
return b;
}
public void inputEmail(){
System.out.println("Please enter your email address ex:xyz#gmail.com");
String emailaddress=name.nextLine();
boolean a = checkEmailvalidity(emailaddress);
if(a){
System.out.println("Valid email");
} else {
System.out.println("InValid email");
inputEmail();
}
}
}
here is with your updated answer :
package smsmain;
import java.util.Scanner;
public class CStudentinfo {
public static void createstudent() {
Scanner name = new Scanner(System.in);
System.out.println("Please enter your first name:");
while(!name.hasNext("[a-zA-Z]+")){
System.out.println("Please re-enter your name, use alphabets)
System.out.println("Please enter your first name:");
name.nextLine();
}
String firstname=name.nextLine();
System.out.println("Your firstname is " + firstname);
inputEmail();
boolean b;
do {
System.out.println("Please enter your email address ex:xyz#gmail.com");
String emailaddress=name.nextLine();
String email_regex = "[A-Z]+[a-zA-Z_]+#\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
String testString = emailaddress;
b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
System.out.println("Email address is " +emailaddress);
}while(!b);
String testString;
String emailaddress;
boolean b = false;
do {
System.out.println("Please enter your email address ex:xyz#gmail.com");
Scanner name = new Scanner(System.in);
emailaddress = name.nextLine();
String email_regex = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
testString = emailaddress;
b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
} while (!b);
System.out.println("Email address is " + emailaddress);

Categories