I am getting a "No line found" exception when I run this. This is the only method in my project that gives me this error. Every other method uses the same code and parameters, but none of them encounter this error.
The method in question is findLargestPalindrome()
Exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at cs1410.TestClass.findLongestPalindrome(TestClass.java:51)
at cs1410.TestClass.main(TestClass.java:12)
import java.util.Scanner;
import java.util.StringTokenizer;
public class TestClass
{
static Scanner test = new Scanner("Hello world! This is my program.");
public static void main(String[] args)
{
System.out.println(findLongestPalindrome(test));
}
public static boolean isPalindrome(String s)
{
if(s.length() == 0)
{
return false;
}
int stringLength = s.length() -1;
if(stringLength == 0)
{
return false;
}
for(int i = 0; i < stringLength; i++)
{
if(s.charAt(i) == s.charAt(stringLength))
{
stringLength--;
}
else
{
return false;
}
}
return true;
}
public static String findLongestPalindrome(Scanner s)
{
int pLength = 0;
String largestPalindrome = "";
String currentToken;
if(s.nextLine().length() > 0)
{
String input = s.nextLine();
StringTokenizer inputTokens = new StringTokenizer(input);
while(inputTokens.hasMoreTokens())
{
currentToken = inputTokens.nextToken();
if(isPalindrome(currentToken) == true)
{
if(currentToken.length() > pLength)
{
pLength = currentToken.length();
largestPalindrome = currentToken;
}
}
}
}
else
{
return null;
}
return largestPalindrome;
}
}
When you access the Scanner in findLongestPalindrom() you only have one line in the Scanner ("Hello world! This is my program.") and you are trying to read two lines (you discard the first line),
if(s.nextLine().length() > 0) // <-- reads the line and advances
{
String input = s.nextLine(); // <-- there isn't another line.
should be something like
String input = s.nextLine();
if (!input.isEmpty()) {
// ...
or
String input = s.nextLine();
if (input.length() > 0) {
// ...
Every time you call Scanner.nextLine() you consume the line.
Related
So I am trying to create a program which takes a text file, creates an index (by line numbers) for all the words in the file and writes the index into the output file. Here is the main class:
import java.util.Scanner;
import java.io.*;
public class IndexMaker
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
String fileName;
// Open input file:
if (args.length > 0)
fileName = args[0];
else
{
System.out.print("\nEnter input file name: ");
fileName = keyboard.nextLine().trim();
}
BufferedReader inputFile =
new BufferedReader(new FileReader(fileName), 1024);
// Create output file:
if (args.length > 1)
fileName = args[1];
else
{
System.out.print("\nEnter output file name: ");
fileName = keyboard.nextLine().trim();
}
PrintWriter outputFile =
new PrintWriter(new FileWriter(fileName));
// Create index:
DocumentIndex index = new DocumentIndex();
String line;
int lineNum = 0;
while ((line = inputFile.readLine()) != null)
{
lineNum++;
index.addAllWords(line, lineNum);
}
// Save index:
for (IndexEntry entry : index)
outputFile.println(entry);
// Finish:
inputFile.close();
outputFile.close();
keyboard.close();
System.out.println("Done.");
}
}
The program contains two more classes: IndexEntry which represents one index entry, and the DocumentIndex class which represents the entire index for a document: the list of all its index entries. The index entries should always be arranged in alphabetical order. So the implementation for these two classes are shown below
import java.util.ArrayList;
public class IndexEntry {
private String word;
private ArrayList<Integer> numsList;
public IndexEntry(String w) {
word = w.toUpperCase();
numsList = new ArrayList<Integer>();
}
public void add(int num) {
if (!numsList.contains(num)) {
numsList.add(num);
}
}
public String getWord() {
return word;
}
public String toString() {
String result = word + " ";
for (int i=0; i<numsList.size(); i++) {
if (i == 0) {
result += numsList.get(i);
} else {
result += ", " + numsList.get(i);
}
}
return result;
}
}
import java.util.ArrayList;
public class DocumentIndex extends ArrayList<IndexEntry> {
public DocumentIndex() {
super();
}
public DocumentIndex(int c) {
super(c);
}
public void addWord(String word, int num) {
super.get(foundOrInserted(word)).add(num);
}
private int foundOrInserted(String word) {
int result = 0;
for (int i=0; i<super.size(); i++) {
String w = super.get(i).getWord();
if (word.equalsIgnoreCase(w)) {
result = i;
} else if (w.compareTo(word) > 0) {
super.add(i, new IndexEntry(w));
result = i;
}
}
return result;
}
public void addAllWords(String str, int num) {
String[] arr = str.split("[^A-Za-z]+");
for (int i=0; i<arr.length; i++) {
if (arr[i].length() > 0 ) {
addWord(arr[i], num);
}
}
}
}
When I run this program I'm getting an error and I'm not sure where the error came from.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:459)
at DocumentIndex.addWord(DocumentIndex.java:14)
at DocumentIndex.addAllWords(DocumentIndex.java:35)
at Main.main(Main.java:53)```
There is where the problem arises:
String line;
int lineNum = 0;
while ((line = inputFile.readLine()) != null)
{
lineNum++;
index.addAllWords(line, lineNum);
}
You add lineNum by 1 before executing the line after. At the last loop, lineNum will be 1 more than the maximum, because the loop starts at line 1, and it is 0 index based.
Instead, use:
String line;
int lineNum = 0;
while ((line = inputFile.readLine()) != null)
{
index.addAllWords(line, lineNum);
lineNum++;
}
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
isPailindrome(ori);
if (isPailindrome(ori))
System.out.println(ori + "is a Pailindrome");
else
System.out.println(ori + "is NOT a Pailindrome");
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
The code works perfectly I'm just confused how I will get it to work irrespective of the case
inputted by the user. For example aBba is a palindrome but It says it's not in the code I've done. I
would like any help if possible thanks.
You can convert all of the letters to lowerCase before you start the processing.
You can write your own function or use toLowerCase() String function.
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
ori = ori.toLowerCase();
isPailindrome(ori);
if (isPailindrome(ori))
}
System.out.println(ori + "is a Pailindrome");
} else {
System.out.println(ori + "is NOT a Pailindrome");
}
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
Take the input and call toUpper(); that way when you check to see if it is a palindrome, all of the characters are uppercase.
String ori = scr.nextLint();
if(isPalindrome(ori.toUpperCase()))
//do something
Convert all the cases to lowercase/uppercase before checking the palindrome
isPailindrome(ori.toLowerCase());
Zoom in from both ends and adjust the case as required.
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len >>1; i++) {
if (Character.toLowerCase(str.charAt(i)) !=
Character.toLowerCase(str.charAt(len - i - 1))) {
return false;
}
}
return true;
}
I have file of which I need to read input. On one of the lines, there is no name added. In this case, I want to print out that no match was found. The problem that I'm having is that I don't know how I can make sure the program actually reads the part as an empty string. What happens now is that the will just leave the line empty on the console.
The date input looks like this:
5=20=22=10=2=0=0=1=0=1;Vincent Appel,Johannes Mondriaan
2=30=15=8=4=3=2=0=0=0;
class Administration {
public static final int TOTAL_NUMBER_OF_SIMULARITY_SCORES = 10;
public static final String ZERO_MATCHES = "_";
public static final String LESS_THAN_TWENTY_MATCHES= "-";
public static final String TWENTY_OR_MORE_MATCHES = "^";
PrintStream out;
Administration() {
out = new PrintStream(System.out);
}
void printSimilarityScores (Scanner similarityScoresScanner, String similarityScoresInput) {
similarityScoresScanner.useDelimiter("=|;");
int length = similarityScoresInput.length();
for (int i = 0; i < TOTAL_NUMBER_OF_SIMULARITY_SCORES; i++) {
int grade = similarityScoresScanner.nextInt();
if (grade == 0) {
out.printf(ZERO_MATCHES);
} else if (grade < 20) {
out.printf(LESS_THAN_TWENTY_MATCHES);
} else {
out.printf(TWENTY_OR_MORE_MATCHES);
}
}
System.out.print("\n");
similarityScoresScanner.useDelimiter(";|,");
while(similarityScoresScanner.hasNext()) {
String name = similarityScoresScanner.next();
if (length < 22) {
out.printf("No matches found\n");
} else {
System.out.print("\n" + name);
}
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
while (fileScanner.hasNext()) {
String finalGradeInput = fileScanner.nextLine();
String similarityScoresInput = fileScanner.nextLine();
Scanner finalGradeInputScanner = new Scanner(finalGradeInput);
Scanner similarityScoresScanner = new Scanner(similarityScoresInput);
printFinalGrade(finalGradeInputScanner);
printSimilarityScores(similarityScoresScanner, similarityScoresInput);
}
}
public static void main(String[] argv) {
new Administration().start();
}
}
An easier solution would be to read the file, line by line and handle them like this :
split by the separator
check if there is more than 1 element,
if positive print them
Scanner similarityScoresScanner = new Scanner(myFile);
while (similarityScoresScanner.hasNextLine()) {
String[] content = similarityScoresScanner.nextLine().split("[;,]");
if (content.length == 1) {
System.out.println("No matches found");
} else {
for (int i = 1; i < content.length; i++) {
System.out.println(content[i]);
}
}
}
I have a program that takes in a file of unindented code and comments the program takes the specified file and will output an indented version of the code.
I keep on getting the java.lang.ArrayIndexOutOfBoundsException: 1 error. This seems to occur when I have only one comment on a line as for when it splits the string the index only takes up 0. I have got an if statement in place to handle a comment on a line on its own but it still throws the exception.
Would I need to implement an if statement to check whether or not the split string has more than 1 part to it?
import java.io.*;
import java.util.*;
class Program
{
public static int spaces = 0;
public static int longestLine = 0;
public static int commentSpaces;
public static String beforeComment;
public static String afterComment;
public static void main(String args[]) throws FileNotFoundException
{
Scanner input2 = new Scanner(new File("C:\\Users\\James\\Music\\code.java")); //get text from file
while (input2.hasNextLine() == true) { //get the longest line
String text = input2.nextLine();
if (text.contains("//")) {
if (text.contains("\"//")) {
printLine(text);
}
String[] parts = text.split("//");
String codeOnly = parts[0];
if (codeOnly.length() > longestLine) {
longestLine = codeOnly.length();
}
}
else {
if (text.length() > longestLine) {
longestLine = text.length();
}
}
if (input2.hasNextLine() == false) {
break;
}
}
Scanner input3 = new Scanner(new File("C:\\Users\\James\\Music\\code.java"));
while (input3.hasNextLine()) { //indent comments
String text = input3.nextLine();
if (text.contains("}")) {
spaces -=2;
}
for (int i = 0; i < spaces; i++) {
System.out.print(" ");
}
if (text.startsWith("//")){
String justComment = text;
commentSpaces = longestLine - spaces + 6;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(justComment);
System.out.println(" ");
}
if (text.contains("\"//")) {
printLine(text);
}
if (text.contains("//")) {
String[] parts = text.split("(?=//)");
beforeComment = parts[0].trim(); // trim() to get rid of any spaces that are already present within the code
afterComment = parts[1];
printLine(beforeComment);
commentSpaces = longestLine - beforeComment.length() - spaces + 5;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(afterComment);
System.out.println();
}
else {
printLine(text);
System.out.println();
}
if (text.contains("{")) {
spaces +=2;
}
}
}
public static void printLine(String text) {
Scanner data = new Scanner(text);
while (data.hasNext()) {
System.out.print(" " + data.next());
}
}
public static void yesItContains() {
System.out.print("It contains a string");
System.exit(0);
}
}
I think that if text is "something//" meaning it is ending in a empty comment your parts will only have length 1. So yes, you need to check it, e.g. via afterComment = parts.length > 1 ? parts[1] : "";. Note that lines like "something // something else // blabla" might break that logic as well.
package school;
import java.util.*;
public class PalindromeWords {
boolean palindrome(String S) {
String check="";
for(int i = S.length()-1;i>=0;i--) {
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S)) {
return true;
}
else {
return false;
}
}
public static void main(String args[]) {
PalindromeWords ob = new PalindromeWords();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String S=sc.nextLine();
S = S + ' ';
int flag = 0,i=0;
String word;
for(i=0;i<S.length();i++) {
if(S.charAt(i)==' ') {
word = S.substring(flag,i);
if(ob.palindrome(word)) {
System.out.println(word);
flag =i+1;
}
}
}
}
}
I have been given an assignment in which I have to Write a Java Program to Print all the Palindrome words in a sentence. This is the code I wrote and I am not getting the correct output.
As you can see the output in the console gives no query in result.
You should move the step which increase flag outside if statement. Otherwise, it only works if the first word is palindrome.
if(ob.palindrome(word)) {
System.out.println(word);
}
flag = i+1;
Use the flag outside the loop.
if(ob.palindrome(word)==true) {
System.out.println(word);
}
flag =i+1;
This code should work.
Here is another solution as follows:
code:
import java.util.*;
public class PalindromeWords
{
boolean isPalindrome(String S)
{
boolean result = false;
String check="";
for(int i = S.length()-1;i>=0;i--)
{
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S))
{
result = true;
}
return result;
}
public static void main(String args[])
{
PalindromeWords ob = new PalindromeWords();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String str = sc.nextLine();
String[] words = str.split(" ");
for(int i=0; i < words.length; i++)
{
if(ob.isPalindrome(words[i]))
{
System.out.println(words[i]);
}
}
}
}
output:
Enter the sentence.
hello mAdam
mAdam
boolean palindrome(String S){
String check="";
for(int i = S.length()-1;i>=0;i--)
{
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S)==true)
{
return true;
}
else
{
return false;
}
}
public static void main(String args[])
{
Para ob = new Para();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String S=sc.nextLine();
S = S + ' ';
int flag = 0,i=0;
String word;
for(i=0;i<S.length();i++)
{
if(S.charAt(i)==' ')
{
word = S.substring(flag,i);
if(ob.palindrome(word)==true)
{
System.out.println(word);
}flag =i+1;
}
}
}