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);
Related
I've been trying to figure out how to create a program for a class. So far, I've gotten the rest of it down but I'm still unsure on how to do the start to it.
It requires for me to receive a name in any format: jOhn, joHN, JoHn
and convert it to John. I've been searching everywhere on how to separate them and return but I've had no luck.
Can anybody help?
This is for Java by the way.
EDIT: Not sure if I ended up doing it the right way, but I ended up with this:
System.out.println("Please type in your first name.");
String firstName = fName.next();
String partFirstName = firstName.toUpperCase().substring(0,1);
String partFirstName2 = firstName.toLowerCase().substring(1);
String correctFirst = (partFirstName + partFirstName2);
Simply in Java, without any 3rd party libraries, you can iterate over each element of an array of splitted Strings and then do:
Character.toUpperCase(user_input.charAt(0)) + user_input.substring(1).toLowerCase();
I don't know if this is what you are looking for but you could try the following:
EDIT: Thanks to Bohemian for pointing out a little bug in my code. The simplest code for the name formatting problem is Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase();. This is also what mhasen answered with so credit to him and also to Bohemian. Below contains the code snippet and all.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String newInput = Character.toUpperCase(charAt(0))
+ input.substring(1).toLowerCase();
System.out.println();
System.out.println(newInput);
scan.close();
}
}
You can use Apache Commons Lang library's WordUtils.capitalize()
e.g: WordUtils.capitalize("john") will return "John".
And in order to split the string you can use split() method of String:
String input = "jOhn,JOhn,jOHn";
String[] values = input.split(",");
values will be array of String contain "jOhn","JOhn" and "jOHn"
I'm trying to write a method that will take a sentence (a String) and convert it into an array of words (Strings) (and it will return this array). I'm looking for a manual way to do this, without .split or tokenize.
So far, all I have in terms of code is the name of my method
public String[] tokenize();
After that, I'm at a loss of where to start. Any help is appreciated, thanks.
EDIT: The string is not of fixed length, the input sentence can be anything.
You probably would want to use java.util.Scanner and construct the scanner with the string
Scanner sc = new Scanner(string);
sc.useDelimiter(\p{Space});
while(sc.hasNext)
{
string[i] = sc.next();
}
or something like that
Or, use a for loop, check each character, and chop off a substring.
I'm currently working on an anagram solver. I saw a really good post which had one recommendation on alphabetizing the letters of both the user input and dictionary list before comparing. It seemed interesting so I'm giving it a try. Previously I used permutations, but I want something that I can eventually (and efficiently) use to solve multi word anagrams.
I can put both my user input and dictionary into char arrays and sorting alphabetically. Now I need to compare each so I can determine if something is an anagram or not. I thought about taking the alphabetized user input and determining if the alphabetized dictionary contained it or not. I've posted my code below. As you can guess I'm a little confused on the logic of this process. I was wondering if someone could help me straighten out the logic a little. Thanks for any help.
public class AnagramSolver1 {
public static void main(String[] args) throws IOException {
List<String> dictionary = new ArrayList<String>();
List<String> inputList = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader("src/dictionary.txt"));
String line = null;
Scanner scan = new Scanner(System.in);
while (null!=(line=in.readLine())){
dictionary.add(line);
}
in.close();
char[] sortDictionary;
char[] inputSort;
System.out.println("Enter Word: ");
String input = scan.next();
inputList.add(input);
//Getting a little confused here. I thought about sorting my input
//then iterating through my dictionary (while sorting it too) and comparing
//thus far it produces nothing
for(int i = 0; i < inputList.size(); i++){
inputSort = inputList.get(i).toCharArray();
Arrays.sort(inputSort);
for (int j = 0; j < dictionary.size(); j++) {
sortDictionary = dictionary.get(i).toCharArray();
Arrays.sort(sortDictionary);
if(inputSort.equals(sortDictionary)){
System.out.println("Anagram" +dictionary.get(i));
} //end if
}//end for
}//end for
}//end main
}
Why not maintain a Map<String, Set<String>> that maps a sorted-character string to a set of strings that are its anagrams. You can update this map as you read words from the dictionary. For example, if you read the word dog you would add an entry to the map "dgo" => {"dog"} (notice that dgo consists of the sorted characters of the word dog). Then if you read the word god, you would sort its characters to obtain the same dgo and consequently amend the previous entry to be "dgo" => {"dog", "god"}. You would of course repeat this for every word in the dictionary.
This should allow for quick and easy querying. If you wanted to then find anagrams of the word dog you would use map.get(sortChars("dog")).
On another note, I'm going to reiterate what the other answer mentioned, namely that it's important to modularize your code. You should put logically related functions/tasks in their own methods as opposed to having everything in one place. This helps with readability and your/others' ability to maintain your code in the future.
You are doing too many things at once here. You've got file IO, user input, sorting and the algorithm all in one place. Try to modularize it so you have a function called isAnagram(List<Character> firstPhrase, List<Character> secondPhrase). Make sure that works correctly, then have all the other steps figure out how to call it. This way you can test your algorithm without requiring user input. This will be a much faster feedback loop.
It's algorithm will work like this:
(optionally) copy the contents of the input so you don't mutate the input
compare their lengths. If they're not equal, return false
sort each list
iterate element by element and check if they're equal. If they're not, return false
if you reach the end, return true.
I'm creating a method that will take the given input and set the value to "plate". I then proceed to use the charAt method and try to take the characters(letters/String) input and set it to a new value. But i'm told to set it to a char value. When I run aprint statement with it, the output is just a bunch of integers, or in my case (for the code i'm going to show) it outputs "195" when I put the license plate as abc 123. Also, the model doesn't do anything(or atleast isnt supposed to). If anyone could tell me what exactly i'm doing wrong it would be a great help.
Here is my code so far:
import java.util.Scanner;
public class CarRental {
public static String model;
public static String plate;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Car Model:");
model = input.nextLine();
System.out.println("License Plate: ");
plate = input.nextLine();
char one = plate.charAt(0);
char two = plate.charAt(1);
System.out.println(two + one);
}
}
To make my issue clear, what I'm hoping to do is, assign the actual letters I type into the input to a separate value. I'm using the charAt method and it is returning integers.
if anyone could offer a suggestion it would help alot!
Thanks,
Sully
the + operator treats 2 chars as ints, try
System.out.println("" + two + one);
You can just use
Character.toChars(X)
Where x is your number to convert to char and then display said chars once they've been converted.
For my assignment I've had to create an ArrayStack, a StackADT, and now I have to make a program to take in a string and output it in reverse.
Now this sounds simple, but I have no idea how to push something into the array. I've been googling the shit out of this and can't find an actual answer that makes sense.
Specifically I'm having trouble linking the main program to the actual array, and then linking the input string to the push().
public class ReverseSentenceMain {
public static void main (String[] args)
{
AssignmentArrayStack stack = new AssignmentArrayStack();
//private AssignmentArrayStack<String> stack;
public ReverseSentenceMain()
{
stack = new AssignmentArrayStack<Integer>();
}
String sentence;
String result = null;
String words;
stack = (T[])(new Object[initialCapacity]);
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence");
}
}
I'd appreciate any help and thanks for your time
You start scanning by calling next on the scanner.
sentence = in.next();
Then you perform a split on whitespace to divide up the sentence into tokens that you push into your stack. The scanner can do the split for you I think. Look at the Scanner JavaDoc or String JavaDoc for more information.
You should format the code. Press ctrl+K or use the little 101010 icon.
Anyways. The stack class should have a push method. You need to get the sentence. You could loop through the sentence and then push the characters onto a stack. Once you do that, then you can pop the characters off to print the string in reverse order.
loop through string
stack.push(string[i])
while(currChar = stack.pop())
print currChar (or store to another variable)
I believe that will work. Been a while since ive done anything in java.
A stack isn't really an array. Its more like a linked list. It adds an element as the first element in a linked list and then updates the pointer.
Acutally heres a decent example http://www.javacoffeebreak.com/faq/faq0037.html
And i just noticed you want to reverse the sentence and not the word, so do what willcodejavaforfood said and tokenize it with scanner. I remember you can do this. It will read up every whitespace. you get that token and add it to the stack. Some kind of type of concept though.