How to I create an adjacency matrix out of this? - java

try to turn in this information into adjacency matrix but confused on how
import java.util.*;
public class graph {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int adjMatrix[][];
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
while(stdin.hasNext()) {
String[] str = stdin.nextLine().split("[\\s,]+");
ArrayList<Integer> inner = new ArrayList<Integer>();
for(int i = 0; i < str.length; i++) {
inner.add(Integer.parseInt(str[i]));
}
list.add(inner);
}
}
}
storing the information in an arraylist of arraylist. help on how to make this an adjacency matrix would be appreciated.

If the data you are extracting from stdin are valid you should be able to construct adjacency matrix like this :
public static void main(String[] args) {
String[] input = "1 2 5 \n3 4 2 \n".split("\n");
int adjMatrix[][];
int max = 0;
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<input.length; i++) {
String[] str = input[i].split("[\\s,]+");
ArrayList<Integer> inner = new ArrayList<Integer>();
for(int j = 0; j < str.length; j++) {
inner.add(Integer.parseInt(str[j]));
}
max = Math.max(Math.max(max, inner.get(0)), inner.get(1));
list.add(inner);
}
int[][] adjacencyMatrix = new int[max+1][max+1];
for(int i=0; i<list.size(); i++) {
int source = list.get(i).get(0);
int dest = list.get(i).get(1);
adjacencyMatrix[source][dest] += 1;
}
for(int i=0; i<adjacencyMatrix.length; i++) {
for(int j=0; j<adjacencyMatrix[i].length; j++) {
System.out.print(adjacencyMatrix[i][j]);
}
System.out.println("");
}
}
I did not take the weight in account since it does not seems to be revelant for adjacency matrix

public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int nodeCount = 0;
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
while(stdin.hasNext()) {
String[] str = stdin.nextLine().split("[\\s,]+");
ArrayList<Integer> inner = new ArrayList<Integer>();
for(int i = 0; i < str.length; i++) {
int value = Integer.parseInt(str[i]);
inner.add(value);
if(value > nodeCount && i != str.length - 1){
nodeCount = value;
}
}
list.add(inner);
}
int adjMatrix[][] = new int[nodeCount + 1][nodeCount + 1];
for(ArrayList<Integer> inner : list){
adjMatrix[inner.get(0)][inner.get(1)] += 1;
}
for(int i = 0; i < nodeCount; i++){
for(int j = 0; j < nodeCount; j++){
System.out.print(adjMatrix[i][j] + " ");
}
System.out.println();
}
}

