I'm currently in my first semester. I have a project requiring me to build a program having a user input 3 words, sort them alphabetically and output the middle word. I have done some searching and seem to only come back with results for sorting 2 words. I so far have code to get the user input but I am completely lost as to how to sort them alphabetically and how to prompt the user to enter the three strings. Please be patient with me as I am very new to programming. If anyone can provide me with any advice or the best or easiest way to go about sorting these I would greatly appreciate it
import java.util.Scanner; //The Scanner is in the java.util package.
public class MiddleString {
public static void main(String [] args){
Scanner input = new Scanner(System.in); //Create a Scanner object.
String str1, str2, str3;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
str1=input.next(); //Sets "str1" = to first word.
str2=input.next(); //Sets "str2" = to second word.
str3=input.next(); //Sets "str3" = to third word.
System.out.println("The middle word is " ); // Outputs the middle word in alphabetical order.
}
}
Please help!
Try something like this:
String [] strings;
int i = 0;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
strings[i++] = input.next(); //Sets "str1" = to first word.
strings[i++] = input.next(); //Sets "str2" = to second word.
strings[i++] = input.next(); //Sets "str3" = to third word.
Arrays.sort(strings);
System.out.println("The middle word is " + strings[strings.length / 2]);
You can sort (compare) only two words at a time, yes, but that is the basis for the whole sorting algorithm. You'll need to loop through your array of words and compare each word with each other word.
String[2] words = new String[2];
words[0] = input.next();
words[1] = input.next();
words[2] = input.next();
String[2] sortedWords = new String[2];
for (String word: words){ // outer loop
for (String word: words){ // inner loop to compare each word with each other
// logic to do the comparisons and sorting goes here
}
}
System.out.println(sortedWords[1]);
Of course I've left out the fun part for you, but that should get you started.
Related
Ive been writing a program that is able to calculate a person's grades, but Im unable to turn a string into an String array (it says the array length is 1 when i put in 3 words). Below is my code. Where am I going wrong??
protected static String[] getParts(){
Scanner keyboard = new Scanner(System.in);
System.out.println( "What assignments make up your overall grade? (Homework, quizzes, etc)" );
String parts = keyboard.next();
Pattern pattern = Pattern.compile(" ");
String[] assignments = pattern.split(parts);
// to check the length
for ( int i = 0; i < assignments.length; i++ )
System.out.println(assignments[i]);
return assignments;
}
Scanner::nextLine
Scanner::next() only consumes one word (it stops at whitespace). You want Scanner::nextLine, which consumes everything until the next line, and will pick up all your words.
Use keyboard.nextLine instead:
static String[] getParts()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What assignments make up your overall grade? (Homework, quizzes, etc)");
String[] assignments = keyboard.nextLine().split(" ");
for (String i : assignments)
System.out.println(i);
return assignments;
}
NOTE: You also do not need to define a Pattern. You also do not need to return anything since the method already prints the strings. Unless of course you plan on using the values elsewhere
The user is supposed to enter multiple words (without regards to lower/uppercase) with space inbetween, this text will then be translated into initials without any spaces included. However, I only want the initials of the words that I approve of, if anything but those words, the printout will instead say "?" instead of printing the first alphabet of a word. E.q: "hello hello hello" will come out as: "HHH", but "hello hi hello" or "hello . hello" will instead result in "H?H".
I've managed to make it print out the initials without the spaces. But I can't figure out how to add a condition where the program would first check whether the input contains unapproved words or signs/symbol or not in order to replace that unapproved or non-word with a question mark instead of just going ahead and printing the initial/sign. I've tried placing the for-loop inside an if-else-loop and using a switch()-loop but they won't interact with the for-loop correctly.
public static void main (String []args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String str = input;
String[] parts = str.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
System.out.print(i.charAt(0));
}
}
So what happens right now is that regardless what words the user enter, the initials of each word or symbol/sign will be printed regardless.
You should create a set of approved words and then check whether each word, entered by the user, makes part of this set.
Something like this:
...
Set<String> approved_words = new TreeSet<>();
approved_words.add("HELLO");
approved_words.add("GOODBYE");
...
for (String i : parts) {
if (approved_words.contains(i))
System.out.print(i.charAt(0));
else
System.out.print('?');
}
System.out.println();
Small suggestion:
You may want to allow the user to enter multiple spaces between the words.
In that case, split the words like this: str.split(" +")
If you want to filter against words you dislike, you will have to code it.
Like the example with "hi":
public static void main (String []args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String str = input;
String[] parts = str.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
if(!"HI".equals(i))
System.out.print(i.charAt(0));
else
System.out.print("?");
}
}
Of course in real life you want such comparison on a collection, preferably something fast, like a HashSet:
public static void main (String []args) {
Set<String> bannedWords=new HashSet<String>(Arrays.asList("HI","."));
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String str = input;
String[] parts = str.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
if(!bannerWords.contains(i))
System.out.print(i.charAt(0));
else
System.out.print("?");
}
}
(this one bans 'hi' and '.')
You could create a simple Set containing all the words that you accept. Then in your for loop, for every String i you check if the set contains ``i```. If this is true, you print out i.charAt(0). Otherwise you print out "?".
I could provide code for this if necessary, but it's always good to figure it out yourself ;)
Supposed you provide unapproved words as input arguments
public static void main (String []args) {
Set<String> unapprovedSet = new HashSet<>(Arrays.asList(args));
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String[] parts = input.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
if (unapprovedSet.contains(i)) {
System.out.print("?");
} else {
System.out.print(i.charAt(0));
}
}
}
i want to count number of words per sentences i write code but count character for each word in sentences this my code
public static void main(String [] args){
Scanner sca = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String sentences= sca.nextLine();
String []count_words= sentences.split(" ");
for(String count : count_words){
System.out.println("number of word is "+count.length());}
}
String[] count_words= sentences.split(" "); is splitting the input argument by " " that means that length of this array is the number of words. simply print the length out.
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String sentences= sca.nextLine();
String[] count_words= sentences.split(" ");
System.out.println("number of word is "+ count_words.length);
}
example:
oliverkoo#olivers-MacBook-Pro ~/Desktop/untitled folder $ java Main
Please type some words, then press enter:
my name is oliver
number of word is 4
The method call count.length() is returning the length of each word because the loop is assigning each word to variable count. (This variable name is very confusing.)
If you want the number of words in the sentence, you need the size of the count_words array, which is count_words.length.
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 need to write a program that helps determine a budget for "peer advising" the following year based on the current year. The user will be asked for the peer advisor names and their highest earned degree in order to determine how much to pay them. I am using a JOptionPane instead of Scanner and I'm also using an ArrayList.
Is there a way for the user to input both the name and the degree all in one input and store them as two different values, or am I going to have to have two separate input dialogs? Example: storing the name as "Name1" and the degree as "Degree1 in order to calculate their specific pay.
Also, I am using an ArrayList but I know that the list will need to hold a maximum of six (6) elements, is there a better method to do what I am trying to do?
Here is what I had down before I started thinking about this, if it's necessary.
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class PeerTutoring
{
public static void main(String[] args)
{
ArrayList<String> tutors = new ArrayList<String>();
for (int i = 0; i < 6; i++)
{
String line = null;
line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
String[] result = line.split("\\s+");
String name = result[0];
String degree = result[1];
}
}
}
"Is there a way for the user to input both the name and the degree all
in one input, but store them as two different values."
Yes. You can ask the user to enter input separated with space for example, and split the result:
String[] result = line.split("\\s+"); //Split according to space(s)
String name = result[0];
String degree = result[1];
Now you have the input in two variables.
"I decided to use ArrayList but I know the number of names that will be inputed (6), is there a more appropriate array method to use?"
ArrayList is fine, but if the length is fixed, use can use a fixed size array.
Regarding OP update
You're doing it wrong, this should be like this:
ArrayList<String[]> list = new ArrayList<String[]>(6);
String[] splitted;
String line;
for(int i=0;i<6;i++) {
line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
splitted = line.split("\\s+");
list.add(splitted);
}
for(int i=0;i<6;i++)
System.out.println(Arrays.deepToString(list.get(i))); //Will print all 6 pairs
You should create an ArrayList that contains a String array that will represent the input (since the user enters pair as an input). Now, all what you have to do is to insert this pair to the ArrayList.
What you can do is store the input from you JOptionPane in a String, and then split the String into an array to store the name and degree entered. For example:
String value = null;
value = JOptionPane.showInputDialog("Please enter tutor name and
their highest earned degree.");
String[] tokens = value.split(" ");//if you input name followed by space followed by degree, this splits the input by the space between them
System.out.println(tokens[0]);//shows the name
System.out.println(tokens[1]);//shows the degree
Now you can use tokens[0] to add the name to your List.