40.5k views
4 votes
Write a method named matchIndex that accepts as its parameter a Scanner for an input file. Your method should compare each neighboring pair of lines (the first and second lines, then the third and fourth lines, and so on) looking for places where the character at a given 0-based index from the two lines is the same. For example, in the strings "hello" and "belt", the characters at indexes 1 ('e') and 2 ('l') match. Your code should be case-sensitive; for example, "J" does not match "j".

User David Tran
by
6.4k points

1 Answer

4 votes

Answer:

Java code given below

Step-by-step explanation:

Java code:

import java.util.*;

import java.io.*;

import java.math.*;

public class abc {

public static void main(String[] args)throws FileNotFoundException{

File file = new File("input.txt");

Scanner sc = new Scanner(file);

matchIndex(sc);

}

public static void matchIndex(Scanner sc){

int line=1;

while(sc.hasNextLine()){

System.out.print( "lines "+Integer.toString(line)+" and "+Integer.toString(line+1)+": ");

String s=sc.nextLine();

String t=sc.nextLine();

s=s.trim();

t=t.trim();

int l=Math.min(s.length(),t.length());

Boolean match=false;

for(int i=0;i<l;i++){

if(s.charAt(i)==t.charAt(i)){

System.out.print(Integer.toString(i)+" ");

match=true;

}

}

if(!match){

System.out.println("none ");

}

else{

System.out.println();

}

line=line+2;

}

}

}

User Noseratio
by
4.8k points