Alright so my code doesn't work : I'm trying to arrange inputted strings in both a "descending" and an "ascending" but sometimes strings just won't go in the lists (either in the right order or it doesn't go in the descending/ascending strings at all)
import java.util.Scanner;
public class Stringseries
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Start the sequence by inputting a string DIFFERENT than 'quit'. When you DO want to end it, input 'quit'");
String encore = scanner.nextLine();
int loop = 0;
String smallest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // we set a "smallest" string to know where to put the new string in the "descending" and "ascending" strings.
String longest = "";
String ascending = "";
String descending = "";
String lastInput = "";
while (!encore.equals("quit")) {
loop = ++loop;
encore = encore.replaceAll("\\s+",""); // this way, the length of the strings is only defined by the characters in the string, and not characters + whitespaces.
if (loop == 1) {
descending = encore;
ascending = encore;
} if (loop >= 2) {
if (encore.length() < smallest.length()) {
descending = descending + " " + encore;
ascending = encore + " " + ascending;
} if (encore.length() > longest.length()) {
descending = encore + " " + descending;
ascending = ascending + " " + encore;
}
}
if (longest.length() < encore.length()) {
longest = encore;
} if (smallest.length() > encore.length()) {
smallest = encore;
}
System.out.println("Enter the string you want to put in your sequence of strings");
lastInput = encore;
encore = scanner.nextLine();
}
if (descending != null && !descending.isEmpty()) { // we check to see if the "descending" string is empty (we could do this with "ascending" mind you).
System.out.println("Here are your strings in ascending order : " + ascending);
System.out.println("Here are your strings in descending order : " + descending);
System.out.println("Here is the longest string : " + longest);
} else if (descending == null | descending == "") {
System.out.println("You have not entered any strings, therefore the program doesn't display any string :("); // customised message.
}
} // end Method
} // end Class
I would take a different approach entirely. Yours is very homegrown, and Java has stuff built in that can do this, most notably here, the Stream API and Comparators
String quitString = "quit";
List<String> userInputList = new ArrayList<>();
try(Scanner scanner = new Scanner(System.in)){ // This is called a "try with resources"
System.out.println("Start the sequence by inputting a string DIFFERENT than 'quit'. When you DO want to end it, input \"" + quitString + "\"." + System.lineSeparator());
String encore = scanner.nextLine();
while(!encore.equalsIgnoreCase(quitString)){
encore = encore.replaceAll("\\s+", ""); // this way, the length of the strings is only defined by the characters in the string, and not characters + whitespaces.
System.out.println("Enter the string you want to put in your sequence of strings");
encore = scanner.nextLine();
if(encore != null && !encore.isEmpty() && !encore.equalsIgnoreCase(quitString)) {
userInputList.add(encore);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
List<String> ascending =
userInputList.stream()
.sorted((strA, strB) -> strA.length() - strB.length())
.collect(Collectors.toList());
List<String> descending =
userInputList.stream()
.sorted((strA, strB) -> strB.length() - strA.length())
.collect(Collectors.toList());
StringBuilder sbAscending = new StringBuilder();
sbAscending.append("Here are your strings in ascending order: ");
ascending.forEach(userInput -> {
sbAscending.append(System.lineSeparator() + userInput);
});
System.out.println(sbAscending.toString());
StringBuilder sbDescending = new StringBuilder();
sbDescending.append("Here are your strings in descending order: ");
descending.forEach(userInput -> {
sbDescending.append(System.lineSeparator() + userInput);
});
System.out.println(sbDescending.toString());
Output:
Start the sequence by inputting a string DIFFERENT than 'quit'. When you DO want to end it, input "quit".
Start
Enter the string you want to put in your sequence of strings
test
Enter the string you want to put in your sequence of strings
test2
Enter the string you want to put in your sequence of strings
test23
Enter the string you want to put in your sequence of strings
test234
Enter the string you want to put in your sequence of strings
quit
Here are your strings in ascending order:
test
test2
test23
test234
Here are your strings in descending order:
test234
test23
test2
test
Assuming you want to do stuff by your self, since this seems to be a practice assignment. Otherwise use j.seashell's answer.
Your current code can only input values into the end of the lists. This means that if you input
Test
Second Test
Third Test
The result after the first two inputs will be
ascending = "Test SecondTest"
descending = "SecondTest Test"
Your next value is supposed to go between those two, so the correct result becomes
ascending = "Test ThirdTest SecondTest"
descending = "SecondTest ThirdTest Test"
but your code may only append to the strings right now.
You also filter away strings that are not the shortest or the longst string inputed yet. To solve this you have to implement some way to split the lists, and insertion of the value in the middle of the splitted values. This can be done in several ways for instance
Using a list structure on the form List<String> ascending;
Splitting it each loop with ascending.split(" ");
Using insertion with substrings as in Insert a character in a string at a certain position
The simplest way would be using Javas built-in List structure i.e.
List<String> ascending = new ArrayList<>();
A possible solution to inserting the string in the correct position may then be
boolean inserted = false;
//We loop to the correct location and add it
for(int i = 0; i < ascending.size(); i++) {
if(ascending.get(i).length() > encore.length()) {
ascending.add(i, encore);
inserted = true;
break;
}
}
//If it wasn't inserted its the longest one yet, so add it at the end
if(!inserted) {
ascending.add(encore);
}
You may use the same loop but switch the comparision to be < instead to get an descending list.
At the end you can print the values with
for(String value : ascending) {
System.out.println(value);
}
/*
Hello Mister Dracose.
perhaps you should use something a bit more appropriated for this goal.
in fact you can not manage more than 2 strings at a time on your currently code, so you rather be using
*/
List<String> supplierNames1 = new ArrayList<String>();
/*
java structures, for save all user inputs, before you can go any further.
after that, than you could use your ordenating algotithm exatcly the same way you re already doing.
hope this help
*/
Use a linked list. Every time you add a word, look down your list one item at a time and insert your new node at position n, where n-1.length => n.length > n+1.length
To read it backwards, you can either implement this as a doubly linked list, or read your singly linked list into a stack and pop off the stack
Related
I'm trying to create a ranking that displays this:
int(value) - String(username)
(In total ten times even if I enter 30 values and 30 nicknames)
Here is my working code:
public class Methods {
private static final ArrayList<Double> nbAll = new ArrayList<>();
private static final ArrayList<String> pseudoAll = new ArrayList<>();
public static void test() {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print(ANSI_RED + "Please enter the number of notes you want to calculate : ");
double nb = scanner.nextInt();
String pseudo = scanner.next();
for (int i = 0; i < nb; i++) {
double temp = scanner.nextDouble();
nbAll.add(temp);
}
System.out.println("------------");
System.out.println("Ranking: ");
nbAll.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
retry();
}
}
I tried : To make a second for loop to be forced to enter the username in string but it didn't work and for the ranking I didn't succeed yet
Screen for Desired operation: https://i.imgur.com/0QlGHd8.png
In this particular case I personally think it may be a little better if you used a HashMap or Map Interface to store the required data. It's rather ideal for this sort of thing since the User Name should be unique and can be used as the Key and the Rank as the Value since several Users could potentially contain the same rank value:
Map<String, Integer> map = new HashMap<>();
Another thing which may make life a little easier is for the User to enter the Rank AND the User Name related to that rank on a single line separated with a whitespace or a tab or whatever, for example:
Ranking #1:
Enter a Rank value followed by a User Name separated with space,
for example: 250 John Doe. Enter 'd' when done.
Your entry: --> |
Of course validation would need to be carried out so to ensure proper entry is done but this isn't overly difficult using the String#matches() method and a small Regular Expression (regex), for example:
if (!myString.matches("^\\d+\\s+.{1,}$")) {
System.err.println("Invalid Entry! Try again...");
System.err.println();
myString = "";
continue;
}
What the regular expression "^\\d+\\s+.{1,}$" above passed to the String#matches() method does is that it validates the fact that the first component of the supplied User entry is in fact a string representation of a Integer value consisting of one or more digits. It then checks to make sure at least one whitespace follows that numerical value and then after the space it expects to see at least 1 (or more) of any characters after the space(s) which is to essentially be the User Name. Of course if the User enters the data incorrectly then an Invalid Entry warning would be issued and the user is given the opportunity to attempt the entry again.
Once valid input has been acquired the data now needs to of course be split into its' respective data types before it can be applied to the the Map Interface object. This of course is done with the String#split() method:
String[] stringParts = myString.split("\\s+");
This will create a String[] Array named stringParts. The \\s+ regular expression tells the split() method to split the string on one or more whitespaces ' ' (or Tabs \t, newlines \n, Carriage Returns \r, form-feeds \f, and vertical tabulations \x0B). This would cover pretty much all the cases for the Users required entry.
Now that we have the array we know that the first element of that array will be the supplied Ranking value. We want to convert this into an Integer data type before adding to our Map, like this:
int rank = Integer.parseInt(stringParts[0]);
Now we want the User Name. Because in this example we also allow for multiple names like First and Last names, a little more is involved to add the names together so to make a single User Name string from it all. Remember we split the data entry on whitespaces so if there are multiple names we could potentially have more than just two elements within the stringParts[] array. We'll need to build the userName string. We use a for loop and the StringBuilder class to do this, for example:
String[] stringParts = tmp.split("\\s+");
int rank = Integer.parseInt(stringParts [0]);
StringBuilder sb = new StringBuilder("");
for (int i = 1; i < stringParts .length; i++) {
if (!sb.toString().isEmpty()) {
sb.append(" ");
}
sb.append(stringParts [i]);
}
String userName = sb.toString();
Okay...now we have the User Name so let's make sure a ranking with that User Name isn't already contained within the Map:
if (map.containsKey(userName)) {
System.err.println("A ranking for '" + userName
+ "' has already been supplied! Try again...");
System.err.println();
myString = "";
continue;
}
If we pass to this point then all is good and we can add the data to the Map:
map.put(userName, rank);
This may seem a little long winded but in my opinion, it's not. Below is a working example or all the above in use:
Scanner userInput = new Scanner(System.in);
Map<String, Integer> map = new HashMap<>();
int count = 0;
String tmp = "";
while (tmp.isEmpty()) {
System.out.println("Ranking #" + (count+1) + ":");
System.out.print("Enter a Rank value followed by a User Name separated "
+ "with space,\nfor example: 250 John Doe. Enter 'd' when done.\n"
+ "Your entry: --> ");
tmp = userInput.nextLine();
if (tmp.equalsIgnoreCase("d")) {
break;
}
if (!tmp.matches("^\\d+\\s+.{1,}$")) {
System.err.println("Invalid Entry! Try again...");
System.err.println();
tmp = "";
continue;
}
String[] parts = tmp.split("\\s+");
int rank = Integer.parseInt(parts[0]);
StringBuilder sb = new StringBuilder("");
for (int i = 1; i < parts.length; i++) {
if (!sb.toString().isEmpty()) {
sb.append(" ");
}
sb.append(parts[i]);
}
String userName = sb.toString();
if (map.containsKey(userName)) {
System.err.println("A ranking for '" + userName
+ "' has already been supplied! Try again...");
System.err.println();
tmp = "";
continue;
}
count++;
map.put(userName, rank);
tmp = "";
System.out.println();
}
// Sort the map by RANK value in 'descending' order:
Map<String, Integer> sortedMap = map.entrySet().stream().sorted(Map.Entry.<String,
Integer>comparingByValue().reversed()).collect(java.util.stream.Collectors.toMap(Map.Entry::
getKey, Map.Entry::getValue,(e1, e2) -> e1, java.util.LinkedHashMap::new));
// If you want the Rank values sorted in 'Ascending' order then use below instead:
/* Map<String, Integer> sortedMap2= map.entrySet().stream().sorted(Map.Entry.<String,
Integer>comparingByValue()).collect(java.util.stream.Collectors.toMap(Map.Entry::
getKey, Map.Entry::getValue,(e1, e2) -> e1, java.util.LinkedHashMap::new)); */
// Display the rankings in Console Window:
System.out.println();
System.out.println("You entered " + count + " rankings and they are as follows:");
System.out.println();
// Table header
String header = String.format("%-4s %-15s %-6s",
"No.", "User Name", "Rank");
System.out.println(header);
// The header underline
System.out.println(String.join("", java.util.Collections.nCopies(header.length(), "=")));
// The rankings in spaced format...
count = 1;
for (Map.Entry<String,Integer> enties : sortedMap.entrySet()) {
System.out.printf("%-4s %-15s %-6d %n",
String.valueOf(count) + ")",
enties.getKey(),
enties.getValue());
count++;
}
When the above code is run, The User is asked to supply a Rank value and a User Name related to that rank. The User is then asked to enter another and another and another until that User enter 'd' (for done). All entries provided are then displayed within the Console Window in a table type format. The Rankings within the Map had been sorted in descending order before (highest rank first) before displaying them. If you prefer Ascending order then that code is also provided but is currently commented out.
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
Hi I am trying to generate response as true or false if a code exists in the list. So I am able to generate the response if the string contains a 'single in-brackets' values for example:"ABC(Q,E,1)EEE", but if a string has multiple brackets like:"B(A,1)AA(E,Z)EE", I am not able to generate output from this. I am new to coding and building logics, it will be great if someone can help.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the code you want to check: ");
String input = scan.next();
List<String> codes = new ArrayList<>();
codes.add("ABC(Q,E,1)EEE");
codes.add("ABDCE(E,Z,X)E");
codes.add("B(A,1)AAEEE");
codes.add("R(1,2,3,4,5)RT(U,M,N,B,V,H)(Q,E,R,F,G,H)(R,Z)");
codes.add("B(A,1)AA(E,Z)EE");
for (Iterator<String> i = codes.iterator(); i.hasNext(); ) {
String code = i.next();
String prefix = code.substring(0, code.indexOf("("));
String suffix = code.substring(code.indexOf(")") + 1);
String middle = code.substring(code.indexOf("(") + 1, code.indexOf(")"));
String[] var = middle.split(",");
String[] result = new String[var.length];
for (int j = 0; j < var.length; j++) {
result[j] = prefix + var[j] + suffix;
if (result[j].equals(input)) {
System.out.println("True: This code is present");
}
}
}
}
Output (which works):
Enter the code you want to check:
BAAAEEE
True: The code is present
Output(not working):
Enter the code you want to check:
BAAAZEE
<gives no output>
Let me give you an example(for "ABC(Q,E,1)EEE") of what is being done: it makes three possible outputs of this string that are: "ABCQEEE", "ABCEEEE", "ABC1EEE". So if i give the input as "ABCQEEE" , it will generate these outputs internally and give me output as True if the code is present anywhere in the list.
If all you have to do is to out put true or false depending on the user input, you can convert your code strings to regular expressions and check if input matches the list of regex.
Steps:
Convert each element in your codes list to a regex
// convert "ABC(Q,E,1)EEE" to "ABC[QE1]EEE" to match each string starting with ABC followed by one of [QE1] and ending with EEE
//"R(1,2,3,4,5)RT(U,M,N,B,V,H)(Q,E,R,F,G,H)(R,Z)" to "R[12345]RT[UMNBVH][QERFGH][RZ]"
etc
Check if input matches one of the regexes
Example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the code you want to check: ");
String input = scan.next();
List<String> codes = new ArrayList<>();
codes.add("ABC(Q,E,1)EEE");
codes.add("ABDCE(E,Z,X)E");
codes.add("B(A,1)AAEEE");
codes.add("R(1,2,3,4,5)RT(U,M,N,B,V,H)(Q,E,R,F,G,H)(R,Z)");
codes.add("B(A,1)AA(E,Z)EE");
//list to store the modified strings
List<String> modifiedCodes = new ArrayList<>();
//for each string in list find if there is a pattern like '('some chars')'
Pattern p = Pattern.compile("\\(.*\\)");
for (Iterator<String> i = codes.iterator(); i.hasNext();) {
String code = i.next();
StringBuffer sb = new StringBuffer ();
Matcher m = p.matcher(code);
while (m.find()) {
String match = m.group();
//if found a match replace '(' and ')' with '[' and ']' and remove commas
m.appendReplacement(sb, match.replace('(', '[').replace(')', ']').replace(",", ""));
}
m.appendTail(sb);
//add modified string to list
modifiedCodes.add(sb.toString());
}
boolean codeIsPresent = false;
for(String code: modifiedCodes){
//check if input matches one of the regex in the list 'modifiedCodes'
if (input.matches(code)) {
codeIsPresent = true;
System.out.println("True: This code is present");
break;
}
}
if(!codeIsPresent){
System.out.println("Code not found");
}
}
EDIT
how can we print the list of all the combinations of the string from
which it is getting the output? say, I just have a string
"BA(1,2,3)QW(A-Z,0-9)" and I want all the possible combinations of it
The above question from your coments is slightly difference as the original post, it might be better if you post a new question. You can create your own algorithm with somekind of tree structure to solve the issue but it can be very hackish and messy. I would suggest to use a 3rd party libraray like generex if possible. You can download the jar from the maven repo here. With generex you can have all your possible commbinations:
public static void main(String args[]){
//change your input to a regular expression
//"BA(1,2,3)QW(A-Z,0-9)" to "BA[1-3]QW[A-Z][0-9]"
Generex generex = new Generex("BA[1-3]QW[A-Z][0-9]");
List<String> matchedStrs = generex.getAllMatchedStrings();
matchedStrs.forEach(System.out::println);
}
Try this.
Edited : Added code comments.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the code you want to check: ");
String input = scan.next();
scan.close();
List<String> codes = new ArrayList<>();
codes.add("ABC(Q,E,1)EEE");
codes.add("ABDCE(E,Z,X)E");
codes.add("B(A,1)AAEEE");
codes.add("R(1,2,3,4,5)RT(U,M,N,B,V,H)(Q,E,R,F,G,H)(R,Z)");
codes.add("B(A,1)AA(E,Z)EE");
for (Iterator<String> i = codes.iterator(); i.hasNext();) {
String code = i.next();
List<String> codePossiblity = generatePossibilities(code);
// check if the input is in the list of all the possibility
for (String s : codePossiblity) {
if (s.contains(input)) {
System.out.println("True: This code is present");
}
}
}
}
/* This method removes the parenthesis and generates all the possibilities.
* This method assumes that the parenthesis always comes in pair, thus
* for every opening parenthesis ["("] there is a closing parenthesis [")"]
* Example if the "code" is [A(WX)C(YZ)] then it will generate AWCY, AWCZ, AXCY and AXCZ
*
* #param code - The string which contains parenthesis.
* #return a list of all the possibilities
*/
public static List<String> generatePossibilities(String code) {
// This will hold the left part of the possibleCodes (part before "(")
List<String> possibleCodeList = new LinkedList<>();
String s = code;
boolean first = true;
// Loop while an open parenthesis ["("] can be found
while (s.contains("(")) {
// Retrieve from the string the first substring where "(" starts and ends with ")"
// In the example, in the first iteration will be "WX"
// in the second iteration this will be "YZ"
String inside = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
// Retrieve the list inside the "(" and ")"
// In the example, in the first iteration the list will have "W", "X"
// in the second iteration the list will have "Y", "Z"
String[] listOfChoices = inside.split(",");
// This will hold the right part of the possibleCodes (part after ")")
List<String> listOfCombinations = new LinkedList<>();
// Loop all the possible choices
for (String choice : listOfChoices) {
// If it is the first iteration then you need to include those characters before the "("
if (first) {
// add the characters before the "(" and the remaining characters after ")"
// In the example, the first iteration of this list ("W", "X") will add "AWC(YZ)"
// the second iteration of this list ("W", "X") will add "AXC(YZ)"
listOfCombinations.add(s.substring(0, s.indexOf("(")) + choice + s.substring(s.indexOf(")") + 1));
}
// Else just start with choice
else {
// add the remaining characters after ")"
// In the example, the first iteration of this list ("Y", "Z") will add "Y"
// the second iteration of this list ("Y", "Z") will add "Z"
listOfCombinations.add(choice + s.substring(s.indexOf(")") + 1));
}
}
// Remove the subtring before the ")", in the example this will be "C(YZ)"
s = s.substring(s.indexOf(")") + 1);
// If it is the first iteration then you just need to assign the listOfCombinations directly to possibleCodeList,
// since possibleCodeList is still empty
if (first) {
possibleCodeList = listOfCombinations;
first = false;
}
// Else combine the left and right part
else {
List<String> codePossiblity2 = new LinkedList<>();
// Iterate though all the list of possible codes since we want all the elements in the list to be concatenated with the right half of the string
// The list will have "AWC(YZ)" and "AXC(YZ)"
for (String possibleCodes : possibleCodeList) {
// Iterate the possible combinations of the right half of the original string (the second pair of "()")
// The list will have "Y" and "Z"
for (String sTmp : listOfCombinations) {
// Replace the string which are inside the "()" in the left half of the original string.
// Replace it with the right half of the original string
// In the string of "AWC(YZ)" replace "(YZ)" with "Y"
// In the string of "AWC(YZ)" replace "(YZ)" with "Z"
// In the string of "AXC(YZ)" replace "(YZ)" with "Y"
// In the string of "AXC(YZ)" replace "(YZ)" with "Z"
String t = possibleCodes.replace("(" + inside + ")", sTmp);
// add the newly created string to codePossiblity2
codePossiblity2.add(t);
}
// At the end of the loop above codePossiblity2 will have these values
// AWCY, AWCZ, AXCY and AXCZ
}
// overwrite the possibleCodeList since we have now a new left part of the string
possibleCodeList = codePossiblity2;
}
}
return possibleCodeList;
}
}
I need some help here with my java school work.
We were told to prompt the user for five words and from there determine the longest word of them and print to console the longest word as well as the number of characters in it.
Right now, I only manage to sort them out using the arrays by displaying the longest number of characters but i'm not sure how to display the word itself. Can someone please help me with it and please bear in mind i'm a total newbie in programming and my progress is still just in the basics so try to make it not too complicated for me please. In addition, feel free to pinpoint those redundant codes as I know I have quite a few. :) Thanks!
import java.util.Scanner;
import java.util.Arrays;
class LongestWord
{
public static void main(String [] args)
{
Scanner theInput = new Scanner(System.in);
System.out.println("Please enter your five words");
String fWord = theInput.next();
String sWord = theInput.next();
String tWord = theInput.next();
String fhWord = theInput.next();
String ffWord = theInput.next();
System.out.println(fWord + sWord + tWord + fhWord + ffWord);
int [] wordCount = new int[5];
wordCount[0] = fWord.length();
wordCount[1] = sWord.length();
wordCount[2] = tWord.length();
wordCount[3] = fhWord.length();
wordCount[4] = ffWord.length();
Arrays.sort(wordCount);
System.out.println(wordCount[4]);
}
}
You need to add all the string to array and iterate all of them.
sample:
String [] wordCount = new String[5];
wordCount[0] = fWord;
wordCount[1] = sWord;
wordCount[2] = tWord;
wordCount[3] = fhWord;
wordCount[4] = ffWord;
String longest = "";
longest = wordCount[0]; //get the first array of words for checking
for(String s : wordCount) //iterate to all the array of words
{
if(longest.length() < s.length()) //check if the last longest word is greater than the current workd
longest = s; //if the current word is longer then make it the longest word
}
System.out.println("Longest Word: " + longest + " lenght: " + longest.length());
result:
Please enter your five words
12345
1234
123
12
1
123451234123121
Longest Word: 12345 lenght: 5
You need to store all words into array and get the maximum value after sort according to its length.
String[] words = ....//Store all words into this array.
Arrays.sort(words, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
});
System.out.println(words[0]);
or, if you use java-8 than you will get the result more easily,
String longWord=
Arrays.stream(words).max((o1, o2)->o1.length()-o2.length()).get();
Instead of putting lengths into an array, you should put all the words in an array and then loop them using for/while and check length of each string comparing with the previous one to record the max length string.
Or another way may be to read strings using loop and you can perform same logic of comparing lengths without using additional array.
I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.
Below is my code. Basically it worksout whether the characters are in ascending or descending order. It works perfectly if a lower case word is entered, but if for example aB is entered it is saying the letters are not in orde, when they clearly are!!! not really to sure and i'm starting to dispair at this!
text.toLowerCase();
while ( ! text.equals( "END" ) )
{
String string = (text);
char[] content = string.toCharArray();
java.util.Arrays.sort(content);
String sorted = new String(content);
if (text.equals(sorted))
{
System.out.print(text);
System.out.print(" letters in ascending order");
System.out.println();
}
else
{
System.out.print((text));
System.out.print(" letters not in ascending order");
System.out.println();
}
System.out.println();
System.out.print( "#Enter input text : " );
text = BIO.getString();
}
}
}
You need to save the value back to text (and check for a lower-case "end" since it was converted).
text = text.toLowerCase();
while (!text.equals("end")) { // ...
toLowerCase does not modify the original string, rather returns a lower-cased version.
Alternatively, if you want to preserve "END" to end:
lowered = text.toLowerCase();
while (!text.equals("END")) {
// ... etc ...
text = BIO.getString();
lowered = text.toLowerCase();
}
Why not use text.compareToIgnoreCase(sorted) == 0 ?