Question

Identify a logical error in the following code and fix it. public class test1 {    ...

  1. Identify a logical error in the following code and fix it.

public class test1 {
    public static void main(String[] args){
        int total;
        float avg;
        int a, b, c;
        a=10;
        b=5;
        c=2;
        total=a+b+c;
        avg=total/3;
        System.out.println("Average: "+avg);
    }
}

Answer:

  1. Write the output of the program below.
import java.util.Scanner;

public class test2 {

    public static void main(String[] arg){

        int psid;

        String name;

        Scanner input=new Scanner(System.in);

        System.out.println("Enter your PSID");

        psid=input.nextInt();

        System.out.println("Enter your Name");

        name=input.nextLine();



        System.out.println("Name: "+ name);

        System.out.println("PSID: "+psid);

    }

}

Did the program produced expected output?

If your answer is “yes”, then justify your answer. Else if your answer is “no”, then what is the reason for that and how to fix it?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

public class test1 {
public static void main(String[] args){
int total;
float avg;
int a, b, c;
a=10;
b=5;
c=2;
total=a+b+c;
avg=total/3.0f;
System.out.println("Average: "+avg);
}
}

Answer:
=====
The fixed code is given above. The error is in calculating average. We need to use 3.0f instead of 3, otherwise it will perform integer division and we will loose the fractional part. Using 3.0f will ensure that we get float as result without loosing data.

output of program
====
Average: 5.6666665


*******************************************
import java.util.Scanner;

public class test2{
   public static void main(String[] arg){

   int psid;

   String name;

   Scanner input=new Scanner(System.in);

   System.out.println("Enter your PSID");

   psid=input.nextInt();
   input.nextLine(); //get rid of newline before reading name
  
  
   System.out.println("Enter your Name");

   name=input.nextLine();

   System.out.println("Name: "+ name);

   System.out.println("PSID: "+psid);

   }
}

output:
=======
Enter your PSID
12
Enter your Name
John
Name: John
PSID: 12

Answer:
=====
The fixed program is given above. The program would not read the name input from user. This is because after the integer for Id is input, there is a newline which is taken by nextLine() method. It would not wait for user to type in name. So avoid the problem, we use input.nextLine() after reading the int input. This removes the newline from input and waits for user input of name after prompting.

Add a comment
Know the answer?
Add Answer to:
Identify a logical error in the following code and fix it. public class test1 {    ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am getting an error from eclipse stating that: Exception in thread "main" java.lang.Error: Unresolved compilation...

    I am getting an error from eclipse stating that: Exception in thread "main" java.lang.Error: Unresolved compilation problem: at EvenOdd.main(EvenOdd.java:10) I am unable to find what I can do to fix this issue. Can you please assist? My code is below: import java.util.InputMismatchException; import java.util.Scanner; public class EvenOdd {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);        System.out.println("Welcome to this Odd program!");        int userInput1 = input.nextInt();    }       public...

  • Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895...

    Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895    {        public static void header()        {            System.out.println("\tWelcome to St. Joseph's College");        }        public static void main(String[] args) {            Scanner input = new Scanner(System.in);            int d;            header();            System.out.println("Enter number of items to process");            d = input.nextInt();      ...

  • read the code and comments, and fix the program by INSERTING the missing code in Java...

    read the code and comments, and fix the program by INSERTING the missing code in Java THank you please import java.util.Scanner; public class ExtractNames { // Extract (and print to standard output) the first and last names in "Last, First" (read from standard input). public static void main(String[] args) { // Set up a Scanner object for reading input from the user (keyboard). Scanner scan = new Scanner (System.in); // Read a full name from the user as "Last, First"....

  • Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class...

    Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class Delete extends Info { String name; int Id; int del; public Delete() { } public void display() { Scanner key = new Scanner(System.in); System.out.println("Input Customer Name: "); name = key.nextLine(); System.out.println("Enter ID Number: "); Id = key.nextInt(); System.out.println("Would you like to Delete? Enter 1 for yes or 2 for no. "); del = key.nextInt(); if (del == 1) { int flag = 0; //learned...

  • Please fix my code so I can get this output: Enter the first 12-digit of an...

    Please fix my code so I can get this output: Enter the first 12-digit of an ISBN number as a string: 978013213080 The ISBN number is 9780132130806 This was my output: import java.util.Scanner; public class Isbn { private static int getChecksum(String s) { // Calculate checksum int sum = 0; for (int i = 0; i < s.length(); i++) if (i % 2 == 0) sum += (s.charAt(i) - '0') * 3; else sum += s.charAt(i) - '0'; return 10...

  • I need the following java code commented import java.util.Scanner; public class Main { public static void...

    I need the following java code commented import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner (System.in); int productNo=0; double product1; double product2; double product3; double product4; double product5; int quantity; double totalsales=0; while(productNo !=0) System.out.println("Enter Product Number 1-5"); productNo=input.nextInt(); System.out.println("Enter Quantity Sold"); quantity=input.nextInt(); switch (productNo) { case 1: product1=1.00; totalsales+=(1.00*quantity); break; case 2: product2=2.00; totalsales+=(2.00*quantity); break; case 3: product3=6.00; totalsales+=(6.00*quantity); break; case 4: product4=23.00; totalsales+=(23.00*quantity); break; case 5: product5=17.00; totalsales+=(17.00*quantity); break;...

  • The part in bold is giving me an error. Ther error is that I cant convert...

    The part in bold is giving me an error. Ther error is that I cant convert an int to a boolean. The program asks the user to input two integer values and determines whether the first is divisible (without a remainder) by the second import java.util.Scanner; public class CheckDivisible { int isDivisible(int dividend, int divisor) { if(dividend % divisor == 0) return 1; else return 0; } public static void main(String[] args) { int dividend = 0; int divisor =...

  • Fix this program package chapter8_Test; import java.util.Scanner; public class Chapter8 { public static void main(String[] args)...

    Fix this program package chapter8_Test; import java.util.Scanner; public class Chapter8 { public static void main(String[] args) { int[] matrix = {{1,2},{3,4},{5,6},{7,8}}; int columnChoice; int columnTotal = 0; double columnAverage = 0; Scanner input = new Scanner(System.in); System.out.print("Which column would you like to average (1 or 2)? "); columnChoice = input.nextInt(); for(int row = 0;row < matrix.length;++row) { columnTotal += matrix[row][columnChoice]; } columnAverage = columnTotal / (float) matrix.length; System.out.printf("\nThe average of column %d is %.2f\n", columnAverage, columnAverage); } } This program...

  • import java.util.Scanner; public class creditScore { public static void main(String[]args) { // declare and initialize variables...

    import java.util.Scanner; public class creditScore { public static void main(String[]args) { // declare and initialize variables int creditScore; double loanAmount,interestRate,interestAmount; final double I_a = 5.56,I_b = 6.38,I_c = 7.12,I_d = 9.34,I_e = 12.45,I_f = 0; String instructions = "This program calculates annual interest\n"+"based on a credit score.\n\n"; String output; Scanner input = new Scanner(System.in);// for receiving input from keyboard // get input from user System.out.println(instructions ); System.out.println("Enter the loan amount: $"); loanAmount = input.nextDouble(); System.out.println("Enter the credit score: "); creditScore...

  • (How do I remove the STATIC ArrayList from the public class Accounts, and move it to...

    (How do I remove the STATIC ArrayList from the public class Accounts, and move it to the MAIN?) import java.util.ArrayList; import java.util.Scanner; public class Accounts { static ArrayList<String> accounts = new ArrayList<>(); static Scanner scanner = new Scanner(System.in);    public static void main(String[] args) { Scanner scanner = new Scanner(System.in);    int option = 0; do { System.out.println("0->quit\n1->add\n2->overwirte\n3->remove\n4->display"); System.out.println("Enter your option"); option = scanner.nextInt(); if (option == 0) { break; } else if (option == 1) { add(); } else...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT