Java GetstringMethod - java

The assignment:
Write a program (Greetings) that prompts the user to enter the first name, the last name, and year of birth, then it returns a greetings message
in proper format (see the example below).
Create a method(s) that accept the scanner and a prompt as parameters and return the user input. A separate method should accept the user input results as parameters, format and print the results. No print statement or scanner input should happen inside main(). Here is an example dialogue with the user:
Please enter your first name:
tom
Please enter your last name:
cruise
Please enter your year of birth:
1962
Greetings, T. Cruise! You are about 53 years old.
I finished the code, but right now it is giving me a compilation error. How do i fix it?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
Scanner newscanner = new Scanner(System.in);
String ask = ("Please enter your first name: ");
String ask2 = ("Please enter your last name: ");
String ask3 = ("Please enter your year of birth: ");
public static String getString(Scanner newscanner, String ask, String ask2, String ask3){
System.out.println(ask);
String first = newscanner.next();
String firstletter = first.substring(0,1).toUpperCase() ;
return firstletter;
System.out.println(ask2);
String second = newscanner.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
String lastname = y.substring(0,1).toUpperCase();
return lastname;
System.out.println(ask3);
int third = newscanner.nextInt();
int age = (2015 - third);
return age
System.out.println("Greetings, "+ firstletter + ". " + lastname+"!" +" You are about " + age + " years old");
}
}
}

Hard to read, but I think you actually have the getString() method inside your main() method - it needs to be after it, and only be called from inside main(), not defined there.

Related

Java - Extracting Substrings Programmatically

I am trying to create a code that accepts a user's full name and returns first and last names and initials. Since a user's name length varies, I did not want to use hard coding, so I extract names and initials programmatically.
However when I run it and enter a name, I get the following error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
I looked into my code carefully and cannot see where exactly I miscalculated on the index range. I tried to find similar questions here, but though I did see similar problems, they have to do with C++ or Perl, not Java.
package nameSubstring;
import java.util.Scanner;
public class NameSubstring {
public static void main(String[] args) {
/*
* This is a program that accepts a user’s full name as a string (e.g. Margaret Thatcher) and displays to the user his/her first name, last name and initials in the following format:
Your first name is Margaret and your last name is Thatcher and your initials are MT.
*/
System.out.println("This program will take your full name and display your first name, last name, and initials.");
Scanner scanner = new Scanner(System.in);
String firstName, lastName, firstNameInitial, lastNameInitial;
System.out.println("Please enter your full name, e.g. Jane Smith:");
String fullName = scanner.next();
int nameSpace = fullName.indexOf(' ');
firstName = fullName.substring(0, nameSpace);
lastName = fullName.substring(nameSpace)+1;
firstNameInitial = firstName.substring(0, 1);
lastNameInitial = lastName.substring(0, 1);
System.out.println("Your first name is " + firstName + ", " + "your last name is " + lastName + ", " + "and your initials are " + firstNameInitial + lastNameInitial + ".");
}
}
Instead of next() use nextLine():
String fullName = scanner.nextLine();
and correct the error with the +1 which must be inside the parenthesis:
lastName = fullName.substring(nameSpace+1);

Splitting a Scanner Input Into Strings

I've been looking for an answer to this for a while, but for some reason, none of them seem to work.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter full name (last, first)");
String[] personalInfo = scanner.next().split(", ");
String firstName = personalInfo[1];
String lastName = personalInfo[0];
System.out.println("Your info: " + firstName + " " + lastName);
There is my code. I'm basically trying to obtain the personal info, which would be the first and last name. I want to split the first and last name into 2 different strings, but whenever I try to print this, I get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 > out of bounds for length 1
at Fines.main(Fines.java:11)
I'm confused because I even started the array with 0 like I was supposed to.. I just don't understand what is going incorrectly.
Please give me a hand - thanks in advance!
What you want is scanner.nextLine() to read from standard input up until end of line. Then split would work as you expected.
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter full name (last, first)");
String[] personalInfo = scanner.nextLine().split(", ");
String firstName = personalInfo[1];
String lastName = personalInfo[0];
System.out.println("Your info: " + firstName + " " + lastName);
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 1 > out of bounds for length 1 at Fines.main(Fines.java:11)
As the size of the personalInfo is 1 not 2.
use nextLine() instead of next() because next() will only return the input that comes before a space.
String[] personalInfo = scanner.next().split(", "); should be
String[] personalInfo = scanner.nextLine().split(", ");
You might want to read this What's the difference between next() and nextLine() methods from Scanner class?
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Please enter full name (last, first)");
String firstName = scan.next();
String lastName = scan.next();
System.out.println("Your info: " + firstName + ' ' + lastName);
}
scanner.next() read until next delimiter (space by default), so it ready only the firstName. Just replace it with scanner.nextLine() or use scanner.next() two times.

Java how to pass and return string, method?

