I suggest you start by getting your program to work with just the first 3 lines
ID: 3764971 • Letter: I
Question
I suggest you start by getting your program to work with just the first 3 lines of data (3 answers) as those will be easy with plain old int data. Then take the challenge of more lines. When I grade these, I will use different numbers, so do not code just for these exact data.
Submit a Class called Sum.java with the following main() method:
and a processFile method as used below!!!!
import java.io.*; // NO you cannot use BigInteger to do this!
import java.util.*; // These are the ONLY imports allowed
public class Sum {
public static final int DIGITS = 50; // maximum number of digits
// ... lots more code follows .....
Above requires two (or more) methods, plus main and processFile. In addition, I REQUIRE two additional methods in your solution, and at least one of these methods must use an array as a passed parameters (two arrays also OK). For example, you might write some sort of "add" method that does the actual addition of int[] arrays as passed parameters. I say int[] because that's how we do addition, one digit at a time, treat each digit as an element of an int[], and write the rules of addition, you know them well, time to code it!!!
Explanation / Answer
import java.io.*;
import java.util.*;
public class Data {
public static void processFile(Scanner input)
{ int count=0;
while(input.hasNextLine())
{
count++;
String line=input.nextLine();
String array[]=line.split(" ") ;
int sum=add(array);
display(sum,array);
}
System.out.println("Total lines = "+count);
}
static void display(int sum,String array[])
{
for(int i=0;i<array.length-1;i++)
{
System.out.print(array[i]+"+");
}
System.out.print(array[array.length-1]+"=");
System.out.println(sum);
}
static int add(String []s)
{
int total=0;
for(int i=0;i<s.length;i++)
{ if(s[i].length()>50)
{
String ss=String.valueOf(s[i].charAt(0));
for(int j=1;j<50;j++)
{
ss=ss+String.valueOf(s[i].charAt(j));
}
total=total+Integer.parseInt(ss);
}else
total=total+Integer.parseInt(s[i]);
}
return total;
}
public static void main(String[] args) throws FileNotFoundException {
final int DIGITS = 50; // maximum number of digits
Scanner input = new Scanner(new File("sum.txt")); // sum.txtPreview the documentView in a new window
processFile(input);
}
}