Maybe you should use something like this as a starting point.
public class AdjacencyMatrix {
public static void main(String... args) {
List<Edge> edges = readFromStdIn();
Graph graph = new Graph(edges);
int[][] adjacencyMatrix = graph.getAdjacencyMatrix();
printMatrix(adjacencyMatrix);
}
private static List<Edge> readFromStdIn() {
List<Edge> edges = new ArrayList<Edge>();
try (Scanner scanner = new Scanner(System.in)) {
boolean readOn = true;
while (scanner.hasNext() && readOn) {
String[] strings = scanner.nextLine().split("[\\s,]+");
if (strings.length == 3) {
edges.add(new Edge(Integer.parseInt(strings[0]), Integer.parseInt(strings[1]),
Integer.parseInt(strings[2])));
} else {
readOn = false;
}
}
}
return edges;
}
private static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
class Edge {
final int source;
final int destination;
final int weight;
Edge(int source, int destination, int weight) {
this.source = source;
this.destination = destination;
this.weight = weight;
}
}
class Graph {
final List<Edge> edges;
Graph(List<Edge> edges) {
this.edges = edges;
}
public int[][] getAdjacencyMatrix() {
int n = getNodeCount();
int[][] matrix = new int[n][n];
for (Edge e : edges) {
matrix[e.source][e.destination] = 1;
// directed graph?
matrix[e.destination][e.source] = 1;
}
return matrix;
}
int getNodeCount() {
int maxNodeNumber = 0;
for (Edge edge : edges) {
if (edge.source > maxNodeNumber) {
maxNodeNumber = edge.source;
}
if (edge.destination > maxNodeNumber) {
maxNodeNumber = edge.destination;
}
}
return maxNodeNumber + 1;
}
}
It introduces some classes to add some structure to the code, avoids lists when the array length is known.
Besides: it will not create entries with values greater than 1, if edges are contained multiple times.

Related

The .length function always returns 0

For some reason the .length function in my "Bubblesort()" method always returns zero. Could someone explain why the value of 0 is returned?
import java.util.Random;
import java.util.Scanner;
public class BubbleSortS {
static int Count;
static Integer org[];
static Integer list[] = { };
public static void main(String[] args) {
Scanner eingabewert = new Scanner(System.in);
System.out.print("Wie viele Zahlen sollen sortiert werden: ");
Count = eingabewert.nextInt();
Integer list[] = intList();
org = list.clone();
Bubblesort();
System.out.print("Original: ");
printArray(org);
System.out.print("\nSortiert: ");
printArray(list);
eingabewert.close();
}
public static void printArray(Integer[] toPrint) {
for(int i = 0; i < toPrint.length; i++) {
if(i < toPrint.length-1)
{
System.out.print(toPrint[i]+ ", ");
} else {
System.out.print(toPrint[i]);
}
}
}
public static Integer[] intList() {
Integer[] nums = new Integer[Count];
Random rand = new Random();
for (int i = 1; i <= nums.length; i++)
{
nums[i - 1] = rand.nextInt((int) (System.currentTimeMillis()/1000000000));
}
return nums;
}
public static void Bubblesort() {
int n = list.length;
int temp = 0;
boolean swapped;
do{
swapped = false;
for (int i=0; i < n-1; ++i)
{
if (list[i] > list[i+1])
{
temp = list[i+1];
list[i+1] = list[i];
list[i] = temp;
swapped = true;
}
}
n = n-1;
} while (swapped);
}
}
Output:
Wie viele Zahlen sollen sortiert werden: 5
Original: 443, 322, 183, 574, 108
Sortiert: 443, 322, 183, 574, 108
You should be passing arguments to your methods, instead of declaring static fields. What is happening in this case is called shadowing. You are calling the length method on the un-initialized static variable, instead of your initialized list.
You can rewrite your program like this:
import java.util.Random;
import java.util.Scanner;
public class Bubblesort {
public static void main(String[] args) {
Scanner eingabewert = new Scanner(System.in);
System.out.print("Wie viele Zahlen sollen sortiert werden: ");
int count = eingabewert.nextInt();
Integer list[] = intList(count);
Integer org[] = list.clone();
bubblesort(list);
System.out.print("Original: ");
printArray(org);
System.out.print("\nSortiert: ");
printArray(list);
eingabewert.close();
}
public static void printArray(Integer[] toPrint) {
for(int i = 0; i < toPrint.length; i++) {
if(i < toPrint.length-1)
{
System.out.print(toPrint[i]+ ", ");
} else {
System.out.print(toPrint[i]);
}
}
}
public static Integer[] intList(int count) {
Integer[] nums = new Integer[count];
Random rand = new Random();
for (int i = 1; i <= nums.length; i++)
{
nums[i - 1] = rand.nextInt((int) (System.currentTimeMillis()/1000000000));
}
return nums;
}
public static void bubblesort(Integer list[]) {
int n = list.length;
int temp;
boolean swapped;
do{
swapped = false;
for (int i=0; i < n-1; ++i)
{
if (list[i] > list[i+1])
{
temp = list[i+1];
list[i+1] = list[i];
list[i] = temp;
swapped = true;
}
}
n = n-1;
} while (swapped);
}
}

Hackerrank (Java) MAXIMUM LENGTH SUBSTRING - timeout error

Link to this problem:
https://www.hackerrank.com/contests/takneek/challenges/maximum-length-substring/problem
The code passes the initial test case but then times out when I go to submit on hacker rank for much larger strings. I have a feeling it's the algorithm I'm using for the unique substrings, how do I cut down this time into something efficient?
My code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedList<Integer> kList = new LinkedList<Integer>();
LinkedList<String> setout = new LinkedList<String>();
LinkedList<String> setLex = new LinkedList<String>();
//Get the original text
String text = in.nextLine();
//Get n from the file
int n = in.nextInt();
//Get the next needed items for comparison and order
for (int i = 0; i < n; i++) {
kList.add(in.nextInt());
}
setout = getAllUniqueSubset(text);
setLex = sortLexographically(setout);
int findMax = findMaximumSub(setLex, kList, 0);
// System.out.println(setLex);
System.out.println(findMax);
}
//Get the unique subset to begin with and return it
public static LinkedList<String> getAllUniqueSubset(String text) {
LinkedList<String> set = new LinkedList<String>();
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < text.length() - i; j++) {
String elem =text.substring(j, j + (i+1));
if (!set.contains(elem)) {
set.add(elem);
}
}
}
return set;
}
public static LinkedList<String> sortLexographically(LinkedList<String> setout){
for(int i = 0; i < setout.size()-1; ++i) {
for (int j = i + 1; j < setout.size(); ++j) {
if (setout.get(i).compareTo(setout.get(j)) > 0) {
String testLex = setout.get(i);
setout.set(i, setout.get(j));
setout.set(j, testLex);
}
}
}
return setout;
}
public static int findMaximumSub(LinkedList<String> setLex, LinkedList<Integer> kList, int maxCheck){
for (int i = 0; i < kList.size()-1; i++) {
if (maxCheck < setLex.get(kList.get(i)).length()) {
maxCheck = setLex.get(kList.get(i)).length();
}
}
return maxCheck;
}
}

