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().
Related
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.
im fairly sure the mistake I am making within this code is short sighted.
so this program starts by getting the first name and last name of the user and storing them as independent strings. the next part is for the program to manipulate that value into getting the first initial of the first name, which is where im having my problem (I have little experience with the CharArray function and have spent enough independent research time for me to opt to asking here lmao)
import java.util.Scanner; //Needed for the Scanner class
public class NumericTypes {
public static void main (String [] args) {
//TASK #2 Create a Scanner object here
//Reading from system.in
Scanner keyboard = new Scanner(System.in);
//prompt user for first name
System.out.println("Enter your first name: ");
//scans the next input as a double
String firstName = keyboard.nextLine();
//prompt user for last name
System.out.println("Enter your last name: ");
//scans the next input as a double
String lastName = keyboard.nextLine();
//concatenate the user's first and last names
String fullName = (firstName + " " + lastName);
//print out the user's full name
System.out.println(fullName);
//task 3 starts here
//get first initial from variable 'fullName'
String firstinitial = fullName.CharAt(0);
System.out.println("the first initial is: " + firstinitial);
}
}
my desired output is for the last set of lines to display the first initial of the first name (user input). any help would be greatly, greatly appreciated
This can be done in two ways -:
1.) Replace String firstinitial with char firstinitial
2.) Wrap fullName.charAt(0) with String.valueOf like this:
String firstinitial = String.valueOf(fullName.charAt(0));
Both will work just fine.
I've only been learning java for a few weeks so I'm still a noob. I want the next line to print "mr/miss." + firstname + lastname;
however, i don't want to type the gender of the person in. I want there to be a list of male names (long list over 1000 names) and the program to detect if the firstname input is one of those male names. The program can then assign the correct title (mr/ms.)
How do I do this without making a normal arraylist and typing out each name individually (which'll take agessss).
Thanks in advance!
public static void main (String [] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Hello, will you be checking out today? (Y/N)");
String CheckOutYesOrNo = scanner.nextLine();
if (CheckOutYesOrNo.equalsIgnoreCase("y")) { x();}
else if (CheckOutYesOrNo.equalsIgnoreCase("n")) {System.out.println("Okay then. Enjoy the rest of your stay at the Rizty Hotel!");}
}
public static void x(){
System.out.println("Sure, would you mind telling me your last name?");
Scanner scanner = new Scanner(System.in); //how can I avoid making a new scanner?
String lastname = scanner.nextLine();
System.out.println("And your first name?");
String firstname= scanner.nextLine();
}
}
Sounds like a typical mapping. You could read all your names into a Map where the key is the name and the gender is the value. To resolve the gender just do something like genderMap.get(name).
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
My goal is to have the user be prompted for multiple separate inputs that would store the data in a manner that I could then manipulate.
For example:
Question:
What is your username?
What is your name?
Input:
Sparkeyy
Nelson
I then want to be able to take these and add them / multiply if they're numbers. This is what I have so far. (Also first question so sorry for poor formatting)
import java.util.*;
public class Program{
public static void main(String args[]){
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
}
public static void (name){
System.out.println("Enter your name: ");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("Your name is " + name);
}
}
Take a look here, they answered you're question thoroughly:
https://stackoverflow.com/questions/5287538/how-to-get-basic-user-input-for-java
You basically need a Scanner, like you're doing, and then for numbers:
scanner.nextInt();
There are also ways of converting properly formatted Strings to Ints/Doubles.