У меня такой вопрос, как мне найти самую короткую строку, я знаю про например:
str.length; , но в этом случае сработает ли list.get(0).length например, или нужно как то по другому изощраться, я бы сделал так:
for( int i =0; i < list.size(); i++){
int max = list.get(0).length;
string str = list.get(0);
if(list.get(i).length > max){
max = list.get(i).length;
str = list.get(i);}
System.out.println(str);
Но что то мне посдказывает, что так ничего не будет работать, и вот тут и вопрос, как сравнивать длинны строк?
package com.javarush.task.task07.task0709;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
Выражаемся покороче
*/
public class Solution {
public static void main(String[] args) throws Exception {
//напишите тут ваш код
BufferedReader reader = new BufferedReader( new InputStreamReader(System.in));
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < list.size(); i++)
{
}
}
}
2 / 2 / 0 Регистрация: 04.03.2014 Сообщений: 55 |
|
1 |
|
Найти самую короткую строку, вывести эту строку и ее длину31.03.2014, 23:55. Показов 20776. Ответов 1
Всем привет! помогите пожалуйста решить несколько задач 1 . Ввести n строк с консоли , найти самую короткую строку. Вывести эту строку и ее длину.
0 |
balerin 0 / 0 / 2 Регистрация: 19.12.2013 Сообщений: 3 |
||||
03.04.2014, 05:31 |
2 |
|||
Решение
0 |
Ok so the goal is to print the smallest length string ( for example, if input is «co», «college», «colleges», «university» I want it to print out co.
I’ve tried the college.compareTo( ____ ); as well as a couple other things but I can’t seem to get it to print it out.
Also it isn’t anything fancy (if you’ve read/have head first java 2nd edition then we are on chapters 5/6)
I’d rather if you can link me to a video that will show the process of what needs to be done with an explanation but anything is helpful :s been staring at this coding for a couple weeks and kinda went brain dead on it…
This is what I have so far (accepts strings from user);
ArrayList <String> colleges = new ArrayList <String> ( ) ;
String input;
Scanner scan = new Scanner(System.in) ;
while (true) {
System.out.println("Please enter your college (Press Enter twice to quit) ");
input = scan.nextLine();
if (input.equals ("")) {
break;
}
else {
colleges.add(input.toUpperCase () );
}// end of if else statement
}// end of while loop
System.out.println("The following " + colleges.size() + " colleges have been entered:");
for ( String college : colleges) {
System.out.println("n" + college );
System.out.println("Character count: " + college.length( ) );
}// end of for each loop
j4rey
2,55220 silver badges34 bronze badges
asked Nov 25, 2014 at 7:51
These are the steps you need:
- Create a custom
Comparator<String>
to sort strings based on their length. - Get the shortest string from your list by using your custom comparator with the
Collections.min()
method.
In its most compact version, your code could look something like this (assuming there are no null
strings in the list):
String shortest = Collections.min(colleges, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
answered Nov 25, 2014 at 7:57
Robby CornelissenRobby Cornelissen
90.6k22 gold badges132 silver badges156 bronze badges
2
You can use the following logic to print the smallest string in given arrayList
string smallString = "";
for ( String college : colleges) {
if(smallString.length() == 0 && college.length() != 0)
{
smallString = college ;
}
else if(college.length() < smallString.length() && college.length() != 0)
{
smallString = college;
}
}
println("Smallest string is: " + smallString );
answered Nov 25, 2014 at 7:58
Sridhar DDSridhar DD
1,9721 gold badge10 silver badges17 bronze badges
6
public static String SmallestString(ArrayList <String> collegeArray){
String smallest = "";
System.out.println("");
for(String string :collegeArray){
//if input-string is null or empty
if(string == null || string.trim() == "" || string.trim().length()==0){
System.out.println("Emtpy String Encountered");
continue;
}
if(smallest == ""){
smallest = string;
continue;
}
if(string.length() < smallest.length()){
smallest = string;
}
}
return smallest;
}
Call it with:
System.out.println("nSmallest String: " + SmallestString(colleges));
answered Nov 25, 2014 at 10:36
j4reyj4rey
2,55220 silver badges34 bronze badges
самая короткая строка
Apr 26th, 2016
579
0
Never
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
-
package com.javarush.test.level0.lesson0.task0;
-
import java.io.BufferedReader;
-
import java.io.InputStreamReader;
-
import java.util.ArrayList;
-
/* Самая короткая строка
-
1. Создай список строк.
-
2. Считай с клавиатуры 5 строк и добавь в список.
-
3. Используя цикл, найди самую короткую строку в списке.
-
4. Выведи найденную строку на экран.
-
5. Если таких строк несколько, выведи каждую с новой строки.
-
*/
-
public class Solution {
-
public static void main(String[] args) throws Exception {
-
ArrayList<String> arrayList = new ArrayList<String>();
-
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
-
for (int i = 0; i < 5; i++) {
-
arrayList.add(reader.readLine());
-
}
-
printIndexesByWidth(arrayList, getShortestLength(arrayList));
-
}
-
public static int getShortestLength(ArrayList<String> input) {
-
int result = input.get(0).length();
-
for (String element : input) {
-
if (element.length() < result) {
-
result = element.length();
-
}
-
}
-
return result;
-
}
-
public static void printIndexesByWidth(ArrayList<String> input, int width) {
-
for (String element : input) {
-
if (element.length() == width) {
-
System.out.println(element);
-
}
-
}
-
}
-
}
Permalink
Cannot retrieve contributors at this time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.InputMismatchException; | |
import java.util.Scanner; | |
/** | |
* Created by roman on 9/3/15. | |
* | |
* 1. Ввести n строк с консоли, найти самую короткую строку. Вывести эту строку и ее длину. | |
* | |
*/ | |
public class main | |
{ | |
public static void main(String[] args) | |
{ | |
int n; // число строк | |
while ( true ) // ввод числа строк | |
{ | |
System.out.println(«Введите число строк»); | |
Scanner sc1 = new Scanner(System.in); | |
try | |
{ | |
n = sc1.nextInt(); | |
if (n > 0) break; | |
} | |
catch(InputMismatchException fg) | |
{ | |
// если введенное значение не является числом | |
System.out.print(«Вы ввели не число. « ); | |
} | |
} | |
// считывание строк из консоли | |
Scanner sc2 = new Scanner(System.in); | |
String shortestString = null; // самая короткая строка0 | |
for (int i = 0; i < n; i++) | |
{ | |
System.out.println( «Введите строку №» + (i+1)); | |
String str = sc2.nextLine(); | |
if (i == 0) { | |
shortestString = str; | |
} else if (shortestString.length() > str.length()) { | |
// если введенная строка короче, чем самая короткая, то обновляем самую короткую | |
shortestString = str; | |
} | |
} | |
System.out.println(«Длинна самой короткой строки: «+shortestString.length()); | |
System.out.println(«Самая короткая строка: «+shortestString); | |
} | |
} |