Why is this method called twice? - java

I'm currently doing a fairly simple project for my class, but I encounter this weird problem.
Here's the code:
import java.util.Scanner;
public class StudentMain {
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program allows you to organize a student's info in a clear, coherent form");
System.out.println("Press [1] to continue");
int x = kb.nextInt();
if (x==1){
Name();
ID();
String IDen = ID();
String name = Name();
System.out.println(name);
System.out.println(IDen);
}
}
private static String Name(){
String SName;
System.out.println("Enter Student name: ");
SName = kb.nextLine();
return SName;
}
private static String ID(){
String Sid;
System.out.println("Enter Student I.D: ");
Sid = kb.nextLine();
return Sid;
}
}
My intention for the program is listed in print statements above, but this is my biggest concern right now.
Whenever I run the program: I get this result (using it in Eclipse):
This program allows you to organize a student's info in a clear, coherent form
Press [1] to continue
1
Enter Student name:
Enter Student I.D:
John
Enter Student I.D:
1034172
Enter Student name:
John
John
1034172
As you can see, I used "John" and "1034172" as just examples, but its executing the two return methods twice. Any insight on this? All replies are welcome and greatly appreciated. Thanks!

Because you are calling it twice as result of first method calls has not been used so those are not needed.
Name();//<-------------(1)
ID();//<-------------(1)
//You can remove these lines
String IDen = ID();//<-------------(2)
String name = Name();//<-------------(2)
Note:You should follow the naming conventions as method name/variable name(except constant) should start with small case.
Here Name(); is method call and it's upto you whether you use the returned value or not.
Name();//First Call
String name =Name();//Second Call

Related

How print things in NetBeans?

I am trying to get NetBeans to print full name of customer with capital letters for the start of the names but I'm only get initials
package question1;
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
// TODO code application logic here
String First;
String Second;
String Fullname;
char UpperCaseFirst;
char UpperCaseSecond;
Scanner input=new Scanner (System.in);
System.out.println ("enter First name");
First=input.next();
System.out.println ("enter Second name");
Second=input.next();
UpperCaseFirst=Character.toUpperCase(First.charAt(0));
UpperCaseSecond=Character.toUpperCase(Second.charAt(0));
Fullname=UpperCaseFirst+" "+UpperCaseSecond;
System.out.println("custoemr:\n");
System.out.println(Fullname);
Please follow Java variable naming conventions, firstName, lastName and fullName (not Firstname, that looks like a class). Second, you shouldn't declare your variables until you need to. And you can use String.substring(int) to get the rest of the String. You can also use String formatting, with String.format, System.out.printf or both. Don't forget to call toLowerCase() at some point (if you want consistency). Like,
System.out.println("enter First name");
String firstName = input.next();
System.out.println("enter Second name");
String lastName = input.next();
String fullName = String.format("%c%s %c%s",
Character.toUpperCase(firstName.charAt(0)),
firstName.substring(1).toLowerCase(),
Character.toUpperCase(lastName.charAt(0)),
lastName.substring(1).toLowerCase());
System.out.printf("customer:%n%s%n", fullName);

Need help to resolve the issue ... not getting desired output. I would like to input two bank details and want output for the same

