I've trying to use tokenizer to set name and surname - java

public static Player newPlayer(Integer playerNum){
Player player = new Player();
System.out.println("Player " + (playerNum+1) + " registration");
try {
String fullname = null;
StringTokenizer lineTokens = new StringTokenizer(fullname);
System.out.print("Name: ");
String name = input.readLine();
String surname = input.readLine();
fullname = input.readLine();
player.setName(name + surname);
while (lineTokens.hasMoreTokens()) {
if ( lineTokens.countTokens() >= 0 ) {
name = lineTokens.nextToken();
surname = lineTokens.nextToken();
fullname = (name+" "+surname);
} else {
String checkSpace = lineTokens.nextToken();
for (int i = 0; i < checkSpace.length(); i++) {
if ( checkSpace.charAt(i) == ' ' ) {
break;
}
}
}
}
}catch (IOException e){}
}
I need to set a name and a surname using Tokenizer it is crashing.
P.S I want learn how to use it instead of the split

I didn't understand exactly what you wanted to do, below is a short script to read first and last name from the user, using StringTokenizer
public static void main(String[] args) {
System.out.println("Enter name: <firstName> <lastName>");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
StringTokenizer tokenizer = new StringTokenizer(input, " ");
String firstName = "";
String lastName = "";
if (tokenizer.countTokens() >= 2){
firstName = tokenizer.nextToken();
lastName = tokenizer.nextToken();
}
System.out.println("first name is " + firstName);
System.out.println("last name is " + lastName);
}

Related

How to create a Java name generator using for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to create a name generator that uses for loops and if/else selection to generate the name. Input will be stored in separate char[] for each of the four words you enter.
I am currently at a lost, so far I have only coded the below but it does not use for loops or arrays.
import java.util.Scanner;
public class NameGenerator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.printf("Enter your first name: ");
String firstname = input.nextLine();
firstname = firstname.substring(0,3);
System.out.printf("Enter your last name: ");
String lastname = input.nextLine();
lastname = lastname.substring(0,2);
System.out.printf("Enter your mother's maiden name: ");
String mothersname = input.nextLine();
mothersname = mothersname.substring(0,2);
System.out.printf("Enter the name of the city in which you were born: ");
String cityname = input.nextLine();
cityname = cityname.substring(0,3);
String GenFirstName = (firstname + lastname);
String GenLastName = (mothersname + cityname);
System.out.println("May the force be with you, " + GenFirstName + " " + GenLastName );
}
}
I'm not too sure what it is you are really after, but this is what I came up with.
import java.util.Scanner;
public class NameGenerator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.printf("Enter your first name: ");
char[] firstname;
firstname = input.next().toCharArray();
System.out.printf("Enter your last name: ");
char[] lastname;
lastname = input.next().toCharArray();
System.out.printf("Enter your mother's maiden name: ");
char[] mothersname;
mothersname = input.next().toCharArray();
System.out.printf("Enter the name of the city in which you were born: ");
char[] cityname;
cityname = input.next().toCharArray();
String GenFirstName = "";
String GenLastName = "";
for(int count = 0; count <= 3; count++){
GenFirstName += firstname[count];
GenLastName += mothersname[count];
}
for(int count = 0; count <= 3; count++){
GenFirstName += lastname[count];
GenLastName += cityname[count];
}
System.out.println("May the force be with you, " + GenFirstName + " " + GenLastName );
}
}
UPDATE
Here is the command line arguments version.
public class NameGenerator
{
public static void main(String[] args)
{
char[] firstname;
firstname = args[0].toCharArray();
char[] lastname;
lastname = args[1].toCharArray();
char[] mothersname;
mothersname = args[2].toCharArray();
char[] cityname;
cityname = args[3].toCharArray();
String GenFirstName = "";
String GenLastName = "";
for(int count = 0; count <= 3; count++){
GenFirstName += firstname[count];
GenLastName += mothersname[count];
}
for(int count = 0; count <= 3; count++){
GenFirstName += lastname[count];
GenLastName += cityname[count];
}
System.out.println("May the force be with you, " + GenFirstName + " " + GenLastName );
}
}

displaying multiple array variables

