Having an issue with formatting a String input - java

I'm trying to get the input that the user enters to go to lower-case and then put the first character in the input to upper-case. For example, If I enter aRseNAL for my first input, I want to format the input so that it will put "Arsenal" into the data.txt file, I'm also wondering if there's a way to put each first character to upper-case if there's more than one word for a team ie. mAN uNiTeD formatted to Man United to be written to the file.
The code I have below is what i tried and I cannot get it to work. Any advice or help would be appreciated.
import java.io.*;
import javax.swing.*;
public class write
{
public static void main(String[] args) throws IOException
{
FileWriter aFileWriter = new FileWriter("data.txt");
PrintWriter out = new PrintWriter(aFileWriter);
String team = "";
for(int i = 1; i <= 5; i++)
{
boolean isTeam = true;
while(isTeam)
{
team = JOptionPane.showInputDialog(null, "Enter a team: ");
if(team == null || team.equals(""))
JOptionPane.showMessageDialog(null, "Please enter a team.");
else
isTeam = false;
}
team.toLowerCase(); //Put everything to lower-case.
team.substring(0,1).toUpperCase(); //Put the first character to upper-case.
out.println(i + "," + team);
}
out.close();
aFileWriter.close();
}
}

In Java, strings are immutable (cannot be changed) so methods like substring and toLowerCase generate new strings - they don't modify your existing string.
So rather than:
team.toLowerCase();
team.substring(0,1).toUpperCase();
out.println(team);
You'd need something like:
String first = team.substring(0,1).toUpperCase();
String rest = team.substring(1,team.length()).toLowerCase();
out.println(first + rest);

Similar as #DNA suggested but that will throw Exception if String length is 1. So added a check for same.
String output = team.substring(0,1).toUpperCase();
// if team length is >1 then only put 2nd part
if (team.length()>1) {
output = output+ team.substring(1,team.length()).toLowerCase();
}
out.println(i + "," + output);

Related

How to splitting different special characters in Java with using if contains?

I have “-“ characters in my strings as below.
I am using if contains “-“ and splitting correctly. But some string values are also “-“ characters in different indexes.
I tried to use 2nd if contains “.-“ cannot solve the issue as well.
So have can I get correct outputs without “-“ characters perfectly?
13-adana-demirspor -> has 2 “-“ characters.
15-y.-malatyaspor -> has “-“ characters too.
1st and 2nd strings makes problem for splitting.
And others has only one “-“ character and no issue.
My Code is:
final String [] URL = {
"13-adana-demirspor",
"14-fenerbahce",
"15-y.-malatyaspor",
"16-trabzonspor",
"17-sivasspor",
"18-konyaspor",
"19-giresunspor",
"20-galatasaray"
};
for(int i=0; i<URL.length; i++)
String team;
if (URL[i].contains("-")) {
String[] divide = URL[i].split("-");
team = divide[1];
System.out.println(" " + team.toUpperCase());
} else if (URL[i].contains(".-")){
String[] divide = URL[i].split(".-");
team = divide[2];
System.out.println(" " + team.toUpperCase());
}else {
team = null;
}
My Output is:
ADANA ** missing second word
FENERBAHCE
Y. ** missing second word
TRABZONSPOR
SIVASSPOR
KONYASPOR
GIRESUNSPOR
GALATASARAY
Thanks for your help.
it looks like you just want to split on the first occurence. for this you can use the second parameter of split and set that to 2. So like
if (URL[i].contains("-")) {
String[] divide = URL[i].split("-", 2);
team = divide[1];
System.out.println(" " + team.toUpperCase());
} else {
team = null;
}
to get the last part instead you could do
if (URL[i].contains("-")) {
String[] divide = URL[i].split("-");
team = divide[divide.length - 1];
System.out.println(" " + team.toUpperCase());
} else {
team = null;
}

How to make it so the user can replace a sentence they typed can be replaced in Java