I can't solve the String index exception problem in Dijkstra algorithm program

So it's the old Exception in thread "main" java.lang.StringIndexOutOfBoundsException problem.
More precisely, (String index out of range: -1)
Obviously it's copy and paste code, otherwise I wouldn't be having problems dealing with this.
Here is the whole code, the relevant snippet is below:
import java.util.*;
import java.io.*;
public class Proj4
public static String[] cities;
public static int[][] mileage;
public static boolean[] visited;
public static int[] prev;
public static int[] dist;
public static int size;
public static void main(String[] args) throws IOException
{
Scanner fin = new Scanner(new File("cities.txt.txt"));
Scanner in = new Scanner(System.in);
size = Integer.parseInt(fin.nextLine());
cities = new String[size];
mileage = new int[size][size];
visited = new boolean[size];
prev = new int[size];
dist = new int[size];
for(int i = 0; i < size; ++i)
{
cities[i] = fin.nextLine();
}
String line = null, city1, city2;
int distance;
for(int i = 0; i < size; ++i)
{
for(int j = 0; j < size; ++j){
mileage[i][j] = Integer.MAX_VALUE;
}
}
Here is the relevant snippet:
while(fin.hasNextLine())
{
line = fin.nextLine();
city1 = line.substring(0, line.indexOf(','));
city2 = line.substring(line.indexOf(',') + 1, line.indexOf(':'));
distance = Integer.parseInt(line.substring(line.indexOf(':') + 1));
mileage[index(city1)][index(city2)] = distance;
mileage[index(city2)][index(city1)] = distance;
}
while(true)
{
System.out.print("Enter the first city: ");
city1 = in.nextLine();
System.out.print("Enter the second city: ");
city2 = in.nextLine();
int startInd = index(city1);
int stopInd = index(city2);
if(startInd == -1 || stopInd == -1){
System.out.println("Invalid city name(s)");
}
else
{
dijkstra(city1);
print(city1, city2);
}
System.out.print("Another pair? (Y/N): ");
line = in.nextLine();
if(line.equalsIgnoreCase("N"))
{
break;
}
}
}
public static int index(String name)
{
for(int i = 0; i < cities.length; ++i)
{
if(cities[i].equalsIgnoreCase(name))
{
return i;
}
}
return -1;
}
public static void init(String start) {
int startInd = index(start);
for(int i = 0; i < size; ++i){
dist[i] = Integer.MAX_VALUE;
prev[i] = -1;
visited[i] = false;
}
dist[startInd] = 0;
}
public static int minIndex()
{
int minInd = -1, minDistance = Integer.MAX_VALUE;
for(int i = 0; i < size; ++i)
{
if(!visited[i] && dist[i] < minDistance)
{
minInd = i;
minDistance = dist[i];
}
}
return minInd;
}
public static boolean done()
{
for(int i = 0; i < size; ++i)
{
if(!visited[i])
{
return false;
}
}
return true;
}
public static void print(String start, String stop)
{
int startInd = index(start);
int stopInd = index(stop);
List<String> intCities = new ArrayList<>();
int prevInd = prev[stopInd];
while(prevInd != startInd)
{
intCities.add(cities[prevInd]);
prevInd = prev[prevInd];
}
System.out.print(start + "->");
for(int i = intCities.size() - 1; i >= 0; --i)
{
System.out.print(intCities.get(i) + "->");
}
System.out.println(stop + ", distance " + dist[stopInd] + " miles");
}
public static void dijkstra(String start)
{
init(start);
while(!done())
{
int x = minIndex();
visited[x] = true;
for(int y = 0; y < size; ++y)
{
if(!visited[y])
{
if(mileage[x][y] != Integer.MAX_VALUE)
{
int dy = dist[x] + mileage[x][y];
if(dy < dist[y])
{
dist[y] = dy;
prev[y] = x;
}
}
}
}
}
}
}
Apologies for the poor formatting, this is my first time asking here. Thanks!
It is possible that your input string doesnt have ','(comma) or ':'(colon), so that indexOf() method will return -1 in your relevant snippet code section which results in java.lang.StringIndexOutOfBoundsException String index out of range: -1 .
Check your input by enabling debugger on line line = fin.nextLine();
OR add print statement in after taking input System.out.println(line)