This program gets user input for 2 teams and 2 results, separates them with the " : " delimiter, then stores them in the array, when the user enters the word "stop" it stops asking for user input and is meant to display the results and stats of the match (which is not yet added into the code). the problem I'm having is if I type more than one line of match results then type 'stop', it only displays the first line of user input back to the console and not any of the others? input example: "Chelsea : Arsenal : 2 : 1".
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
if ("stop".equals(line)) {
System.out.println(Arrays.toString(results));
return; // exit
}
The reason that it outputs the first results you entered is because results is assigned to s.split(" : "). s never changes in the first iteration of the outer for loop, so s.split(" : ") never changes. Your results always holds the first match results!
You have written your code very wrongly.
First, why do you have a while loop inside a for loop? The for loop is redundant.
Second, you can't use arrays for this. Try an ArrayList. Arrays don't have the ability to change its size dynamically.
Third, I recommend you to create a class for this, to represent a MatchResult.
class MatchResult {
private String homeTeam;
private String awayTeam;
private int homeScore;
private int awayScore;
public String getHomeTeam() {
return homeTeam;
}
public String getAwayTeam() {
return awayTeam;
}
public int getHomeScore() {
return homeScore;
}
public int getAwayScore() {
return awayScore;
}
public MatchResult(String homeTeam, String awayTeam, int homeScore, int awayScore) {
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.homeScore = homeScore;
this.awayScore = awayScore;
}
#Override
public String toString() {
return "MatchResult{" +
"homeTeam='" + homeTeam + '\'' +
", awayTeam='" + awayTeam + '\'' +
", homeScore=" + homeScore +
", awayScore=" + awayScore +
'}';
}
}
Then, you can create an ArrayList<MatchResult> that stores the user input.
Scanner sc = new Scanner(System.in);
String hometeam;
String awayteam;
int homescore;
int awayscore;
ArrayList<MatchResult> list = new ArrayList<>();
System.out.println("please enter match results:");
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(list.toArray()));
return; // exit
}
String results[] = line.split(" : "); // parse strings in between
hometeam = results[0];
awayteam = results[1];
homescore = Integer.valueOf(results[2]);
awayscore = Integer.valueOf(results[3]);
list.add(new MatchResult(hometeam, awayteam, homescore, awayscore));
}
try just adding another array
string[] matches = new string[]{};
then input your values into the array. I am using b since that is the int variable in your loop. I also put in + " : "
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
then change the print to
System.out.println(Arrays.toString(matches));
i think this should work, but I wasn't able to test it.
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
string[] matches = new string[]{};
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(matches));
return; // exit
}
Here is a simple loop to grab all data from user until "stop" is entered and display the output of the input
Scanner sc = new Scanner(System.in);
ArrayList<String[]> stats = new ArrayList<>(); //initialize a container to hold all the stats
System.out.println("please enter match results:");
while(sc.hasNextLine())
{
String input = sc.nextLine();
String[] results = input.split(" : ");
if(results.length == 4)
{
stats.add(results);
}
else if(input.equals("stop"))
break;
else
System.out.println("Error reading input");
}//end of while
for(int i = 0; i < stats.size(); i++)
{
try{
System.out.println(stats.get(i)[0] + " vs " + stats.get(i)[1] + " : " +
Integer.valueOf(stats.get(i)[2]) + " - " + Integer.valueOf(stats.get(i)[3]));
}catch (Exception e) {
//do nothing with any invalid input
}
}
Output
please enter match results:
r : b : 5 : 4
r : c : 7 : 10
j : g : 3 : 9
stop
r vs b : 5 - 4
r vs c : 7 - 10
j vs g : 3 - 9

Modify whole line of data in txt file using java

