I am trying to do this stuff. If a user enters "C:\Windows\system32\foo.txt" then the program will convert it to "C:\\Windows\\system32\\foo.txt". A front slash needs to be added to every other preceding slash. Here's what I have coded till now (only the section relevant):
import javax.swing.*;
public class test {
public static void main(String[] args){
String path = JOptionPane.showInputDialog(null, "Enter the File path", "Word counter", JOptionPane.INFORMATION_MESSAGE);
for (int z=0;z<=path.length()-1;z++)
{
if (path.charAt(z) == '\\')
{
path.charAt(z) = "\\\\";
}
}
System.out.println(path); // For knowing what's going on
}
}
Unfortunately it's not compiling, and I don't have a clue of what to do. Any possible help welcomed. Thank you!
You are trying modify a String. Remember strings are immutable.
you can try something like
path.replace(oldChar, newChar) if you want to replace some chars.
This: path.charAt(z) cannot be on the left side of an assignment statement. Instead concatenate your String or use a StringBuilder.
Or just use String's replace(...) method.
Related
We were told to do a program on stings and I wasn't able to attend class because I was sick. I am asking for your help on this task that was given to us.
Create a java program that will ask the user to input two Strings. Compare the two strings and display the letters that are found on the first string but are not found on the second string.
Here is what I have at the moment https://pastebin.com/7a4dHecR
I really have no Idea what to do so any help would be appreciated!
https://pastebin.com/7a4dHecR
import java.util.*;
public class filename{
public static void main(String[] args){
Scanner sc =new Scanner(System.in);
System.out.print("Input first string: ");
String one=sc.next();
System.out.println();
System.out.print("Input second string: ");
String two=sc.next();
}
}
There are many ways to do this. I'm going to give you some parts you can put together. They are not the shortest or simplest way to solve this particular problem, but they will be useful for other small programs you write.
Here are some hints:
First, figure out how to step through your code with a debugger.
Second, figure out how to find the Javadoc for Java library classes and their methods.
You need to do something for each character in a string. Use a for loop for that:
for (int i = 0; i < one.length(); i++) {
// your code here
}
You need to get a particular character of a String.
String c = one.substring(i, i+1);
Read the Javadoc for String.substring to understand what the i and i+1 parameters do.
Now you need to find a way to check whether a String contains another String. Look at the Javadoc for the String class.
Then you can put all this together.
You could try the following:
String diff: StringUtils.difference(one, two);
System.out.println(diff);
I have to write a program which prints the String which are inputed from a user and every letter like the first is replaced with "#":
mum -> #u#
dad -> #a#
Swiss -> #wi## //also if it is UpperCase
Albert -> Albert //no letter is like the first
The user can input how many strings he wants. I thought to split the strings with the Split method but it doesn't work with the ArrayList.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
ArrayList <String> Parolecens= new ArrayList <String>();
while (s.hasNextLine()) {
tdc=s.nextLine();
Parolecens.add(tdc);
}
System.out.println(Parolecens);
}
}
If you want to read in single words you can use Scanner.next() instead. It basically gives you every word, so every string without space and without newline. Also works if you put in two words at the same time.
I guess you want to do something like this. Feel free to use and change to your needs.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
while (s.hasNext()) {
tdc=s.next();
char c = tdc.charAt(0);
System.out.print(tdc.replaceAll(Character.toLowerCase(c) +"|"+ Character.toUpperCase(c), "#"));
}
}
}
Edit:
Basically it boils down to this. If you want to read single words with the scanner use .next() instead of .nextLine() it does consider every word seperated by space and newline, even if you put in an entire Line at once.
Tasks calling for replacing characters in a string are often solved with the help of regular expressions in Java. In addition to using regex explicitly through the Pattern class, Java provides a convenience API for using regex capabilities directly on the String class through replaceAll method.
One approach to replacing all occurrences of a specific character with # in a case-insensitive manner is using replaceAll with a regex (?i)x, where x is the initial character of the string s that you are processing:
String result = s.replaceAll("(?i)"+s.charAt(0), "#");
You need to ensure that the string is non-empty before calling s.charAt(0).
Demo.
Assuming that you've successfully created the ArrayList, I'd prefer using the Iterator interface to access each elements in the ArrayList. Then you can use any String variable and assign it the values in ArrayList . Thereafter you can use the split() in the String variable you just created. Something like this:
//after your while loop
Iterator<String> it = Parolecens.iterator();
String myVariable = "";
String mySplitString[];
while(it.hasNext()) {
myVariable = it.next();
mySplitString = myVariable.split(//delimiter of your choice);
//rest of the code
}
I hope this helps :)
Suggestions are always appreciated.
In Java can I use startsWith and endsWith to check a user input string? Specifically, to compare first and last Characters of the input?
EDIT1: Wow you guys are fast. Thank you for the responses.
EDIT2: So CharAt is way more efficient.
So How do I catch the First and last Letter?
char result1 = s.charAt(0);
char result2 = s.charAt(?);
EDIT3: I am very close to making this loop work, but something is critically wrong.
I had some very good help earlier, Thank you all again.
import java.util.Scanner;
public class module6
{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
while(true){
System.out.print("Please enter words ending in 999 \n");
System.out.print("Word:");
String answer;
answer = scan.next();
char aChar = answer.charAt(0);
char bChar = answer.charAt(answer.length()-1);
String MATCH = new String("The word "+answer+" has first and last characters that are the same");
String FINISH = new String("Goodbye");
if((aChar == bChar));
{
System.out.println(MATCH);
}
if(answer !="999")
{
System.out.println(FINISH);
break;
}
}
}
}
The loop just executes everything, No matter what is input. Where did I go wrong?
In Java can I use startsWith and endsWith to check a user input string?
You certainly can: that is what these APIs are for. Read the input into a String, then use startsWith/endsWith as needed. Depending on the API that you use to collect your input you may need to do null checking. But the API itself is rather straightforward, and it does precisely what its name says.
Specifically, to compare first and last Characters of the input?
Using startsWith/endsWith for a single character would be a major overkill. You can use charAt to get these characters as needed, and then use == for the comparison.
yes, you should be able to do that and it should be pretty striaghtforward. Is there a complexity that you are not asking?
Yes, in fact, not just characters, but entire strings too.
For example
public class SOQ4
{
public static void main(String[] args)
{
String example = "Hello there my friend";
if(example.startsWith("Hell"))
{
System.out.println("It can do full words");
}
if(example.startsWith("H"))
{
System.out.println("And it can also do letters");
}
if(example.endsWith("end"))
{
System.out.println("Don't forget the end!");
}
if(example.endsWith("d"))
{
System.out.print("Don't forget to upvote! ;)");
}
}
}
I recommend you use the API, here's a link to it http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
I am writing a program that counts song lyrics. Right now I have it programmed to delete certain characters using line.replace, for example:
String computerComma=",";
String computerPeriod=".";
String nothing="";
line=line.replace(computerComma,nothing);
line=line.replace(computerPeriod,nothing);
and this works totally fine. However, when I try
String computerExclamation="!";
line=line.replace(computerExclamation,nothing);
it messes up my entire program and many of my word counters. Does anybody know the reason behind this?
Thanks!
No. Works fine.
public static void main(String[] args) {
String computerExclamation="!";
String line = "i am a String !!.";
line=line.replace(computerExclamation,"");
System.out.println(line); //i am a String .
}
Error lies some where else.
You can see here.
public class recursionExcercise4
{
public static void main (String[] args)
{
boolean statement=false;
String ch="";
String a="I am bubbles who is a little slugger and loves apple and yellow."
BacktoBacks(a,ch,statement);
}
public static void BacktoBacks(String sentence, String ch, boolean statement)
{
String newLine="",word="";
System.out.print(sentence.charAt(0));
if(sentence.charAt(0)=='.') System.out.println();
if(sentence.length()>1)
{
int num=sentence.substring(1).indexOf(" ");
word = sentence.substring(0,num);
System.out.println(word);
}
BacktoBacks(newLine,ch,statement);
}
}
That is the code.
The lines inside the if statement loop were added by me so you can change that but nothing else can be changed. The if statement on top must remain there. Also, I am trying to avoid loops as it makes it too easy then. Any way to do this? I tried it but need help.
The objective is to print out the words from the string that have double letters. This should also be printed backwards. So like this:
Yellow
Apple
Slugger
Little
Bubbles
Your help is much appreciated.
Thanks!!
So you need a function to check whether a word contains double letters,
public boolean hasDoubleLetters(String word){
// test
}
and based on its outcome, print the word after the recursive call. And you have to pass the correct argument to the recursive call.