Find and compare lengths of individual words in a string - java

So I need to write a program that reads a sentence of five words, and finds the longest word in the sentence and displays it. If there happen to be two equally large words, it just displays the first largest word.
import java.util.Scanner;
public class Longest_Word {
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
String line;
String q, w, e, r, t;
System.out.print("Enter a five word sentence: ");
line = in.nextLine();
Scanner scanner = new Scanner(line);
q = scanner.next();
w = scanner.next();
e = scanner.next();
r = scanner.next();
t = scanner.next();
System.out.println(q + " " + r);
}
}
You can probably tell where I'm stuck. I really don't know how to compare these words. The first thing that came to mind was to use if/else to compare them individually, using line.length().
Can't use array, .split, or loops (sadly).

Show your teacher this!
Stream.generate(scanner::next).limit(5)
.max(Comparator.comparing(String::length))
.ifPresent(System.out::println);

if/else and loops are the same for this problem.
String largerString = q;
if(w.length()>largerString.length())
{
largerString = w;
}
if(e.length()>largerString.length())
{
largerString = e;
}
if(r.length()>largerString.length())
{
largerString = r;
}
if(t.length()>largerString.length())
{
largerString = t;
}
System.out.println(largerString);

Given the constraints I suggest you use if statements as you assumed.
import java.util.Scanner;
public class Longest_Word {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line;
String q, w, e, r, t;
System.out.print("Enter a five word sentence: ");
line = in.nextLine();
Scanner scanner = new Scanner(line);
q = scanner.next();
String longest = q;
w = scanner.next();
if (w.length()>longest.length())
longest = w;
e = scanner.next();
if (e.length()>longest.length())
longest = e;
r = scanner.next();
if (r.length()>longest.length())
longest = r;
t = scanner.next();
if (t.length()>longest.length())
longest = t;
System.out.println(longest);
}
}

Read all the values in list and use Java Streams to find longest String
String logestStr = list.stream().max(Comparator.comparing(String::length)).get();

If you just want to show the largest word, you can do it as follows, and it will be dynamic too in case the number of words is more than 5.
Scanner in = new Scanner(System.in);
String line;
String q, w, e, r, t;
System.out.println("Enter a five word sentence: ");
line = in.nextLine();
Scanner scanner = new Scanner(line);
String maxWord = "";
while(scanner.hasNext()){
String word =scanner.next();
if(word.length()>maxWord.length())
maxWord = word;
}
System.out.println(maxWord);

Related

Java scanner test for empty line

I'm using Scanner to read 3 lines of input, the first two are strings and the last one is int.
I'm having an issue when the first line is empty and I don't know how to get around it. I have to do this:
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
encrypt(operation,line,index);
But when the first line is empty I get an error message.
I tried the following to force a loop until I get a non empty next line but it does not work either:
while(sc.nextLine().isEmpty){
operation = sc.nextLine();}
Anybody has a hint please ?
A loop should work, though you must actually call the isEmpty method and scan only once per iteration
String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());
You could also use sc.hasNextLine() to check if anything is there
Try this:
Scanner scanner = new Scanner(reader);
String firstNotEmptyLine = "";
while (scanner.hasNext() && firstNotEmptyLine.equals("")) {
firstNotEmptyLine = scanner.nextLine();
}
if (!scanner.hasNext()) {
System.err.println("This whole file is filled with empty lines! (or the file is just empty)");
return;
}
System.out.println(firstNotEmptyLine);
Then you can read the other two lines after this firstNotEmptyLine.
Please try this.
Scanner sc = new Scanner(System.in);
String operation = null;
String line = null;
int index = 0;
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
operation = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
line = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
index = Integer.parseInt(nextLine);
break;
}
}
System.out.println(operation + " " + line + " " + index);
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
test(operation,line,index);
}
public static void encrypt(String a,String b,int c){
System.out.println("first :"+a+" Second :"+b+" Third :"+c);
}
I don't see any error here. It compiles well.

How to take space separated input in Java using BufferedReader?