I am new to Java and stared learning things of my own, however I need some help to resolve the issue I am facing... let me know where I am wrong with my code.
My output is displaying like
Input -
Enter Bank Name: a
Enter Bank Account number: 1
Output -
Bank Name: null
Bank Account Number: 0
Why it is not displaying bank name as 'a' and account number as '1'. Kindly provide some help.
//Bank.java
import java.util.Scanner;
class Bank
{
String bank_name;
int bank_account_number;
void input_info()
{
Scanner input1 = new Scanner(System.in);
System.out.print("Enter Bank Name: ");
String bank_name = input1.nextLine();
Scanner input2 = new Scanner(System.in);
System.out.print("Enter Bank Account number: ");
int bank_account_number = input2.nextInt();
}
void display_info()
{
System.out.println("Bank Name: " +bank_name);
System.out.println("Bank Account Number: " +bank_account_number);
}
}
//Display_bank_details.java
class Display_bank_details
{
public static void main (String args[])
{
Bank details1 = new Bank();
Bank details2 = new Bank();
details1.input_info();
details2.input_info();
details1.display_info();
details2.display_info();
}
}
The main problem is the scoping of your variables. In your input_info method, you have these lines:
String bank_name = input1.nextLine();
...
int bank_account_number = input2.nextInt();
Those are declaring local variables that only exist in the method. Instead, you want to assign new values to the fields in your object. It's an easy change to make:
// Just assignments, not declarations
bank_name = input1.nextLine();
...
bank_account_number = input2.nextInt();
Additionally, I would:
Rename the variables and methods to follow Java naming conventions, e.g. inputInfo, displayInfo
Remove the bank prefix from the variables - you're already in a Bank class, so just name and accountNumber should be fine (although the latter suggests it should be a BankAccount rather than a Bank
Create a single Scanner object and pass that as an argument to the inputInfo method, rather than creating a new one for each line of input
The problem with your code is that you're doing something which is called "hiding". You're creating new variables with the same name as your class fields inside your methods.
String bank_name = input1.nextLine();
int bank_account_number = input2.nextInt();
Remove the types on these lines and you'll be assigning the values to your fields instead.

I don't exactly know how .equalsIgnoreCase work?

