I've partially coded a program that's supposed to read a file of a list of cities, determine which are the longest and shortest name-wise, and output it into a separate file. However, I can't figure out why from the list of cities, it's not giving me the longest and shortest
import java.io.*;
import java.util.Scanner;
public class testing
{
public static void main(String args[])throws IOException
{
Scanner sc = new Scanner(new File("C:/code/names.txt"));
String city="", longest="", shortest="";
int len=0, min = 0, max = 0;
while(sc.hasNext())
{
city= sc.nextLine();
len= city.length();
if(len>max)
{
max=len;
longest=city;
}
if(len<min)
{
min=len;
shortest=city;
}
}
System.out.println(longest + " is the longest name.");
System.out.println(shortest + " is the shortest name.");
}
}
The list of cities in the text file are Alexandria, Virginia, Aurora , Illinois, Austin, Kinikinik, Texas, Boston, Massachusetts, Chandler, Arizona, Charlotte, North Carolina, Dallas, Dayton, Ohio, Elizabeth, New Jersey, Eugene, Oregon, Gilbert, Houston, Jackson, Mississippi, and Glenelg, and the output I always get is Massachusetts for longest and a blank/nothing for shortest, which is incorrect. I was also wondering how/where can I incorporate this piece of code into my code
import java.io.*;
import java.util.Scanner;
public class palindrome_demo
{
public static void main(String args[]) throws IOException
{
String s="";
Scanner sc= new Scanner(new File("c:/code/names.txt"));
while(sc.hasNextLine())
{
String word = sc.nextLine();
for(int i = word.length() - 1; i >= 0; i--)
{
s = s + word.charAt(i);
}
if (word.equalsIgnoreCase(s))
{
System.out.println(word + " is a palindrome");
}
s="";
}
sc.close();
}
}
It finds the palindrome in the file perfectly, but I'm not sure where to place it without it looping infinitely.
TLDR; My code isn't giving me the correct longest and shortest word when reading from a file, and I'd like to know where can I place my separate code into my first code, so that they can both run together. In the end, I'd also like to output all of this info(longest,shortest, and palindrome words) to a separate txt, but I'm not sure how.
*EDIT: anupamD's response helped solve my string reading problem. I'd still like to know where can I place my palidrome code in my length code.