Out of bounds exception on java array sorting even and odd integers?

The error occurs at odd[count1] = value.
This program should basically print a 2d array with evens being less than odds and then both sorted from lowest to highest.
public static void main(String args[]) {
int[][] arzarehard = {{12,13,17}, {38,44,13}, {54,37,15}, {35,25,17}};
oddSort(arzarehard);
}
public static void oddSort(int[][] thots) {
int [] even = new int[thots.length + thots[0].length];
int [] odd = new int[thots.length + thots[0].length];
for (int i=0; i<even.length; i++) {
even[i] = Integer.MAX_VALUE;
}
for(int i=0; i<odd.length; i++) {
odd[i] = Integer.MAX_VALUE;
}
int count = 0;
int count1 = 0;
//try non for each - possibly causing problem
for (int[] row : thots) {
for(int value : row) {
if (value%2==0) {
even[count] = value;
count++;
} else {
//odd.add(value); - adds it to the end and then concatinate
odd[count1] = value;
count1++;
}
}
}
//even bubble sort
for(int j=0; j<odd.length; j++) {
for(int i=0; i<odd.length-1; i++) {
if(odd[i]>odd[i+1]) {
int temp = odd[i];
int tempTwo = odd[i+1];
odd[i] = tempTwo;
odd[i+1] = temp;
}
}
}
//odd bubble sort
for(int j=0; j<even.length; j++) {
for(int i=0; i<even.length-1; i++) {
if(even[i]>even[i+1]) {
int temp = even[i];
int tempTwo = even[i+1];
even[i] = tempTwo;
even[i+1] = temp;
}
}
}
int e = 0;
int o = 0;
for(int j=0; j<thots.length; j++) {
for(int i=0; i<thots[0].length; i++) {
if(e<even.length) {
thots[j][i] = even[e];
e++;
} else {
thots[j][i] = odd[o];
o++;
}
}
}
for(int[] whatever : thots) {
for( int value : whatever) {
System.out.print(value + " ");
}
System.out.println();
}
}
The basic idea is that I am inputting a 2d array. Then breaking that array into an even and odd array. Then sorting both and putting them back together to print.
since in you code size of array even[] and odd[] is 7.it should be sufficient enough to hold all the values.when you assigh value 17 to odd[7] this will through ArrayIndexOutOfBoundException.
change code-
int [] even = new int[thots.length + thots[0].length];
int [] odd = new int[thots.length + thots[0].length];
to-
int [] even = new int[thots.length * thots[0].length];
int [] odd = new int[thots.length * thots[0].length];
Use following code-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class BinarySearch{
public static void main(String args[]) {
//System.out.println(Integer.MAX_VALUE);
int[][] arzarehard = {{12,13,17}, {38,44,13}, {54,37,15}, {35,25,17}};
oddSort(arzarehard);
}
public static void oddSort(int[][] thots) {
List<Integer> evenList=new ArrayList<Integer>();
List<Integer> oddList=new ArrayList<Integer>();
for (int[] row : thots) {
for(int value : row) {
if (value%2==0) {
evenList.add(value);
} else {
oddList.add(value);
}
}
}
Collections.sort(evenList);
Collections.sort(oddList);
int i=0;
int j=0;
for(Integer even:evenList){
if(j==thots[0].length){
i++;
j=0;
}
thots[i][j]=even;
j++;
}
for(Integer odd:oddList){
if(j==thots[0].length){
i++;
j=0;
}
thots[i][j]=odd;
j++;
}
for(int[] whatever : thots) {
for( int value : whatever) {
System.out.print(value + " ");
}
System.out.println();
}
}
}

