I'm struggling with this code. Return of this one is eg: "JS John Smith" but when I try to put two names plus surname all I get is a mess. I wish to get when I type eg: "John William Smith" something like this: "JW Smith", anybody know hot to do it?
import java.io.*;
import java.io.BufferedReader;
public class ex54 {
public static void main(String[] args) {
System.out.print("Enter your name: ");
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
String fullName = null;
try{
fullName = br.readLine();
} catch (IOException ioe) {
System.out.println("Error");
System.exit(1);
}
int spacePos = fullName.indexOf(" ");
// String firstName = fullName.substring(0, spacePos);
// String secondName = fullName.substring(1, spacePos);
String firstInitial = fullName.substring(0, 1);
String secondInitial = fullName.substring(spacePos+1, spacePos+2);
String userName = (firstInitial + secondInitial + " ").concat(fullName);
System.out.println("Hello, your user name is: " + userName);
}
}
}
You can split the name, assuming you are given a three-name string:
String[] names = fullname.split(" ");
System.out.println("" + names[0].charAt(0) + names[1].charAt(0) + " " + names[2]);
int spacePos = -1;
System.out.print("Hello, your user name is:");
do {
System.out.print(" "+fullName.substring(spacePos+1, spacePos+2));
fullName = fullName.substring(spacePos+1);
spacePos = fullName.indexOf(" ");
}while(spacePos != -1);
System.out.println("\b"+fullName);
Just for kicks, here is an implementation using regular expressions:
private static String firstNamesToInitials(String name) {
StringBuilder buf = new StringBuilder();
Matcher m = Pattern.compile("\\b([A-Z])[A-Za-z]*\\b").matcher(name);
String lastName = null;
while (m.find()) {
buf.append(m.group(1));
lastName = m.group();
}
if (buf.length() <= 1)
return lastName;
buf.setCharAt(buf.length() - 1, ' ');
return buf.append(lastName).toString();
}
Test
System.out.println(firstNamesToInitials("Cher"));
System.out.println(firstNamesToInitials("John Smith"));
System.out.println(firstNamesToInitials("John William Smith"));
System.out.println(firstNamesToInitials("Charles Philip Arthur George"));
System.out.println(firstNamesToInitials("Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso"));
Output
Cher
J Smith
JW Smith
CPA George
PDFPJNRCTR Picasso
Related
Okay so this code asks the user to enter a name, year, and gender, and displays the ranking of the name for the selected year. It reads data from the url and places it into a map for each year. These maps are then placed into an array, and finally the rank is displayed to the user. My program never finishes running after entering the while loop. Here is the code:
public static void main(String[] args) throws MalformedURLException, IOException {
Scanner input = new Scanner(System.in);
Map[] boyArray = new Map[10];
Map[] girlArray = new Map[10];
System.out.print("Enter year (between 2001 and 2010): ");
String year = input.nextLine();
System.out.print("Enter gender (M or F): ");
String gender = input.nextLine();
System.out.print("Enter name: ");
String name = input.nextLine();
for (int i = 0; i < 10; i++) {
Map<String, String> boys = new HashMap<>();
Map<String, String> girls = new HashMap<>();
try {
java.net.URL url = new java.net.URL("http://www.cs.armstrong.edu/liang/data/babynamesranking"+ year + ".txt");
Scanner urlInput = new Scanner(url.openStream());
while (urlInput.hasNext()) {
String rank = input.next();
boys.put(urlInput.next(), rank);
urlInput.next();
girls.put(input.next(), rank);
urlInput.next();
}
}
catch (IOException ex) {
}
boyArray[i] = boys;
girlArray[i] = girls;
}
if (gender.charAt(0) == 'M') {
System.out.println("The name " + name + " was ranked " + boyArray[Integer.parseInt(year) - 2001].get(name) + " in " + year);
} else {
System.out.println("The name " + name + " was ranked " + girlArray[Integer.parseInt(year) - 2001].get(name) + " in " + year);
}
}
}
It looks like, as #uthark has already noted, your program is waiting for input because in your while loop you're waiting for input from System.in with the line String rank = input.next(); (and the line girls.put(input.next(), rank);). You probably meant to write String rank = urlInput.next(); and girls.put(urlInput.next(), rank); instead so that the rank and girl name come from http://www.cs.armstrong.edu/liang/data/babynamesrankingYYYY.txt.
Sorry if there are noob mistakes. am noob.
package lab7fall2015;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Lab7{
public static String computeMessage(double inputGpa){
String feedback = "";
if(inputGpa >= 3.8){
feedback = "Excellent!";
return feedback;
}
else if(inputGpa >= 3.4 && inputGpa < 3.8){
feedback = "Very Good!";
return feedback;
}
else if(inputGpa >= 2.8 && inputGpa < 3.4){
feedback = "Okay";
return feedback;
}
else if(inputGpa < 2.8){
feedback = "see your advisor";
return feedback;
}
else{
feedback = "error";
return feedback;
}
}
public static void main(String[] args) throws FileNotFoundException{
String myReaderRef = null;
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Lab 7 Josh Peel");
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"TXT - text files", "txt");
chooser.setFileFilter(filter);
chooser.setCurrentDirectory(new File("C:\\Java"));
int picked = chooser.showOpenDialog(null);
if (picked == JFileChooser.APPROVE_OPTION){ //user picked something
myReaderRef = chooser.getSelectedFile().getAbsolutePath();
}
else{
System.exit(0);
}
FileReader myReader = new FileReader(myReaderRef);
Scanner input = new Scanner(myReader);
String output = "";
double gpaSum = 0.00;
while(input.hasNextLine()){
String readLastName = input.next();
String readFirstName = input.next();
String readMiddleName = input.next();
Double readGpa = input.nextDouble();
Student aStudent = new Student(readLastName, readFirstName, readMiddleName, readGpa);
String message = computeMessage(aStudent.getGPA());
gpaSum += aStudent.getGPA();
output += aStudent + " " + message + "\n";
}
input.close();
String blank = " ";
Student actor = new Student(blank, blank, blank, 0.0);
double gpaAvg = gpaSum / actor.getStudentCount();
output += "\n\nInput file read: " + myReaderRef + "\n";
output += "That file contains data on " + actor.getStudentCount() + " students\n";
output += "Average of all GPA's in that file is: " + gpaAvg;
JOptionPane.showMessageDialog(null, output, "Lab 7 by Josh Peel",
JOptionPane.INFORMATION_MESSAGE);
}
}
class Name{
private String lastName, firstName, middleName;
public Name(String studentLastName, String studentFirstName, String studentMiddleName){
lastName = studentLastName;
firstName = studentFirstName;
middleName = studentMiddleName;
}
public String toString(){
String studentName = firstName + " " + middleName + " " + lastName + " ";
return studentName;
}
}
class Student{
private static Name name;
private double gpa = 0.00;
private int numberOfStudents = 0;
public Student(String newLastName, String newFirstName,
String newMiddleName, double newGpa){
name = new Name(newLastName, newFirstName, newMiddleName);
gpa = newGpa;
numberOfStudents++;
}
public double getGPA(){
return gpa;
}
public String toString(){
return name + "(" + gpa + ")";
}
public int getStudentCount(){
return numberOfStudents - 1;
}
}
this returns a runtime error that reads as follows:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at lab7fall2015.Lab7.main(Lab7.java:64)
input file reads:
Smith Bob D. 3.14
Jones Mary K. 3.92
Wilson Donald J. 2.91
Martin Mark P. 3.44
Miller Marsha H. 3.66
Dummy Iam A. 1.11
Brilliant Johnny B. 4.0
i have no error messages in the code but i am new to using scanners and assigning variables from a text document. it fails after I use the JFilechooser to select my file.
for debugging purposes i added "System.out.print(readLastName)" and it output all of the last names. so it DOES make it through the entire document line by line...
I have an assignment where the user is asked for baby name using a scanner. Then it reads through files names.txt and meanings.txt and returns the popularity of the name for each decade ranging from 1890 - 2010 then it prints out the meaning. Some names have multiple meanings and some are used in both genders. The assignment states to print only the first line where the name is found. I am having trouble only returning the first line in which the name is found. PLEASE HELP ME!
import java.io.*;
import java.util.*;
public class BabyNames4 {
public static void main(String[] args) throws FileNotFoundException {
printIntro();
Scanner console = new Scanner(System.in);
System.out.print("Name: ");
String searchWord = console.next();
Scanner fileScan = new Scanner(new File("names.txt"));
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan);
}
}
Scanner fileScan2 = new Scanner(new File("meanings.txt"));
String dataLine2 = find(searchWord, fileScan2);
if (dataLine2.length() > 0) {
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
}
}
public static void printIntro() {
System.out.println("This program allows you to search through the");
System.out.println("dada from the Social Security Administration");
System.out.println("to see how popular a particular name has been");
System.out.println("since 1890");
System.out.println();
}
public static String find(String searchWord, Scanner fileScan) {
while (fileScan.hasNextLine()) {
String dataLine = fileScan.nextLine();
String dataLineLC = dataLine.toLowerCase();
if (dataLineLC.contains(searchWord.toLowerCase())) {
return dataLine;
//} else { runs a continuous loop
//System.out.println(search" not found.");
}
}
return "";
}
public static void printName(String dataLine) {
Scanner lineScan = new Scanner(dataLine);
String name = lineScan.next();
String gender = lineScan.next();
String rank = "";
while (lineScan.hasNext()) {
rank += lineScan.next() + " ";
}
System.out.println(name + (" ") + gender + (" ") + rank);
}
public static void printMeaning(String dataLine2) {
Scanner lineScan2 = new Scanner(dataLine2);
String name2 = lineScan2.next();
String gender2 = lineScan2.next();
String language = lineScan2.next();
String meaning = "";
while (lineScan2.hasNext()) {
meaning += lineScan2.next() + " ";
}
System.out.println(name2 + (" ") + gender2 + (" ") + language + (" ") + meaning);
}
}
It looks like sushain hit it with his comment.
The loop:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
could be changed to:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
break;
}
This way you do not find the second definition and do not print it.
In this loop, you don't need to find the next line, correct?
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan); // remove this line
}
}
If you remove the next find to dataLine and remove the while blocks in both instances where you search the file, you won't need a break, and you'll only end up printing one instance.
Do this:
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
printName(dataLine);
}
package michael.week.pkg5;
class Employee {
String Fname ;
String Lname;
String PhoneNum;
String Address;
void setFirst(String First){
Fname = First ;
}
void setlast(String Last){
Lname = Last ;
}
void setAddress (String address){
Address = address ;
}
void setPhone (String Phone){
PhoneNum = Phone ;
}
void display (){
System.out.println ("the Fist name is :"+ Fname + " , the last name is : " + Lname + " ,the address is : "+ Address+ " ,the phone is : "+ PhoneNum);
}
}
package michael.week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MichaelWeek5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Stck {
Employee stck [] = new Employee[10];
int x ;
void stck (){
x= -1 ;
}
Employee push (Employee item){
if (x == 9){
System.out.println ("Stack is full");
}else stck[++x] = item ;
return stck[x];
}
Employee pop (){
if (x <0){
System.out.println (" Stack underflow");
return stck [x];
}else
return stck[x++];
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
String info2 = null ;
Stck obj = new Stck();
Employee obj2 = new Employee ();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.stck ();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
System.out.println ("please enter Employee last name name :");
info = br.readLine();
System.out.println ("please enter Employee address :");
info = br.readLine();
System.out.println ("please enter Employee phone number :");
info = br.readLine();
}
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}
Greetings,
i am new to java and i am working on this program....... i need to know how can i push the data to the stck ?
note : the push's parameter is type employee, and Employee contains First , Last, Phone , and address. how i can push each of them ?
here is what i did , and my instructor refused it
package week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Week5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Employee {
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
void increment(){
x++;
}
void PushFirst(String First){
Fname[x] = First ;
}
void Pushlast(String Last){
Lname [x] = Last ;
}
void PushPhone (String Phone){
PhoneNum [x] = Phone ;
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
}
void PushAddress (String address){
Address [x] = address ;
}
void pop (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
x--;
}
}
void display (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
for (int q = 0 ; q <=x ; q++){
System.out.println ((q+1)+"- "+"the First name is :"+ Fname [q]+ " , the last name is : " + Lname [q] + " ,the address is : "+ Address[q] + " ,the phone is : "+ PhoneNum[q]);
}
}
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
Employee obj = new Employee();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter display to display all employees list");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.increment();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
obj.PushFirst(info);
System.out.println ("please enter Employee last name name :");
info = br.readLine();
obj.Pushlast(info);
System.out.println ("please enter Employee address :");
info = br.readLine();
obj.PushAddress(info);
System.out.println ("please enter Employee phone number :");
info = br.readLine();
obj.PushPhone(info);}
} else if(choice.equals("display")){
obj.display();
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}
You would need to create a stack of employees and then you can push the whole employee object on to the stack.
import java.util.Stack;
...
Employee emp = new Employee();
Stack<Employee> stack = new Stack<Employee>();
stack.push(emp);
after creating an object to the class say (here stck) which will hold the data by calling method ex shown below
class std
{
int id;
string name;
public:
void set_id(int i)
{
id=i;
}
void set_name(string n)
{
name = n;
}
void disp()
{
system.out.println("name"+name+" and id = "+id);
}
};
main()
{
std s = new std();
s.set_id(1);
s.set_name("sunmoon");
s.disp();
}
so here you can observe that s is considered as stack and we pushed one person details as like you can create array of object and push n number of person details.
You have several issues in how you've modeled the data.
Issue #1 (The biggest issue of all):
An Employee should not have any internal representation of the stack. Think objects in the real world. In your example, each Employee should have:
a first name
last name
address
phone number
So the member fields :
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
do not belong. This leads us to...
Issue #2 : The way you've modeled the Stack only allows for a fixed number of entries - 10 in your case). This is not how a stack should work. Read up on what a Stack is if you are uncertain. You can model a Stack in Java using a LinkedList - or use the built in Stack that Java provides. If you decide to create your own version, the important operations that need to be created are:
push
pop
isEmpty
My advice is to start by modelling the employee and pratice by pushing and popping them off of a built in Stack from the JDK until you really understand the operations before you try to create your own.
I created a program which will parse the firstName, middleName and lastName. Here is the program and output. This program can definitely be improved and need some input on reducing my cumbersome ugly code and replace it with a better one. Any suggestions or example ?
public class Test {
public static void main(String[] args) {
String fullName = "John King IV. Cena";
String[] tokens = fullName.split(" ");
String firstName = "";
String middleName = "";
String lastName = "";
if(tokens.length > 0) {
firstName = tokens[0];
middleName = tokens.length > 2 ? getMiddleName(tokens) : "";
lastName = tokens[tokens.length -1];
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
public static String getMiddleName(String[] middleName){
StringBuilder builder = new StringBuilder();
for (int i = 1; i < middleName.length-1; i++) {
builder.append(middleName[i] + " ");
}
return builder.toString();
}
}
John
King IV.
Cena
This code does the same, but doesn't keep a trailing space in the middle name. This is one of several possible cleaner implementations.
public class Test {
public static void main(String[] args) {
String name = "John King IV. Cena";
int start = name.indexOf(' ');
int end = name.lastIndexOf(' ');
String firstName = "";
String middleName = "";
String lastName = "";
if (start >= 0) {
firstName = name.substring(0, start);
if (end > start)
middleName = name.substring(start + 1, end);
lastName = name.substring(end + 1, name.length());
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
}
As the guys said, next time go directly to https://codereview.stackexchange.com/
The algorithm will fail if the persons last name has more than one word, like Abraham Van Helsing. Van is not a middle name but part of the last name.
Obviously, there is no algorithm to clearly distinguish between middle name and last name in general. We always have to guess and we can only try to improve the probability that the guess is correct, maybe be checking middle name parts against word or filter lists.
You could also use a StringTokenizer for this:
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
String fullName = "John King IV. Cena";
StringTokenizer stok = new StringTokenizer(fullName);
String firstName = stok.nextToken();
StringBuilder middleName = new StringBuilder();
String lastName = stok.nextToken();
while (stok.hasMoreTokens())
{
middleName.append(lastName + " ");
lastName = stok.nextToken();
}
System.out.println(firstName);
System.out.println(middleName.toString().trim());
System.out.println(lastName);
}
}
Update the code to handle where there is no last name i.e. user enters only the first name like "Mark"
if(tokens.length > 0) {
firstName = tokens[0];
middleName = tokens.length > 2 ? getMiddleName(tokens) : "";
if(tokens.length > 1){
lastName = tokens[tokens.length -1];
}
}