import java.util.Scanner;
import javax.swing.JOptionPane;
public class StarWars {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String firstName = "";
String lastName = "";
String maidenName = "";
String town = "";
System.out.print("What is your first name? ");
firstName = reader.nextLine();
System.out.print("What is your last name? ");
lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
maidenName = reader.nextLine();
System.out.print("What town were you born? ");
town = reader.nextLine();
String Sfirstname = firstName.substring(0,2);
String Slastname = lastName.substring(0,3);
String SmaidenName = maidenName.substring(0,2);
String Stown = town.substring(0,3);
String Star = Sfirstname + Slastname;
String War = SmaidenName + Stown;
String StarWar = Star + War;
System.out.print("Your Star Wars name is: " + StarWar);
}
public static String StarWar (String Star, String War) {
String name;
name = Star + " " + War;
return War;
}
}
So this is my code about my project. While I'm doing my project I have some problem about the returning method and passing method.
I set up the main method perfectly to print out thing that what I want to see.
The problem is I also have to use passing method and returning method. My teacher want me to do two things with passing/returning method.
Pass all this data to your method, and the method should generate and return the users Star Wars name.
Get the return value of the method, and display it to the screen.
I have no idea what should I do with this problems (took 5 hrs to do everything I learn but wrong..).
Can someone give a hint or teach me what actually my teacher want me to do and How I can do this?
I really need help from you guys.
Additional, if I run a program it should be like this.
first name? user input: Alice last name? user input:Smith mothers maiden name? user input: Mata town were you born? user input: Sacramento
Your Star Wars name is: SmiAl MaSac
There are a few things we can improve here, lets start with the method - the method name looks like a constructor and doesn't perform the logic itself, lets describe what it does and move the logic into the method - we don't need all of those temporary variables (we can use a StringBuilder) like
public static String buildStarWarsName(String firstName, String lastName,
String maidenName, String town)
{
return new StringBuilder(lastName.substring(0, 3)) //
.append(firstName.substring(0, 2)) //
.append(" ") // <-- for the space between first and last
.append(maidenName.substring(0, 2)) //
.append(town.substring(0, 3)) //
.toString();
}
Then you can initialize your variables when you read them and finally call the method
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("What is your first name? ");
String firstName = reader.nextLine();
System.out.print("What is your last name? ");
String lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
String maidenName = reader.nextLine();
System.out.print("What town were you born? ");
String town = reader.nextLine();
System.out.print("Your Star Wars name is: " + //
buildStarWarsName(firstName, lastName, maidenName, town));
}
You should return what you evaluated instead :
return name;
and then call this defined method while you want to read the value.
The changes highlighted in the comments as well:
String StarWar = Star + War; // this would not be required, as handled by your method 'starWarName'
System.out.print("Your Star Wars name is: " + starWarName()); // calling the method defined
}
public static String starWarName (String Star, String War) { //renamed method to break the similarity with other variables
String name;
name = Star + " " + War;
return name; //returning the complete star war name
}
Your method is returning the 'war' parameter. Based on what your trying to do it looks like it should be returning 'name'. That's what the method built.

Limiting the number of characters in a user Scanner input in String in Java

This code is supposed to print the user's name when they enter it and limit it's length to 20 characters, but it only works when the user's name is longer than 20 chars. I get en error when it's below 20. Any ideas on how to fix this?
Thank you.
String name;
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
String cutName = name.substring(0, 20);
if (name.length()>20) {
name = cutName;
System.out.print("Hello " +name+"!");
}
Just take the lower index between 20 and the String 's length .
name.substring(0, Math.min(20,name.length()));
If you place your String cutName inside the if, the error should disappear. You cannot take a substring from a string that is longer than the String itself.
if (name.length()>20) {
String cutName = name.substring(0, 20);
name = cutName;
}
System.out.print("Hello " +name+"!");
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
if(name.length()>20)
name = name.substring(0,20);

Generating username with given information from the user

Hi Im Can Somebody help me with my program ?
my professor ask us to do a program that will get information from the user and generate a 6 letter username from the lastname and firstname of the user.
the first 3 letters of the user name is the first 3 letters of the firstname and the other 3 is the last 3 letters of the lastname of the user. and we need to test it by log-in module
to test if the username and password are match on the generated username and user inputted password
As far as im doing i cant find a answer on this and our professor didn't teach us about this this and im struggling right now.
this is my program right now>>>
public static InputStreamReader r = new InputStreamReader(System.in);
public static BufferedReader i = new BufferedReader(r);
public static void main(String[]args) throws Exception{
String Lname,Fname,Mi;
int age,bday;
float pass;
System.out.print("Enter Last Name: ");
Lname=i.readLine();
System.out.print("Enter First Name: ");
Fname=i.readLine();
System.out.print("Enter Middle Name: ");
Mi=i.readLine();
System.out.print("Age: ");
age=Integer.parseInt(i.readLine());
System.out.print("Birthday (MM/DD/YY) :");
bday=Integer.parseInt(i.readLine());
System.out.println("Password Must Be A 4-6 Digit Combination");
System.out.print("Enter Password : ");
pass=Float.parseFloat(i.readLine());
System.out.println("Please Wait While Generating Your UserName");
for(int j=0;j<=35;j++)
{
try{
Thread.sleep(100);
}
catch(InterruptedException ex)
{
//do nothing
}
System.out.print("*");
}
}
Can Somebody Help Me Please....
You can just:
String username = FName.substring(0,3) + LName.substring(LName.length() - 3, LName.length());
You should probably check that FName and LName have a minimum length of 3 characters, or you will get an exception

Categories