Sort strings in an array based on length

I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
String[] sortedArr = new String[arr.length];
for(int i=0;i<sortedArr.length;i++)
{
sortedArr[i] = compareArrayElements(arr);
}
System.out.println("The strings in the sorted order of length are: ");
for(String sortedArray:sortedArr)
{
System.out.println(sortedArray);
}
}
public static String compareArrayElements(String[] arr) {
String temp = null;
for(int i=0;i<arr.length-1;i++)
{
temp = new String();
if(arr[i].length() > arr[i+1].length())
temp = arr[i+1];
else
temp = arr[i];
}
return temp;
}
}
If you really want to learn Java: use a Comparator. Any other way is bad Java code.
You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.
For your actual code, here are some hints:
Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.
Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".
Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.
You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.
Use bubble sort, but instead of comparing ints, just compare String lengths.
I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.
Good luck.
References:
Bubble sort in Java
Sorting an array of strings
Implement bubbleSort() and swap(). My implementations mutate the original array, but you can modify them to make a copy if you want.
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
bubbleSort(arr);
System.out.println("The strings in the sorted order of length are: ");
for (String item : arr) {
System.out.println(item);
}
}
// Mutates the original array
public static void bubbleSort(String[] arr) {
boolean swapped = false;
do {
swapped = false;
for (int i = 0; i < arr.length - 1; i += 1) {
if (arr[i].length() > arr[i + 1].length()) {
swap(arr, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
// Mutates the original array
public static void swap(String[] arr, int index0, int index1) {
String temp = arr[index0];
arr[index0] = arr[index1];
arr[index1] = temp;
}
}
Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string
import java.util.*;
class strings {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> a = new ArrayList<String>(2);
System.out.println("Start entering your words or sentences.");
System.out.println("Type stop to stop.");
String b;
int c = 0, d;
do {
b = in.nextLine();
b = b.trim();
a.add(b);
c++;
}
while (!b.equalsIgnoreCase("stop"));
if (c > 1)
a.remove(a.size() - 1);
System.out.println("Choose the sort you want. Type the corresponding
number");
System.out.println("1. Ascending");
System.out.println("2. Descending");
int sc=in.nextInt();
switch(sc) {
case 1: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] > sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
case 2: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] < sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
}
}
}
For instance, the following:
ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);
By lambda:
str.sort((String s1, String s2) -> s1.length() - s2.length());
By static Collections.sort
import static java.util.Collections.sort;
sort(str, new Comparator<String>{
#Override
public int compare(String s1, String s2) {
return s1.lenght() - s2.lenght()
}
});
Both options are implemented by default sort method from List interface
Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]
we can use Comparator for sorting the given string array to sort it based on length with the following code:
String[] sortByLength(String[] inputArray) {
Arrays.sort(inputArray, new Comparator<String>(){
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
});
return inputArray;
}
//sort String array based on length
public class FirstNonRepeatedString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your String");
String str = in.nextLine();
String arrString[] = str.split("\\s");
arrString = sortArray(arrString);
System.out.println("Sort String ");
for(String s:arrString){
System.out.println(s);
}
}
private static String[] sortArray(String[] arrString) {
int length = arrString.length;
String s;
for (int i = 0; i < length ; i++) {
s= new String();
for(int j = 0; j < length; j++ ){
if(arrString[i].length()< arrString[j].length()){
s = arrString[i];
arrString[i] = arrString[j];
arrString[j] = s;
}
}
}
return arrString;
}
}
import java.util.*;
public class SortStringBasedOnTheirLength {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.nextLine();
String[] str1=str.split("\\s");
for(int i=0;i<str1.length;i++)
{
for(int j=i+1;j<str1.length;j++)
{
if(str1[i].length()>str1[j].length())
{
String temp= str1[i];
str1[i]=str1[j];
str1[j]=temp;
}
}
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]+" ");
}
}
}

Categories

Resources