So I am trying to make the program ask the user the following and get the following answer:
For example:
Type a 2nd Sentence Below:
This is a book (user inputs this)
Choose what string of characters do you want to replace:
book (user inputs this)
Choose what new string will be used in the replacement:
car (user inputs this)
The text after the replacement is: This is a car.
import java.util.*;
import java.util.Scanner;
public class StringManipulation {
public static void main(String[]args) {
/*This is where the user can type a second sentence*/
System.out.println("Type a 2nd Sentence Below:");
Scanner sd = new Scanner(System.in);
String typingtwo = sd.nextLine();
String sending;
/*Here the program will tell the user a message*/
System.out.println("This is your sentence in capital letters:");
sending = typingtwo.toUpperCase();
System.out.println(sending);
/*Here the program will tell the user another message*/
System.out.println("This is your sentence in lower letters:");
sending = typingtwo.toLowerCase();
System.out.println(sending);
System.out.print("Your Token Count:");
int FrequencyTwo = new StringTokenizer(sending, " ").countTokens();
System.out.println(FrequencyTwo);
String charactertwo = new String(typingtwo);
System.out.print("Your Character Length:");
System.out.println(charactertwo.length());
String repWords;
String newWord;
String nwords;
String twords;
System.out.println("Choose what string of characters do you want to
replace");
repWords = sd.next();
System.out.println("Choose what new string will be used in the replacement");
nwords = sc.next();
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
}
}
I have tried everything but for some reason I keep getting the word that they chose at the end only. Pleas help!
try using Scanner.nextLine instead of Scanner.next
refer to the Java API documentation to understand the difference between the two
Here is another problem:
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
You are printing nwords instead of twords.
Two errors i could see.
nwords = sc.next(); here it should give compilation error as scanner instance name is sd.
You are trying to print nwords at the end. it should be "twords".

read from file with space delimiter

hello guys I need help with reading from file with space delimiter. The problem is for example i got a text file the format as follows: id name
example:
1 my name
how can I get the string together (my name) as the code I have tried would only get me (my). I can't change the delimiter from the text file
while(myScanner.hasNextLine())
{
String readLine = myScanner.nextLine();
String readData[] = readLine.split(" ");
String index = readData[0];
String name = readData[1];
}
myScanner.close();
If it's always just going to be id space name with nothing coming after it, then you can do this:
String readLine = myScanner.nextLine();
int split = readLine.indexOf(" ");
String index = readLine.substring(0, split);
String name = readLine.substring(split + 1);
This will only work if those are the only two fields though. If you add more fields after that there's no (general) way to determine where item two ends and item three begins.
Another way is to use next, nextInt, etc, to read out exactly what you want:
String index = myScanner.next(); //Or int index = myScanner.nextInt();
String name = myScanner.nextLine().substring(1); //drop the leading space
That's a bit more flexible of an approach, which might be better suited to your needs.
Use following code.
while(myScanner.hasNextLine())
{
String readLine = myScanner.nextLine();
if(null != readLine && readLine.length()>0) {
String index = readLine.substring(0, id.indexOf(" "));
String name = readLine.substring(id.indexOf(" ") + 1);
}
}
myScanner.close();

Java String variable becomes corrupt at runtime

Hey all I've got a weird bug in a small Java program I'm writing for a school project. I am well aware of how sloppy the code is (it is still a work in progress), but anyway, somehow my string variable "year" becomes corrupted after breaking out of a loop. I am using Java with Mapreduce and hadoop to count unigrams and bigrams and sort them by year/author. Using print statements, I have determined that "year" is indeed set when I set it equal to temp, but any time after the loop it is set in, the variable is corrupted somehow. The year number becomes replaced with a huge amount of whitespace (at least that's how it appears in the console). I have tried setting year=year.trim() and using the regex year=year.replaceAll("[^0-9]",""), neither works. Anybody have any ideas?
I have only included the map class, as that is where the problem is. Also it should be noted that the text files being parsed are files from Project Gutenberg.I am working with a small sample of about 40 random texts from the project.
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class WordCount {
public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public synchronized void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
line = line.toLowerCase();
line = line.replaceAll("[^0-9a-z\\s-*]", "").replaceAll("\\s+", " ");
String year=""; // variable to hold date -- somehow this gets cleared out before I need it
String temp=""; // variable to hold each token
StringTokenizer tokenizer = new StringTokenizer(line); // Splits document into individual words for parsing
while (tokenizer.hasMoreTokens()) {
temp = tokenizer.nextToken(); // grab first token of document
if (temp.equals("***")) // hit first triple star, break out and move to next while loop
break;
if (temp.equals("release")&&tokenizer.hasMoreTokens()){ // if token is "release" followed by "date", extract year
if (tokenizer.nextToken().equals("date")){
while(tokenizer.hasMoreTokens()){
temp = tokenizer.nextToken();
for (int i = 0; i<temp.length();i++){
if (Character.isDigit(temp.charAt(0))){
if (temp.length()>3||Integer.parseInt(temp)>=40){
year = temp; // set year = token if token is a number greater than 40 or has >3 digits
break;
}
}
}
if (!year.equals("")){ //if date isn't an empty string, it means we have date and break
break; // out of first while loop
}
}
System.out.println("\n"+year+"\n");// year will still print here
}
} // but it is gone if I try to print past this point
}
while (tokenizer.hasMoreTokens()){ // keep grabbing tokens until hit another "***", then break and
temp = tokenizer.nextToken(); // can begin counting unigrams/bigrams
if (temp.equals("***"))
break;
}
line = line.substring(line.indexOf(temp)); // form a new document starting from location of previous "***"
line = line.replaceAll("[^a-z\\s-]", "").replaceAll("\\s+", " ");
line = line.replaceAll("-+", "-"); /*Many calls to remove excess whitespace and punctuation from entire document*/
line = line.replaceAll(" - ", " ");
line = line.replaceAll("- ", " ");
line = line.replaceAll(" -", " ");
line = line.replaceAll("\\s+", " ");
StringTokenizer toke = new StringTokenizer(line); //start a new tokenizer with re-formatted file
while(toke.hasMoreTokens()){//continue to grab tokens until EOF
temp = toke.nextToken();
//System.out.println(date);
if (temp.charAt(0)=='-')
temp = temp.substring(1);//if word starts or ends with hyphen, remove it
if (temp.length()>1&&temp.charAt(temp.length()-1)=='-')
temp = temp.replace('-', ' ');
if ((!temp.equals(" "))){
word.set(temp+"\t"+year);
context.write(word,one);
}
}
}
}
You have year = temp in your code. It seems it depends on your input what you get there.
Possible bug:
for (int i = 0; i<temp.length();i++){
if (Character.isDigit(temp.charAt(0))){
IMHO you mean i instead of 0 in charAt:
for (int i = 0; i<temp.length();i++){
if (Character.isDigit(temp.charAt(i))){
Also consider not to use StringTokenizer:
StringTokenizer is a legacy class that is retained for compatibility
reasons although its use is discouraged in new code. It is recommended
that anyone seeking this functionality use the split method of String
or the java.util.regex package instead.
The following example illustrates how the String.split method can be
used to break up a string into its basic tokens:
String[] result = "this is a test".split("\\s");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
Found your white space...
The 2 statements that print out the year variable add a couple newlines:
System.out.println("\n"+year+"\n")
or a tab:
word.set(temp+"\t"+year);
context.write(word,one);
Try removing the \n and \t.

Read nth line from string

i am trying to read 7th line of a string so that i can filter the required text but not getting more.(assuming i have n number of line).
class Lastnthchar {
public static void main(String[] args) {
// TODO Auto-generated method stub
String alldata =" FORM"+"\n"+
" to get all data"+"\n"+
" PART A is mandatory"+"\n"+
" enclose all Certificate"+"\n"+
" Certificate No. SFDSFDFS Last updated on 12-Jun-2009"+"\n"+
" Name and address"+"\n"+
" Lisa Lawerence"+"\n"+
" 10/3 TOP FLOOR, Street no 22 ,NewYork"+"\n"+
" residence"+"\n"+
" zip-21232"+"\n"+
" C 78,New York"+"\n"+
" US"+"\n"+
" US"+"\n"+
" "+"\n"+
" worldwide";
String namerequired = new String ();
//BufferedReader br = new BufferedReader(alldata);
int lineno = 0;
for(lineno = 0; lineno <alldata.length(); lineno ++)
{
//what should i do?
}
}
}
so if any solution please help.
alldata.length() will return the length of the string (i.e. number of characters), not the number of lines.
To get the nth line you'll need to split the string at the line breaks, e.g.
alldata.split("\n")[6] to get the 7th line (provided there are at least 7 lines).
This also assumes you have line breaks (\n) in your string and not just carriage returns (\r). If you want to split at both individually or in combination, you can change the parameter of split() to "\r\n|\n|\r". If you want to skip empty lines, you can split at any sequence of at least one line break or carriage return, e.g. "[\r\n]+".
Example:
System.out.println("--- Input:");
String input = "A\nB\rC\n\nD\r\nE";
System.out.println(input);
System.out.println("--- 4th element, split by \\n:");
System.out.println(input.split("\n")[3]); //3rd element will be "D\r"
System.out.println("--- 4th element, split by \\r\\n|\\n|\\r:");
System.out.println(input.split("\r\n|\n|\r")[3]); //3rd element will be an empty string
System.out.println("--- 4th element, split by [\\r\\n]+:");
System.out.println(input.split("[\r\n]+")[3]); //3rd element will be "D"
System.out.println("--- END");
Output:
--- Input:
A
B
C
D
E
--- 4th element, split by \n:
D
--- 4th element, split by \r\n|\n|\r:
--- 4th element, split by [\r\n]+:
D
--- END
Alternatively, if you're reading the text from some stream (e.g. from a file) you can use BufferedReader#readLine() and count the lines. Additionally you can initialize the BufferedReader with a FileReader, StringReader etc., depending on where you read the input from.
If you're reading from the console, the Console class also has a readLine() method.
If you use the BufferedReader you could do the following:
class Lastnthchar {
public static void main(String[] args) throws IOException {
String alldata =" FORM"+"\n"+
" to get all data"+"\n"+
" PART A is mandatory"+"\n"+
" enclose all Certificate"+"\n"+
" Certificate No. SFDSFDFS Last updated on 12-Jun-2009"+"\n"+
" Name and address"+"\n"+
" Lisa Lawerence"+"\n"+
" 10/3 TOP FLOOR, Street no 22 ,NewYork"+"\n"+
" residence"+"\n"+
" zip-21232"+"\n"+
" C 78,New York"+"\n"+
" US"+"\n"+
" US"+"\n"+
" "+"\n"+
" worldwide";
BufferedReader br = new BufferedReader(new StringReader(alldata));
String namerequired;
String line;
int counter = 0;
while ((line = br.readLine()) != null) {
if (counter == 6) {
namerequired = line;
}
counter++;
}
}
}
One way to approach your problem is to check index of "\n" specified amount of times until you find the line you need. I'm writing this off the top of my head so i'm sorry if syntax is not 100% accurate, but the logic is here:
public String readSpecifiedLine(String str, int lineNumber){
int lineStartIndex = 0;
//start by finding start of specified line
for(int i=0;i<lineNumber;i++){
lineStartIndex = str.IndexOf("\n",lineStartIndex); //find new line symbol from
//specified index
lineStartIndex++; //increase the index by 1 so the to skip newLine Symbol on
//next search or substring method
//Note, you might need to increase by 2 if "\n" counts as 2 characters in a string
}
int nextLine = str.IndexOf("\n",lineStartIndex); //end of line 7
retrun str.substring(lineStartIndex,nextline);
}
You might need to play around with indexes

Categories

Resources