So I have this console app with line of Java code intended to modify the Book data inside txt file.
User will prompted to enter the book ID of the book that is going to be modified and then just basically enter all the book details.
public void UpdatingBookData()
{
int bid; String booktitle; String author; String desc; String Alley;
System.out.println("Enter Book ID: ");
bid = sc.nextInt();
System.out.println("Enter Book Title: ");
booktitle = sc.next();
System.out.println("Enter Book Author: ");
author = sc.next();
System.out.println("Enter Book Description: ");
desc = sc.next();
System.out.println("Enter Book Alley: ");
Alley = sc.next();
UpdateBook(bid, booktitle, author, desc, Alley);
}
public static void UpdateBook(int bid, String booktitle, String author, String desc, String Alley)
{
ArrayList<String> TempArr = new ArrayList<>();
try
{
File f = new File("book.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
String[] lineArr;
line = br.readLine();
while(line != null)
{
lineArr = line.split(" ");
if(lineArr[0].equals(bid))
{
TempArr.add(
bid + " " +
booktitle + " " +
author + " " +
desc + " " +
Alley );
}
else
{
TempArr.add(line);
}
}
fr.close();
}
catch(IOException ex)
{
System.out.println(ex);
}
try
{
FileWriter fw = new FileWriter("book.txt");
PrintWriter pw = new PrintWriter(fw);
for(String str : TempArr)
{
pw.println(str);
}
pw.close();
}
catch(IOException ex)
{
System.out.println(ex);
}
}
but when I run it, I keep receiving this error
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at lmsconsole.Administrator.UpdateBook(Administrator.java:438)
at lmsconsole.Administrator.UpdatingBookData(Administrator.java:409)
at lmsconsole.Administrator.adminPanel(Administrator.java:52)
at lmsconsole.MainMenu.loginAdmin(MainMenu.java:68)
at lmsconsole.MainMenu.MainPanel(MainMenu.java:45)
at lmsconsole.LMSConsole.main(LMSConsole.java:24)
Is it because of the ArrayList or what? Thanks in advance!

Java substring to split up name

I am asked to take input from a user, their first and last name in one string.
Then output their name, with their last name first then their first name.
I have finished everything but the part I am stuck on is how to show their first name then their last name, please help.
This is my code so far as requested
package chapter2Codes;
import java.util.Scanner;
public class StPrac1 {
public static void main(String[] args) {
String name;
System.out.println("Please your full name");
Scanner kbd = new Scanner( System.in );
name = kbd.nextLine();
System.out.print(name.substring(5,8) + (", ") + name.substring(0,));
}
}
If Firstname and Lastname are seperated by white-space then try this
var fullname = "Firstname Surname";
var fname = fullname.Split(" ")[0];
var sname = fullname.Split(" ")[1];
string output = sname + ", " + fname;
OR if you want to Avoid middle name
string fullName = "Firstname MidName LastName";
string[] names = fullName.Split(' ');
string fname = names.First();
string lname = names.Last();
string output = lname + ", " + fname;
OR use your delimeter in .Split('addyourdelimeterhere')
AS per your Code
public class StPrac1 {
public static void main(String[] args) {
String name;
System.out.println("Please your full name");
Scanner kbd = new Scanner( System.in );
name = kbd.nextLine();
string fname = name.Split(" ")[0];
string sname = name.Split(" ")[1];
string output = sname + ", " + fname;
System.out.print(output);
}
}
This is just an example not a perfect solution, It will be easy to help you if you can Post more detail

multiple prints for each input. Why?

Each time I run this code it gets to where it asks for student id and it prints out the student id part and the homework part. Why? I am trying to do get a string for name, id, homework, lab, exam, discussion, and project then in another class I am splitting the homework, lab, and exam strings into arrays then parsing those arrays into doubles. After I parse them I total them in another method and add the totals with project and discussion to get a total score.
import java.util.Scanner;
import java.io.*;
public class GradeApplication_Kurth {
public static void main(String[] args) throws IOException
{
Student_Kurth one;
int choice;
boolean test = true;
do
{
Scanner keyboard = new Scanner(System.in);
PrintWriter outputFile = new PrintWriter("gradeReport.txt");
System.out.println("Please select an option: \n1. Single Student Grading \n2. Class Grades \n3. Exit");
choice = keyboard.nextInt();
switch (choice)
{
case 1 :
System.out.println("Please enter your Student name: ");
String name = keyboard.next();
System.out.println("Please enter you Student ID: ");
String id = keyboard.nextLine();
System.out.println("Please enter the 10 homework grades seperated by a space: ");
String homework = keyboard.next();
System.out.println("Please enter the 6 lab grades seperated by a space: ");
String lab = keyboard.nextLine();
System.out.println("Please enter the 3 exam grades seperated by a space: ");
String exam = keyboard.nextLine();
System.out.println("Please enter the discussion grade: ");
double discussion = keyboard.nextDouble();
System.out.println("Please enter the project grade: ");
double project = keyboard.nextDouble();
one = new Student_Kurth(name, id, homework, lab, exam, discussion, project);
outputFile.println(one.toFile());
System.out.println(one);
break;
case 2 :
File myFile = new File("gradeReport.txt");
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println("\n" + str);
}
break;
case 3 :
test = false;
keyboard.close();
outputFile.close();
System.exit(0);
}
} while (test = true);
}
}
second class
public class Student_Kurth
{
public String homework;
public String name;
public String id;
public String lab;
public String exam;
public double project;
public double discussion;
public double[] hw = new double[10];
public double[] lb = new double[6];
public double[] ex = new double[3];
public final double MAX = 680;
public double percentage;
public String letterGrade;
public Student_Kurth()
{
homework = null;
name = null;
id = null;
lab = null;
exam = null;
project = 0;
discussion = 0;
}
public Student_Kurth(String homework, String name, String id, String lab, String exam, double project, double discussion)
{
this.homework = homework;
this.name = name;
this.id = id;
this.lab = lab;
this.exam = exam;
this.project = project;
this.discussion = discussion;
}
public void Homework(String homework)
{
String delims = " ";
String[] tokens = this.homework.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
hw[i] = Double.parseDouble(tokens[i]);
}
}
public void Lab(String lab)
{
String delims = " ";
String[] tokens = this.lab.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
lb[i] = Double.parseDouble(tokens[i]);
}
}
public void Exam(String exam)
{
String delims = " ";
String[] tokens = this.exam.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
ex[i] = Double.parseDouble(tokens[i]);
}
}
public double getHomeworkTotal(double[] hw)
{
double hwTotal = 0;
for(int i = 0; i < hw.length; i++)
{
hwTotal += hw[i];
}
return hwTotal;
}
public double getLabTotal(double[] lb)
{
double lbTotal = 0;
for(int i = 0; i < lb.length; i++)
{
lbTotal += lb[i];
}
return lbTotal;
}
public double getExamTotal(double[] ex)
{
double exTotal = 0;
for(int i = 0; i < ex.length; i++)
{
exTotal += ex[i];
}
return exTotal;
}
public double getTotalScores(double getExamTotal, double getLabTotal, double getHomeworkTotal)
{
return getExamTotal + getLabTotal + getHomeworkTotal + this.project + this.discussion;
}
public double getPercentage(double getTotalScores)
{
return 100 * getTotalScores / MAX;
}
public String getLetterGrade(double getPercentage)
{
if(getPercentage > 60)
{
if(getPercentage > 70)
{
if(getPercentage > 80)
{
if(getPercentage > 90)
{
return "A";
}
else
{
return "B";
}
}
else
{
return "C";
}
}
else
{
return "D";
}
}
else
{
return "F";
}
}
public void getLetter(String getLetterGrade)
{
letterGrade = getLetterGrade;
}
public void getPercent(double getPercentage)
{
percentage = getPercentage;
}
public String toFile()
{
String str;
str = " " + name + " - " + id + " - " + percentage + " - " + letterGrade;
return str;
}
public String toString()
{
String str;
str = "Student name: " + name + "\nStudent ID: " + id + "\nTotal Score: " + getTotalScores(getExamTotal(ex), getLabTotal(lb), getHomeworkTotal(hw)) +
"\nMax Scores: " + MAX + "Percentage: " + percentage + "Grade: " + letterGrade;
return str;
}
}
At the end of the switch, you have
while ( test = true)
You probably want to change that to
while ( test == true)
Also, take these lines out of the loop:
Scanner keyboard = new Scanner(System.in);
PrintWriter outputFile = new PrintWriter("gradeReport.txt");
In addition to Ermir's answer, this line won't capture all the grades:
System.out.println("Please enter the 10 homework grades seperated by a space: ");
String homework = keyboard.next();
Keyboard.next only reads until the next delimiter token, so if you want to capture 10 grades separated by spaces you need capture the whole line, like:
System.out.println("Please enter the 10 homework grades separated by a space: ");
String homework = keyboard.nextLine();

Categories