This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
We had a programming exam last week and I wasn't able to do it.
We were asked to make a program that will ask the user to select either of these three options:
given name
middle name
last name.
After selecting, you are asked to enter a name using scanner.
Then it will ask you if you want to try again, if you input yes, the program will loop again and if you enter the same name, it will prompt an error saying you already set it that way.
I've done all of it except that part, comparing the values.
How do I compare the 1st and 2nd input using scanner?
Here is what I have done so far.
public class PXM {
private String givenname;
private String middlename;
private String lastname;
public void setGN(String gn) {
this.givenname = gn;
}
public void setMN(String mn) {
this.middlename = mn;
}
public void setLN(String ln) {
this.lastname = ln;
}
public boolean equals() {
}
}
import java.util.*;
public class TestPXM {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String yes;
int t;
PXM p1 = new PXM(); {
System.out.println("1. given name ");
System.out.println("2. middle name");
System.out.println("3. last name");
System.out.print("select method: ");
int method = sc.nextInt();
if (method == 1) {
System.out.println("enter given name: ");
String gn = sc.next();
p1.setGN(gn);
}
}
}
}
You don't use the scanner to compare. You would save the values input and compare against those.
I would use a Set to hold the values, because Set values are guaranteed to be unique, and that suits the application. You would use Set.contains() to find if you've already got a name.
Assuming you have two Strings, s1 and s2 and you want to compare them, you should use the equals() method:
if (s1.equals(s2)) {
// strings are the same
} else {
// strings are different
}
If you don't know how to use Scanner, take a look here.
You can use this:
Since you've already set the variable in:
p1.setGN(gn);
you can read the input again after suitable prompt like:
String gn=sc.next();
and then compare the stored variable in the object p1 using a getter method:
public String getGN()
{
return this.givenname;
}
Now if you do
if(gn.equals(p1.getGN())
{
System.out. println("You have already set that");
}
You will get the desired result.
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
I have an assignment where I have to have a class named Employee with two variables and a class called Salary that inherits those variables and declares new ones. Within the Salary class, I have to create a method that will take user input for the different variables. The first number inputted is the number of employees you are giving information for and tells the loop how many times to go around. After typing in the information for all the employees the information must be presented like this
123 John engineer 40000.0
124 Emma Testing 33000.0
The only other thing that is required in the program is a function that will check the salary variable and if it is under 20000, not display the employee information to the console.
I have the user input working but I can't seem to get the array to display properly. Whatever I try I either get gibberish or null. I have tried putting the array and the array printing function in the display method and the main method and it doesn't make a difference. How can I fix this?
Side note: I know having different scanners for each input is not the best way of doing things it's just temporary. I'm trying to get the program to work before cleaning it up. The reasoning for it is a type mismatch error using one scanner as a result of scanning an int, then two strings, then a double.
This is the code I have right now:
import java.util.Scanner;
class Employee {
int employee_id;
String employee_name;
Employee(int employee_id, String employee_name) {
}
Employee() {
}
}
class Salary extends Employee {
double monthly_salary;
String designation;
int num_of_employees;
int n = 0;
Salary(int employee_id, String employee_name, String designation, double monthly_salary) {
super(employee_id, employee_name);
}
Salary() {
}
void display() {
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
Scanner a = new Scanner(System.in);
Scanner e = new Scanner(System.in);
Scanner t = new Scanner(System.in);
num_of_employees = s.nextInt();
for (;n<num_of_employees;) {
employee_id = c.nextInt();
employee_name = a.nextLine();
designation = e.nextLine();
monthly_salary = t.nextDouble();
n++;
}
s.close();
c.close();
a.close();
e.close();
t.close();
}
}
public class Solution2 {
public static void main(String[] args) {
Salary sal = new Salary();
Salary salary[] = new Salary[10];
sal.display();
salary[sal.n] = new Salary(sal.employee_id, sal.employee_name, sal.designation,
sal.monthly_salary);
if (sal.monthly_salary >= 20000) {
System.out.println(salary[sal.n]);
}
else {
System.out.println("");
}
}
}
The result from the array with this code is
Salary#7b23ec81
This question already has answers here:
How to find an object in an ArrayList by property
(8 answers)
Closed 5 years ago.
I've just started learning java and I'm trying to create an application to register students.
Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.
public class RegStudent {
ArrayList<Student> studentList = new ArrayList<>();
Scanner input = new Scanner(System.in);
public void reggaStudent(int start) {
while (start != 0) {
String programNamn, studNamn;
int totalPoint, antalKurser;
System.out.println("Vad heter programmet?");
programNamn = input.nextLine();
System.out.println("Vad heter studenten");
studNamn = input.nextLine();
System.out.println("Hur många poäng har studenten?");
totalPoint = input.nextInt();
System.out.println("Hur många kurser är studenten registrerad på?");
antalKurser = input.nextInt();
// Add student to list of students
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
System.out.println("Vill du registrera in en fler studenter? "
+ "Skriv 1 för ja och 0 för nej");
start = input.nextInt();
input.nextLine();
} // End of whileloop
}
}
The class is:
public class Student {
private int totalPoint;
private int antalKurser;
private String programNamn;
private String studNamn;
private static int counter;
public Student(int totalPoint, int antalKurser, String program, String studNamn) {
this.totalPoint = totalPoint;
this.antalKurser = antalKurser;
this.programNamn = program;
this.studNamn = studNamn;
counter++;
}
public int getTotalPoint() {
return totalPoint;
}
public void setTotalPoint(int totalPoint) {
this.totalPoint = totalPoint;
}
public int getAntalKurser() {
return antalKurser;
}
public void setAntalKurser(int antalKurser) {
this.antalKurser = antalKurser;
}
public String getProgramNamn() {
return programNamn;
}
public void setProgramNamn(String programNamn) {
this.programNamn = programNamn;
}
public String getStudNamn() {
return studNamn;
}
public void setStudNamn(String studNamn) {
this.studNamn = studNamn;
}
public static int getCount(){
return counter;
}
#Override
public String toString() {
return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
+ "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
}
}
How do I go about to get and set the instance variables in specific instance? I.e find the instances.
I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.
I've added a counter just to see I actually created some instances of the class.
You simply query objects for certain properties, like:
for (Student student : studentList) {
if (student.getProgramName().equals("whatever")) {
some match, now you know that this is the student you are looking for
In other words: when you have objects within some collection, and you want to acquire one/more objects with certain properties ... then you iterate the collection and test each entry against your search criteria.
Alternatively, you could "externalize" a property, and start putting objects into maps for example.
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
You now have your Student objects in a list. I assume you have something like
List<Student> studentList = new ArrayList<>();
somewhere in your code. After you populate the list with Student objects, you can use it to find instances. You need to decide what criteria to use for a search. Do you want to find a student with a specific name? Do you want to find all students in a given program? Do you want to find students with more than a certain number of points?
Maybe you want to do each of these. Start by picking one and then get a piece of paper to write out some ideas of how you would do the search. For example, say you want to find a student with the name "Bill". Imagine that you were given a stack of cards with information about students. This stack of cards represents the list in your program. How would you search this stack of cards for the card with Bill's name on it? Describe the steps you need to take in words. Don't worry about how you will code this yet. The first step in writing a computer program is breaking the solution down into small steps. After you have a clear idea how you might do this by hand in the physical world, you can translate your description into Java code.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
Class File:
public class Student {
public String stu_FName;
public String stu_LName;
public String stu_ID;
}
This is the code I wrote to get inputs from the user
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter value for X");
int x = sc.nextInt();
ArrayList<Student> stuIDArray = new ArrayList<Student>(4);
while (x != 0) {
Student st = new Student();
System.out.println("Enter First Name");
st.stu_FName = sc.next();
stuIDArray.add(st);
System.out.println("Enter value fo1r X");
x = sc.nextInt();
}
When I print the size of the array after storing values using the above code, size works fine,
System.out.println(stuIDArray.size());
but when i try to print out the results in any of the following methods, it prints some code type format
for (int i=0;i<stuIDArray.size();i++){
System.out.println(stuIDArray.get(i));
}
for (Student a : stuIDArray){
System.out.println(a);
}
output :
com.company.Student#45ee12a7
com.company.Student#330bedb4
com.company.Student#45ee12a7
com.company.Student#330bedb4
You need to specify name of the variable you need to get data for. Below code is working fine.
for (int i = 0; i < stuIDArray.size(); i++) {
System.out.println(stuIDArray.get(i).stu_FName);
}
for (Class1 a : stuIDArray) {
System.out.println(a.stu_FName);
}
This would happen because when you are trying to print the student "object", it would print the string representation of the student object.
What you need to do is to override the toString method in Student class with proper properties somewhat like,
#Override
public String toString() {
return "Student [stu_FName=" + stu_FName + ", stu_LName=" + stu_LName
+ ", stu_ID=" + stu_ID + "]";
}
You have to learn about toString() method. When you try to use System.out.println() on an object, its toString() method is invoked, and the signature you've been getting, e.g. com.company.Student#330bedb4 is the default return value of those methods, as explained here. If you'd like a proper detail of each field, override the toString method in your Student class. For more, check out this answer
This question already has answers here:
Ways to iterate over a list in Java
(13 answers)
Closed 7 years ago.
import java.util.*;
public class ChristmasParty
{
private Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
ChristmasParty cp = new ChristmasParty();
cp.run();
}
public void run()
{
menu();
addName();
}
public void menu()
{
System.out.println("Welcome to the guests lists program");
System.out.println("Enter a name or enter X to quit");
}
public void addName()
{
String nameAdded = "";
ArrayList<String> guestsLists = new ArrayList<String>();
do
{
System.out.print("Enter a name: ");
nameAdded = input.nextLine();
guestsLists.add(nameAdded);
System.out.println("-----------------------------------------------");
System.out.println(nameAdded + " has been added to the guests list.");
}while(!nameAdded.equals("X"));
System.out.println("Guests lists:");
System.out.println("========================");
System.out.println(guestsLists.get(0));
System.out.println(guestsLists.get(1));
System.out.println(guestsLists.get(2));
System.out.println(guestsLists.get(3));
System.out.println(guestsLists.get(4));
System.out.println(guestsLists.get(5));
System.out.println(guestsLists.get(6));
System.out.println(guestsLists.get(7));
System.out.println(guestsLists.get(8));
System.out.println(guestsLists.get(9));
System.out.println(guestsLists.get(10));
System.out.println(guestsLists.get(11));
System.out.println(guestsLists.get(12));
System.out.println(guestsLists.get(13));
System.out.println(guestsLists.get(14));
System.out.println(guestsLists.get(15));
}
}
Hello, I am trying to make a code that will prompt the user to enter a name,and that name will be saved in the arraylists, and then once the user exits and quits by pressing "X", it will display all the names in the lists. However how do I make the System.out.println(guestsLists.get()); codes simpler rather than typing it all out?
Put this code:
}while(!nameAdded.equals("X"));
System.out.println("Guests lists:");
System.out.println("========================");
for(int i = 0; i < guestsLists.size(); i++)
{
System.out.println(guestsLists.get(i));
}
OR
for(String s : guestsLists)
{
System.out.println(s);
}
And remove all the sysouts after the
System.out.println("========================");
Simply iterate through the list using an enhanced for loop:
...
for (String name : guestsLists) {
System.err.println(name);
}
...
You can use that form of a for loop when you do not need an index inside the loop, but just want to iterate over the collection. In these cases, it is much easier to read (and less code) than using an explicit index (or using an explicit Iterator).
See also https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
I created a JAVA code, and I don't have any errors, but when I run the code, the output does this:
Enter a word: Thank you for entering a word! And it does not let me enter anything, when I intend for the code to let me enter a word, then it checks if it is a word, and gives the answer if it is a word, or none if it isn't. (It is my first time asking on this site) Here's the code:
package files;
import java.util.Scanner;
public class Testprinter {
static boolean myBoolean = false;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args){
String usersInput;
while(myBoolean != true)
{
System.out.print("Enter a word: ");
usersInput = userInput.toString();
myBoolean = checkInput(usersInput);
}
checkifComplete();
}
public static boolean checkInput(String usersInput){
if(usersInput == (String)usersInput)
{
return true;
} else { return false; }
}
public static void checkifComplete(){
if(myBoolean = true){
System.out.print("Thank you for entering a word!");
}
}
}
This line is wrong:
if (usersInput == (String)usersInput)
It should be:
if (usersInput.equals(usersInput))
In Java, strings (and in general: all objects, that is all types that are non-primitive) must me compared using the equals() method, which tests for equality. The == operator is fine for testing equality between primitive types, but for objects it tests for identity - a different concept, and 99% of the time, not what you want.
And besides, you're comparing a string with itself! it'll always return true, I'm quite sure that's not what you want to do… notice that the parameter must have a different name, currently it's called just like the attribute. Perhaps this is what you meant?
public static boolean checkInput(String input) {
return usersInput.equals(input);
}
You forgot scanner.nextLine(); thats reason its not asking you enter anything.
Instead of usersInput = userInput.toString();
Use:
String usersInputStr = scanner.nextLine();
Follow this link - for how to use scanner: How can I read input from the console using the Scanner class in Java?
Your issue is using userinput.toString(), when you should be using usersInput = userInput.next();. You are currently retrieving the string representation of the scanner, not getting a word.
Corrected main:
public static void main(String[] args){
String usersInput;
while(myBoolean != true)
{
System.out.print("Enter a word: ");
usersInput = userInput.next();
myBoolean = checkInput(usersInput);
}
checkifComplete();
}