java lexicographically sort three words - java

I'm new to the Java programming language and want to create a program that reads in three words using scanner class and lexicoggraphically order the three words doing this in the main method for example user enters Tom Harry Dick, answer should be Dick Harry and Tom.. I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void.
public class SortWords {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String firstWord;
String secondWord;
String thirdWord;
System.out.println("Enter three words seperated by white space");
firstWord = userInput.next();
System.out.println(firstWord);
secondWord = userInput.next();
System.out.println(secondWord);
thirdWord = userInput.next();
System.out.println(thirdWord);
}
}

Then try to read as an array elements then sort that array
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] strings = new String[3];
for (int i = 0; i < strings .length; i++)
{
System.out.println("Please enter name");
strings [i] = input.next();
}
}
Arrays.sort(strings);

"I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void."
This is incorrect.
First, we do not say an if statement 'returns anything', we say that it chooses to either execute its statement block or not (the one enclosed by { }) based on whether its condition (enclosed by ( )) evaluates to true or false. (Similar idea when else and else if are thrown in)
Second, this is not effected by the return type of the method it's in, since it has nothing to do with return.
You should use print and println statements to print out the results of your comparisons of the three strings, since this is the main method and there is no higher method to return to.

Related

How to limit the number of words when reading a line from standard input?

I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}

Write a program to receive input from user and check its spelling

I have written code to find if two strings are equal or not. The first string input should be given by the user and it should be compared with a second string which is predefined. But even when I am giving an input that is the same as the second string, the output is incorrect.
import java.util.Scanner;
public class correction {
public static void main(String[] args) {
int i,c=0;
String[] s1=new String[] {"F","R","I","E","N","D","S"};
String[] s2=new String[7];
System.out.println("enter a alphabet");
Scanner sc=new Scanner(System.in);
s2[0]=sc.next();
s2[1]=sc.next();
s2[2]=sc.next();
s2[3]=sc.next();
s2[4]=sc.next();
s2[5]=sc.next();
s2[6]=sc.next();
int length = s1.length;
for(i=0;i<length;i++)
{
if(s1.equals(s2[i]))
c++;
}
if(c==7)
System.out.println("right way");
else
System.out.println("wrong way");
}
}
I expected the output to be "right way" but the output is "wrong way". And c value is also 0.
You're currently comparing the entire array s1 with a specific letter in s2 in each iteration of your for loop. What you should be doing instead is to compare s1[i] with s2[i] like so,
int length = s1.length;
for(i=0;i<length;i++)
{
if(s1[i].equals(s2[i]))
c++;
}
if(c==7)
System.out.println("right way");
else
System.out.println("wrong way");
This way, you're now comparing each letter in s1 with each letter in s2, assuming you're only entering letters as input to s2.
Quick tips:
First, add a .lower() method to the .equals() method to avoid problems resulting from capital letters.
You are comparing the entire s1 array with an s2[i] value, you can change the s1 to s1[i].
New here so please ignore the crappy formatting.
s1 is a reference to an array, while s2[i] is reference to a String, which is why s1.equals(s2[i]) is evaluating to false, which is why c++ never runs.

While loop with a scanner never satisfies condition [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
public class ex1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Please enter a series of strings each followed by the enter key. When you'd like to end thr program simply type 'quit': \n");
Scanner scan = new Scanner(System.in);
ArrayList<String> inputList = new ArrayList<String>(); // creates a list to store user input
String input = scan.nextLine(); //takes the scanner input
while(input != "quit") { //makes sure its not equal to quit
//System.out.println(input);
inputList.add(input);
input = scan.nextLine();
}
scan.close();
System.out.println("The number of strings enetered was: " + inputList.size());
System.out.println("The strings you entered were as follows");
for (String i: inputList) {
System.out.println(i);
}
}
}
I'm trying to use the preceding code to take a series of inputs from a user using the enter key and if they enter quit I end the program. However the condition is never satisfied and the while loop never ends and I can't understand why
while(!input.equals("quit")) { //makes sure its not equal to quit
//System.out.println(input);
inputList.add(input);
input = scan.nextLine();
}
You should use equals method as shown above to compare strings. Java provides equals method to compare the contents of two strings. == and != operators are used in comparing object equalities.
a == b returns true if, and only if, a points to the same object as b
The equals method should be used, as the String class implements it so that, if a contains the same characters as b, it would returns true.
while (!input.equals("quit")) { ... }

Make Java Program Loop until x is entered?

I want to make my program loop until the user types in x instead of a number. I tried using a while statement but I do not know how to use it with multiple variables. Here is my code
public static void main(String[] args)
{
int denominatorOne = 1, numeratorOne = 1;
System.out.println("Welcome, type an \"x\" at any point to exit the program");
while (numeratorOne !=x)
{
Scanner in = new Scanner(System.in);
//Prompt the user for fraction one
System.out.print("Enter the first numerator (top number): ");
numeratorOne = in.nextInt();
System.out.print("Enter the first denominator (bottom number): ");
denominatorOne = in.nextInt();
}
}
The exact phrasing from my assignment is The program should run in loop and allow the user to exit with some special character input (e.g. x or X to exit)
First off, 'x' isn't a number and won't be accepted by nextInt or a comparison to 'x', you should trying checking to see if it has next int (in.hasNextInt()) and process depending. Besides the point, you can easily test two variables in a while loop. Assuming you set up the variables right to be chars:
do {
// scan code.
} while(!(numChar1.equals('x') && numChar2.equals('x')))
what you need to do is have a bool value that holds the loop and when have a if statement check for the keydown event in the loop
bool looping = true
while ( looping == true)
{
if (x button was pressed == true)
{looping = false
}
}
try changing it to
while(!numeratorOne.equals("x")){...}
You can just call the method over again in this case main();.
What I suggest however is to create a new method, in the method just checking the users input returning the input as a string. Then you can check the string in your main method, and if that's not the string you wanted then recall the method. Here's an example, please note I didn't use an IDE for this.
public String getMessage(){
Scanner input = System.in();
return input;
}
public void checkMessage(String wantedString){
if(!getMessage().equalsIgnoreCase(wantedString)){
System.out.println("Please retry");
checkMessage();
}
}
public static void main(String[] args){
checkMessage();
}

Check for value in array

I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.

Categories