How to take space separated input in Java using BufferedReader?
Please change the code accordingly, i wanted the values of a, b, n as space seperated integers and then I want to hit Enter after every test cases.
Which means first i'll input the number of test cases then i'll press the Enter key. Then i input the vale of a then i'll press Space, b then again Space then i'll input the value of n, then i'll press the Enter key for the input for the next testcase.
I know that this can be done easily through Scanner but i don't wanna use it because it throws TLE(Time Limit Extended) error on online judges.
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputString = br.readLine();
int testCases = Integer.parseInt(inputString);
double a,b,n,j,t=1;
int i;
int ans [] = new int[testCases];
for(i=0;i<testCases;i++)
{
inputString = br.readLine();
a = Double.parseDouble(inputString);
inputString = br.readLine();
b = Double.parseDouble(inputString);
inputString = br.readLine();
n = Double.parseDouble(inputString);
for(j=0;j<n;j++)
{
if(t==1)
{
a*=2;
t=0;
}
else if(t==0)
{
b*=2;
t=1;
}
}
if(a>b)
ans[i]=(int)(a/b);
else
ans[i]=(int)(b/a);
t=1;
}
for(i=0;i<testCases;i++)
System.out.println(ans[i]);
}catch(Exception e)
{
return;
}
}
First read the number of input lines to be read.
Then parse each line and get the String.
Though I have not added the NumberFormatException handling, but it's a good idea to have that.
Change your for loop like this:
for(i=0;i<testCases;i++){
inputString = br.readLine();
String input[] = inputString.split("\\s+");
a = Double.parseDouble(input[0]);
inputString = br.readLine();
b = Double.parseDouble(input[1]);
inputString = br.readLine();
n = Double.parseDouble(input[2]);
for(j=0;j<n;j++){
if(t==1){
a*=2;
t=0;
}else if(t==0){
b*=2;
t=1;
}
}
if(a>b){
ans[i]=(int)(a/b);
}else{
ans[i]=(int)(b/a);
t=1;
}
}

Search a text file for two strings and display how many strings are in between

How can I use Binary search in Java to find how many strings lie between the two strings given by the user? I have a large text file to search through.
I was thinking ((word position 2 - word position 1)-1) would give the position from an array but I am not quite sure how to put it into code. I got stuck after checking the file for the words.
String[] allWords = new String[400000];
int wordCount = 0;
Scanner input = new Scanner(new File("C:\\text.txt"));
while (input.hasNext()) {
String word = input.next();
allWords[wordCount] = word;
wordCount++;
System.out.println(wordCount);
}
Scanner sc = new Scanner(new File("C:\\text.txt"));
while(sc.hasNextLine()){
String in = sc.nextLine();
System.out.println("Enter a string:");
Scanner sc2 = new Scanner(System.in);
String str = sc2.nextLine();
System.out.println("Enter a string:");
Scanner sc3 = new Scanner(System.in);
String str2 = sc3.nextLine();
if (str.contains(str)) {
System.out.println("yes");
}
if (str.contains(str2)) {
System.out.println("yes");
}
Your math is correct. As you have surmised, subtract one from the difference of the positions. If you have any issues with the code, post your attempt to your question.
You could try something like this pseudocode.
int start
int end
a = startingString
b = startingString
String[] lines = StringFromFile.split("\n");
for(x in lines)
if(x=a)
start = position of x
for(x in lines)
if(x=b)
end = position of x
String[] newLines = Arrays.copyOfRange(lines, start,end)
return newLines.length

How to multiply a String by an Integer?

I know there's some way to change a string into an integer but it's not really working out for me when I try to do it.
I was asked to take in an integer 'n' and 'a' string 's' and print 's' 'n' times
Here's my code and my main question / question is how do I easily turn the string into an integer so I can multiply the two together:
public static void main(String args[])
{
System.out.println("Enter the number of times you want to print a string");
Scanner n = new Scanner(System.in);
int x = n.nextInt();
System.out.println("Enter the string you want printed");
Scanner y = new Scanner(System.in);
String s = y.nextLine();
}
You only need one Scanner, and if I understand your question then you might use a loop like, also an int n.
System.out.println("Enter the number of times you want to "
+ "print a string");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
for (int i = 0; i < n; i++) {
System.out.print(s);
}
System.out.println();
Of course, you could put the loop in a method like
private static String multiply(String str, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
Then you could call it like,
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
System.out.println(multiply(s, n));

Concatenate User Input JAVA

This is what I have so far. I want the program to print out the words the user inputs as a sentence. But
I don't know how I get that to happen with the code I have written so far.
ex: if you entered
Hello
World
done
The program should say: "Hello World"
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+word);
}
}
What you need it to store it in a variable which is declared outside the loop.
StringBuilder sentence=new StringBuilder();
do {
word = in.nextLine();
count++;
System.out.print(" "+word);
sentence.append(" "+word);
}
while (!word.equals(SENTINEL));
Then for printing use
System.out.println(sentence.toString());
You will need to create an additional string to "collect" all of the words that the user enters. The problem with your original is that you replace 'word' with the word entered. This should do the trick:
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
String sentence = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
sentence += " " + word;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+sentence);
}
}
You can read it by pieces and put them together using a StringBuffer - http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
StringBuffer sb = new StringBuffer();
do {
sb.append( in.next() );
count++;
}
while (!word.equals(SENTINEL));

Categories

Resources