I am literally know and get the hang of the java right now and I'm writing the program that helps to records patient'd ID in the Hospital, i'll show the whole code first,then, I will tell where you will, here is the code
package hospitalsrecord;
import java.util.*;
import java.io.*;
public class HospitalsRecord {
public static Scanner read = new Scanner(System.in);
public static ArrayList nameList = new ArrayList();
public static ArrayList patientAge = new ArrayList();
public static ArrayList Disease = new ArrayList();
public static ArrayList dateHospitalized = new ArrayList();
public static ArrayList roomNumber = new ArrayList();
//adding patient function
public static void AddNewPatient () {
//Ask patient's name
System.out.println("Please enter patient's name:");
String patientName = read.next();
//Ask Patient's age
System.out.println("Please enter patient's age:");
int age = read.nextInt();
//Ask patient's illness
System.out.println("Please enter patient's Disease name (also include accidents eg. Leg broke by Car Accident):");
String illness = read.next();
//Ask patient Hospitalized date
System.out.println("Please enter patient's Hospitalized date(Total days not included):");
String HPTLdate = read.next();
//Ask patient's room number
System.out.println("Please enter patient's hospitalize room number(3 degits):");
int HRN = read.nextInt();
//Confirmation
System.out.println("Doctor, would you like to confirm the following(y/n)?");
System.out.println("Name:" + patientName);
System.out.println("Age:" + age);
System.out.println("Disease:" + illness);
System.out.println("Date Hospitalized (HPTLD):" + HPTLdate);
System.out.println("Room Number:" + HRN);
String Confirm = read.next();
if (Confirm.equals("y")) {
nameList.add(patientName);
patientAge.add(age);
Disease.add(illness);
dateHospitalized.add(HPTLdate);
roomNumber.add(HRN);
} else {
AddNewPatient();
}
}
//Searching patient that listed
public static void searchPatient (){
}
//remove the patient function
public static void removePatient() {
}
//text printing function when strat the program
public static void selectorPage(){
System.out.println("Hello Doctor, welcome to Hospital Recorder v1.0.0");
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
//text printing simmilar to selecterPage function but perform after function
public static void selecterPageAfterAction() {
System.out.println("Your action has been performed, doctor");
System.out.println("Would you like to perform another action?(y/n)");
choiceSelection = read.next();
if (choiceSelection.equals("y")){
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
}
//Selection var
public static String option;
public static String choiceSelection;
//Main program
public static void main(String[] args) {
selectorPage();
switch (option) {
case("add"): {
AddNewPatient();
break;
}
case("search"):{
searchPatient();
break;
}
case("remove"):{
removePatient();
break;
}
case("end"):{
break;
}
default: {
System.out.println("Please enter the indentified option");
break;
}
}
if (option.equalsIgnoreCase("end")){
}
}
}
I hope you guys can read every line because it was so so so so complex, but for someone who can read all of it, i'll know that you'll say I still need more time for hard working, no worry i'll spend sometime to get most knowledge from you guys first, but still working hard for program to complete while waiting for answers! anyway the point that I want you guys to focus at this point:
if (option.equalsIgnoreCase("end")){
}
It maybe too blank because I've just newly add it while i'm working on it. So, what I want to know is at the if statement I type option.equalsIgnoreCase("end"), Am I explain the computer to do the following?
1.Compare the the String variable options with the String"end"?
2.Tell the computer to do the action inside if statement's when the String option wasn't the word end?
And please tell me how this method work, i don't clearly understand it. I understand like this "It compare two strings if it wasn't the same then it's result is true" I know my explanation is wrong so could you please help me? thanks again for helping if you can.
option.equalsIgnoreCase("end") - equalsIgnoreCase will ignore whether string is in lower case or uppercase.
So it will enter into if block only when option variable has either end or END.
Your first assumption is correct, you are asking to compare String whether it is equal to end. But Second one is wrong, from above code it will enter and execute statements present inside if only when option is end/END.
If you want to go inside If block when the option is not end then add a not like this if(!option.equalsIgnoreCase("end")).
I Hope this clears your doubt!
The class String has two methods to compare one String to another.
See the example below:
public static void main(String[] args) {
String str1 = "beer";
String str2 = "Beer";
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
}
The first method equals() compares str1and str2and takes the case into consideration. Hence, the first comparison results in false, meaning Beer is not equal to beer.
The second method equalsIgnoreCase()does the same, except that it is not case-sensitive. Result of this comparison is true, meaning "ignoring the case, Beer is the same string as beer".
Hope this helps.

Java Constructor Syntax Issue

I need a little help understanding constructors. It isnt full code I just need help understanding one part. My code is as follows:
School.java
public class School {
private String name;
private int busNumber;
enter code here
public School (String name) {
this.name = name;
}
public String getSchoolName() {
return name;
}
public int getBusNumber() {
return bus Number;
}
Main.Java
System.out.println("Enter school number 1: ");
school1 = keyboard.nextLine();
School s1 = new School(school1);
System.out.println("Enter school number 2: ");
school2 = keyboard.nextLine();
School s2 = new School(school2);
System.out.println("School 1 is " + s1.getName());
System.out.println("School 2 is " + s2.getName());
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
//Now what I want to do is send the bus numbers to getBusNumber.
//How do I send bus1 so I can use s1.getBusNumber(); to call the number later! I feel like this should be so easy but I can't grasp it or find how to do it anywhere. I also do not want to use a set function. Any syntax help would be awesome!!
Thanks!
So if you need to not use a setter, you probably need to put it in the constructor.
So your constructor would be
public School (String name, int busNumber) {
this.name = name;
this.busNumber = busNumber
}
and your code would look like this
System.out.println("Enter school number 1: ");
school1 = keyboard.nextLine();
System.out.println("Enter school number 2: ");
school2 = keyboard.nextLine();
System.out.println("School 1 is " + school1);
System.out.println("School 2 is " + school2);
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
int intBus1 = Integer.parseInt(bus1)
School s1 = new School(school1, intBus1);
Then later in your code you can call get s1.getBusNumber() if needed
With the code you posted here is not possible since the busNumber is declared private...
You need (is a good practice) to define a setter for the member bus in the class School, you can to use public members but is not a good oop design since you need to change the access of the busNumber to public...
public void setBusNumber(int number) {
this.busNumber = number;
}
and call it from the main java
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
s1.setBusNumber(bus1);
Be aware you need to validate that what you read is a number because next line is returning strings...

java class and static method [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have a question regarding how to use variables that I have already used in a method into another method and how to set a limit on what a user can input, for example, for one of my java homework assignments I need to write a program that takes 3 to 6 names and then I need to create a new static method called geneateNewName() and it has to use the 3 to 6 names to display the names as well as take each of the names' second letter and produce a new name, how can I do this, thank you. Also, here is the code that I have so far:
public class Testing{
public static void main(String args[]){
Console c = System.console();
String str1;
String str2;
String str3;
String str4;
String str5;
String str6;
str1 = c.readLine("Please enter a family member's name: ");
str2 = c.readLine("Please enter a family member's name: ");
str3 = c.readLine("Please enter a family member's name: ");
str4 = c.readLine("Please enter a family member's name: ");
str5 = c.readLine("Please enter a family member's name: ");
str6 = c.readLine("Please enter a family member's name: ");
}
public static void generateNewName(){
System.out.println((str1.charAt(1)));
System.out.print(str22.charAt(1));
System.out.print(str33.charAt(1));
System.out.print(str44.charAt(1));
System.out.print(str55.charAt(1));
System.out.print(str66.charAt(1));
}
}
When I run this program on the command line, it only asks for six names, it doesn't display the newly generated name that is coded in the generateNewName() static method.
You never call generateNewName(). You should stick it in main somewhere. if you want it to be run.
you should call generateNewName method after the last read line like this:
str6 = c.readLine("Please enter a family member's name: ");
generateNewName();
}
Like the others have said, you never call generateNewName() so it doesn't run. But there are much bigger problems here.
You should be using Scanner to read user input. You're also declaring your string variables in main() which limits their scope so generateNewName() can't see them. There are several ways you can make your strings available to generateNewName(), including passing in all the strings individually or storing them all in an array and passing that in. However for your purposes you can just declare all the strings as static class variables.
class Testing
{
public static String str1;
public static String str2;
public static String str3;
public static String str4;
public static String str5;
public static String str6;
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a family member's name: ");
str1 = scanner.next();
System.out.println("Please enter a family member's name: ");
str2 = scanner.next();
System.out.println("Please enter a family member's name: ");
str3 = scanner.next();
System.out.println("Please enter a family member's name: ");
str4 = scanner.next();
System.out.println("Please enter a family member's name: ");
str5 = scanner.next();
System.out.println("Please enter a family member's name: ");
str6 = scanner.next();
generateNewName();
}
public static void generateNewName()
{
System.out.print(str1.charAt(1));
System.out.print(str2.charAt(1));
System.out.print(str3.charAt(1));
System.out.print(str4.charAt(1));
System.out.print(str5.charAt(1));
System.out.print(str6.charAt(1));
}
}
Since I'm assuming you're still a beginner the above code will work for you just fine. But I'd like to show you how you could cut way back on the number of lines of code you have using techniques you've probably already learned or hopefully will learn very soon. By using a for loop and string array you don't have to write out all those lines each time you want to prompt and collect data from the user. From there you can pass the array of names to generateNewName() and use another for loop to print out your new name. Now you don't need to declare your strings individually and you can control how many times the user is prompted to provide input by simply changing the size of the array.
class Testing
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
int arraySize = 0;
while(arraySize > 6 || arraySize < 3)
{
//Get user input here.
}
String[] names = new String[arraySize];
for(int i = 0; i < names.length; i++)
{
System.out.println("Please enter a family member's name: ");
names[i] = scanner.next();
}
generateNewName(names);
}
public static void generateNewName(String[] names)
{
for(int i = 0; i < names.length; i++)
{
System.out.print(names[i].charAt(1));
}
}
}
To print out the generated name on one line make sure you use System.out.print() and not System.out.println().

Categories

Resources