JAVA: Determine the problem and fix the program. The file has syntax and/or logi
ID: 3930451 • Letter: J
Question
JAVA:
Determine the problem and fix the program. The file has syntax and/or logic errors.
// Program prompts user to enter a series of integers
// separated by spaces
// Program converts them to numbers and sums them
import java.util.*;
public class DebugSeven2
{
public static void main(String[] args)
{
String str;
int x;
int length;
int start = 0;
int num;
int lastSpace = -1;
int sum = 0;
String partStr;
Scanner in = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = in.nextLine();
length = length();
for(x = 0; x <= length; ++x)
{
if(str.charAt(x) == " ")
{
partStr = str.substring(x, lastSpace + 1);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum = num;
lastSpace == x; *****Error Here*****
}
}
partStr = str.substring(lastSpace + 1, length);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum = num;
System.out.println(" -------------------" +
" The sum of the integers is " + sum);
}
}
Explanation / Answer
Hi,
I have fixed the systex/logical issues. it is an error free now. Highlighteed the code changes below.
DebugSeven2.java
import java.util.*;
public class DebugSeven2
{
public static void main(String[] args)
{
String str;
int x;
int length;
int start = 0;
int num;
int lastSpace = -1;
int sum = 0;
String partStr;
Scanner in = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = in.nextLine();
length = str.length();
for(x = 0; x < length; ++x)
{
if(str.charAt(x) == ' ')
{
partStr = str.substring(lastSpace + 1,x );
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum = sum + num;
lastSpace = x; //*****Error Here*****
}
}
partStr = str.substring(lastSpace + 1, length);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum =sum + num;
System.out.println(" -------------------" +
" The sum of the integers is " + sum);
}
}
Output:
Enter a series of integers separated by spaces >> 2 3 4
2
3
4
-------------------
The sum of the integers is 9
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.