Making parallel array that accepts names, hours, payrates - java

So for this program I need to have three arrays accept data and display the gross pay, It seems to work at first but after enter the first person's data, my code begins to stack on top of itself in the window, please help me fix this to work properly.
I am required to use arrays. Objects are not allowed.
import java.util.Scanner;
public class ThreeArrays {
public static void main(String args[]) {
float[] payRate = new float[5];
float[] hours = new float[5];
String[] name = new String[5];
getPayData(name, hours, payRate);
displayGrossPay(name, hours, payRate);
}
public static void getPayData(String[] name, float[] hours, float[] payRate) {
Scanner kb = new Scanner(System.in);
for (int i = 0; i < hours.length; i++) {
System.out.print("Enter the employee's name: ");
name[i] = kb.nextLine();
System.out.print("Enter the employee's hours: ");
hours[i] = kb.nextFloat();
System.out.print("Enter the employee's hourly rate: ");
payRate[i] = kb.nextFloat();
}
}
public static void displayGrossPay(String[] name, float[] hours, float[] payRate) {
for (int i = 0; i < hours.length; i++) {
System.out.println("Employee name: " + name[i] + " Gross Pay: " + hours[i] *
payRate[i]);
}
}
}

Put System.out.println(); between each statement where you ask for data.
EDIT: It could also be that the \n character isn't being read with .nextInt(). To fix it, put kb.nextLine(); after kb.nextFloat();
for (int i = 0; i < hours.length; i++) {
System.out.print("Enter the employee's name: ");
name[i] = kb.nextLine();
System.out.println("");
System.out.print("Enter the employee's hours: ");
hours[i] = kb.nextFloat();
kb.nextLine();
System.out.println("");
System.out.print("Enter the employee's hourly rate: ");
payRate[i] = kb.nextFloat();
kb.nextLine();
System.out.println("");
}
// Enter the employee's name: Foo
// (Blank Line)
// Enter the employee's hours: 1
// (Blank Line)
// Enter the employee's hourly rate: -20.00 // They owe me now. :D
// (Blank Line)

The problem is related to stdin flushing. Because last entered float value for line payRate[i] = kb.nextFloat(); don't removes \n character. This \n character is being fetched by line name[i] = kb.nextLine(); in next iteration. Which further leaves a String value for line hours[i] = kb.nextFloat();. Since it is not a valid float hence you are getting exception: java.util.InputMismatchException.
To solve this use line if(i < hours.length-1) kb.next(); after line payRate[i] = kb.nextFloat();.
Following is corrected code. See complete working code here:
public class ThreeArrays {
public static void main(String args[]) {
float[] payRate = new float[5];
float[] hours = new float[5];
String[] name = new String[5];
getPayData(name, hours, payRate);
displayGrossPay(name, hours, payRate);
}
public static void getPayData(String[] name, float[] hours, float[] payRate) {
Scanner kb = new Scanner(System.in);
for (int i = 0; i < hours.length; i++) {
System.out.print("Enter the employee's name: ");
name[i] = kb.nextLine();
System.out.print("Enter the employee's hours: ");
hours[i] = kb.nextFloat();
System.out.print("Enter the employee's hourly rate: ");
payRate[i] = kb.nextFloat();
if(i < hours.length-1) kb.next();
}
}
public static void displayGrossPay(String[] name, float[] hours, float[] payRate) {
for (int i = 0; i < hours.length; i++) {
System.out.println("Employee name: " + name[i] + " Gross Pay: " + (hours[i] *
payRate[i]));
}
}
}

I have figured it out everyone
The problem lies with using
System.out.print("Enter the employee's name: ");
name[i] = kb.nextLine();
I had to change it to
System.out.print("Enter the employee's name: ");
name[i] = kb.next();

Related

My scanner class java code has a exception that is a error

I get this error when running my code, please help.
Exception in thread "main" java.util.InputMismatchException
I would appreciate any fixes you could provide to the code overall.
When I input data like weight in this case, it is full of mistakes and it's annoying.
package howto;
import java.util.Scanner;
public class Howto {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
double weightkg [] = new double [30];
double weightkgEndOfMonth [] = new double [30];
String name [] = new String [30];
double weightDifference [] = new double[30];
for (int i = 0; i<31; i++)
{
System.out.println("Input name: ");
String scanner1 = sc1.nextLine();
name [i] = scanner1;
System.out.println("Input weight: ");
double scanner2 = sc2.nextDouble();
if(!sc1.hasNextDouble())
{
System.out.println("Invalid Weight!. Start Again");
} else
{
weightkg[i] = scanner2;
}
System.out.println("Name: " + name[i]);
System.out.println("weight : " + weightkg[i]);
}
for (int i = 0; i<31; i++)
{
System.out.println("Input weight at the end of month: ");
double scanner2 = sc2.nextDouble();
if(!sc1.hasNextDouble())
{
System.out.println("Invalid Weight!. Start Again");
} else
{
weightkgEndOfMonth[i] = scanner2;
}
weightDifference [i] = weightkg[i] - weightkgEndOfMonth[i];
if(weightDifference[i]>2.5)
{
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Rise");
}
if(weightDifference[i]> -2.5)
{
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Fall");
}
}
}
}
Error Message:
run:
Input name:
Test
Input weight:
90
10
Name: Test
weight : 90.0
Input name:
Input weight:
Test1
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at howto.Howto.main(Howto.java:45)
Java Result: 1
BUILD SUCCESSFUL (total time: 16 seconds)
There are a few issues which stand out...
First...
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
You don't need multiple scanners, they are reading from the same stream anyway, better to use just one and reduce the complexity.
Next...
String scanner1 = sc1.nextLine();
name [i] = scanner1;
System.out.println("Input weight: ");
double scanner2 = sc2.nextDouble();
if(!sc1.hasNextDouble())
{
System.out.println("Invalid Weight!. Start Again");
} else
{
weightkg[i] = scanner2;
}
When using nextDouble, the buffer still contains a newline marker, meaning that the next time you use nextLine, it will return a blank String and move on.
Also, hasNextDouble seems to be waiting for data, but you've already read the double value from the buffer, leaving the dangling new line. In my test, this was causing issues with the program waiting for more input.
I "solved" the basic problem by doing something like this...
String scanner1 = sc1.nextLine();
name [i] = scanner1;
System.out.println("Input weight: ");
double scanner2 = sc1.nextDouble();
weightkg[i] = scanner2;
sc1.nextLine();
Now this "will" work, but it's not the best solution. A "different" approach might be to read the weight in as a String and attempt to parse it as a double, this gives you the chance to trap the invalid input and handle it in a more appropriate manner, for example...
System.out.println("Input name: ");
String scanner1 = sc1.nextLine();
name[i] = scanner1;
boolean done = false;
double weight = 0;
do {
System.out.println("Input weight: ");
String input = sc1.nextLine();
try {
weight = Double.parseDouble(input);
done = true;
} catch (NumberFormatException nfe) {
System.out.println("!! Invalid value");
}
} while (!done);
weightkg[i] = weight;
System.out.println("Name: " + name[i]);
System.out.println("weight : " + weightkg[i]);
}
you have some logical mistakes in your code. after every line i mention them.
import java.util.Scanner;
public class HowTo {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in); // you need only 1 scanner
double weightkg[] = new double[30];
double weightkgEndOfMonth[] = new double[30];
String name[] = new String[30];
double weightDifference[] = new double[30];
for (int i = 0; i < 30; i++) { // need to iterate from 0 index to 29
System.out.print("Input name: ");
String scanner1 = sc1.nextLine();
name[i] = scanner1;
System.out.print("Input weight: ");
if (!sc1.hasNextDouble()) {
System.out.println("Invalid Weight!. Start Again");
} else {
weightkg[i] = sc1.nextDouble();// if it has double then read it
}
System.out.println("Name: " + name[i]);
System.out.println("weight : " + weightkg[i]);
sc1.nextLine();
}
for (int i = 0; i < 30; i++) {// need to iterate from 0 index to 29
System.out.println("Input weight at the end of month: ");
if (!sc1.hasNextDouble()) {
System.out.println("Invalid Weight!. Start Again");
} else {
weightkgEndOfMonth[i] = sc1.nextDouble();// read double here
}
weightDifference[i] =weightkgEndOfMonth[i]- weightkg[i] ;// weight difference is (final weight- initial weight)
if (weightDifference[i] > 2.5) {
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Rise");
}
if (weightDifference[i] < -2.5) {// fall if weight less than 2.5
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Fall");
}
}
}
}
Now it is working fine.

How to add more variables inside of loops java

Have each department's number of computers stored in variables. Have the program store the values in variables, calculate the total and average computers and display them.
example output:
Chemistry: 4
Physics: 8
Music: 2
Math lab: 12
Total: 26
Average: 6.5
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What is the name of your first class?");
String class1 = sc.nextLine();
System.out.print("What is the name of your second class?");
String class2 = sc.nextLine();
System.out.print("What is the name of your third class?");
String class3 = sc.nextLine();
System.out.print("What is the name of your fourth class?");
String class4 = sc.nextLine();
System.out.print(" \n\n");
System.out.println("How many computers are in each class?");
System.out.print(class1 + ": \t");
int class1comp = sc.nextInt();
System.out.print(class2 + ": \t");
int class2comp = sc.nextInt();
System.out.print(class3 + ": \t");
int class3comp = sc.nextInt();
System.out.print(class4 + ": \t");
int class4comp = sc.nextInt();
int sum = class1comp + class2comp + class3comp + class4comp;
double avg = sum / 4.0;
System.out.print(" \n\n");
System.out.println("\n\n" + class1 + ":\t" + class1comp);
System.out.println(class2 + ":\t" + class2comp);
System.out.println(class3 + ":\t" + class3comp);
System.out.println(class4 + ":\t" + class4comp);
System.out.println("\n");
System.out.println("Total:\t\t" + sum);
System.out.println("Average:\t" + avg);
}
}
After unit 2: Allow the user to add more departments.
I want the user to be able to add more classes until they say stop. Then later ask how many computers each class needs. Then display them, add them to the sum and average.
This should work for your purposes , it uses an ArrayList for the class names and an array of integers for the grades. It uses the AddOrdinal method taken from this answer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> stringList = new ArrayList<>();
String capture;
int count =1;
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
while (!((capture = scan.nextLine()).toLowerCase().equals("stop"))) {
count++;
stringList.add(capture);
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
}
System.out.println("How many computers are in each class?");
int[] intList = new int[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
String className = stringList.get(i);
System.out.println(className + "\t:");
intList[i] = (scan.nextInt());
}
scan.close();
Arrays.stream(intList).sum();
int sum = Arrays.stream(intList).sum();
double average = (double)sum/intList.length;
/*
Output goes here
*/
}

FileWriter not receiving all input and mysterious dangling newline issue

I am trying to write a Java program in which the user specifies how many "student records" they would like to input, followed by the student's name, age, and GPA, which then gets stored as text. However, I am having a problem with my text not including all entered data and a mysterious dangling newline that I cannot get rid of.
Here is my program:
import java.io.*;
import java.util.Scanner;
public class CreateFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
FileWriter fwriter = new FileWriter("c:\\Students.dat");
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = " ";
String next = " ";
int age = 0;
int hm = 0;
double gpa = 0.0;
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.nextLine();
input.nextLine();
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
next = input.nextLine();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
StudentFile.close();
System.exit(0);
}
}
Here is sample input and output to illustrate my issues:
run:
How many student records would you like to enter: 3
Enter Name: Jon
Enter Age: 20
Enter GPA: 3.4
Enter Name: Bill
Enter Age: 24
Enter GPA: 3.6
Enter Name: Ted
Enter Age: 34
Enter GPA: 3.9
This is the produced text file:
20
3.4
Bill
24
3.6
Ted
34
3.9
Why doesn't it store the first name entered? Why isn't there a newline in the first entry, but it is in the others?
The problem is that you're using nextLine() when you need to be using next(). I'm assuming you put the second input.nextLine() in there because you were initially having a problem where it would print out "Enter Name: " and then immediately "Enter Age: ". nextLine() is telling your program to skip whatever is there, and not to wait for it. The reason that this paradigm worked at all for any of your entries is that you put next = input.nextLine() at the bottom of your loop. Here's a fix:
package createfile;
import java.io.*;
import java.util.Scanner;
public class CreateFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
FileWriter fwriter = new FileWriter("c:Students.dat");
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = " ";
String next = " ";
int age = 0;
int hm = 0;
double gpa = 0.0;
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.next();
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
StudentFile.close();
System.exit(0);
}
}
You could also just move your input.nextLine() above name=input.nextLine() and it would have the same effect.
The other examples only work if you don't have names like "James Peter" - in their code examples only James would be saved as name.
I'd prefer this:
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
input.nextLine();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.nextLine();
System.out.print("Enter Age: ");
age = input.nextInt();
input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
input.nextLine();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
This is the corrected for loop:
for ( int x = 1; x <= hm; x++ )
{
System.out.print( "Enter Name: " );
name = input.next();
input.nextLine();
System.out.print( "Enter Age: " );
age = input.nextInt();
input.nextLine();
System.out.print( "Enter GPA: " );
gpa = input.nextDouble();
next = input.nextLine();
StudentFile.println( name );
StudentFile.println( age );
StudentFile.println( gpa );
}
Some things you may want to consider:
Handle the IOException - it should not be ignored!!
Use the methods hasNextXXX() of the Scanner to check if something is available.
Refactor your usage of the variable next, it's never really used.
It's not necessary to call System.exit( 0 ) from the main method - rather use the return statement with a meaningful value.

Why is the value of the subclass data member not displayed?

I have created 2 java files: XCompanyShortlist.java and StudentDemo.java. The XCompanyShortlist.java contains the main method and all the user input like Student Registration No., Name, Semester, GPA, CGPA, Branch Name, Placement status and Internship status.
The StudentDemo.java has a superclass StudentDemo which initializes Reg. No., Name, Semester, GPA, CGPA using parameterized constructor and it also contains a method display() which displays all there informations.
A class BranchStudent extends StudentDemo class and contains an extra String named BranchName. This class also contains a display() method which calls the display() method in the superclass and also prints the BranchName. Another class StudentPlacement contains variables for InternshipStatus, PlacementStatus, and an array of preferred company list.
Here is the StudentDemo.java file code:
class StudentDemo {
long RegNo;
String fname;
short sem;
float gpa;
float cgpa;
StudentDemo() {
RegNo = 0;
fname = "";
sem = 0;
gpa = (float) 0.0;
cgpa = (float)0.0;
}
StudentDemo(long RegNo, String fname, short sem, float gpa, float cgpa) {
this.RegNo = RegNo;
this.fname = fname;
this.sem = sem;
this.gpa = gpa;
this.cgpa = cgpa;
}
StudentDemo(StudentDemo obj) {
RegNo = obj.RegNo;
fname = obj.fname;
sem = obj.sem;
gpa = obj.gpa;
cgpa = obj.cgpa;
}
void display() {
System.out.println("------------------------------------------");
System.out.println("Registration No. :"+RegNo);
System.out.println("Full Name: "+fname);
System.out.println("Semester: "+sem);
System.out.println("GPA: "+gpa);
System.out.println("CGPA: "+cgpa);
System.out.println("------------------------------------------");
}
}
class BranchStudent extends StudentDemo {
public String BranchName;
BranchStudent(long RegNo,String fname,short sem,float gpa,float cgpa,String BranchName) {
super(RegNo,fname,sem,gpa,cgpa);
this.BranchName = BranchName;
}
BranchStudent() {
super();
BranchName = "CSE";
}
BranchStudent(BranchStudent obj) {
super(obj);
BranchName = obj.BranchName;
}
void display() {
super.display();
System.out.println("Student Branch: "+BranchName);
}
}
class StudentPlacement extends BranchStudent {
String compList[];
int StatusPlacement, StatusIntern;
StudentPlacement() {
super();
StatusPlacement = 0;
StatusIntern = 0;
compList = new String[3];
}
StudentPlacement(StudentPlacement obj) {
super(obj);
StatusPlacement = obj.StatusPlacement;
StatusIntern = obj.StatusIntern;
compList = obj.compList;
}
StudentPlacement(long RegNo, String fname, short sem, float gpa, float cgpa, String BranchName,String compList[], int StatusPlacement,int StatusIntern) {
super(RegNo, fname, sem, gpa, cgpa, BranchName);
this.compList = compList;
this.StatusPlacement = StatusPlacement;
this.StatusIntern = StatusIntern;
}
}
Here is the XCompanyShortlist.java file code:
import java.util.Scanner;
public class XCompanyShortlist {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter The Number Of Students: ");
int n = sc.nextInt();
StudentPlacement obj[] = new StudentPlacement[n];
for(int i = 0; i < n; i++) {
obj[i] = new StudentPlacement();
}
System.out.println("Please Enter The Student Details: ");
for(int i = 0; i < n; i++) {
System.out.print("Please Enter The Reg. No. :");
long RegNo = sc.nextLong();
sc.nextLine();
System.out.print("Please Enter The Full Name: ");
String fname = sc.nextLine();
System.out.print("Please Enter The Semester: ");
short sem = sc.nextShort();
System.out.print("Please Enter The GPA: ");
float gpa = sc.nextFloat();
System.out.print("Please Enter The CGPA: ");
float cgpa = sc.nextFloat();
System.out.print("Please Enter Branch Name:");
String branchName = sc.nextLine();
sc.nextLine();
System.out.println("Please Enter 3 Preferred Choice: ");
String compList[] = new String[3];
for(int x = 0; x < 3; x++) {
compList[x] = sc.nextLine();
}
System.out.print("Please Enter The Status Of Placement(0/1): ");
int statusPlacement = sc.nextInt();
System.out.print("Please Enter Status Of Internship(0/1): ");
int statusIntern = sc.nextInt();
obj[i] = new StudentPlacement(RegNo,fname,sem,gpa,cgpa,branchName,compList,statusPlacement,statusIntern);
System.out.println();
}
for(int i = 0; i < n; i++) {
obj[i].display();
}
sc.close();
}
}
The problem I am facing is that all the student details from the StudentDemo superclass is being dislayed but the subclass BranchStudent is not printing the BranchName. I am unable to find the problem in my code.
OUTPUT:
Please Enter The Number Of Students:
1
Please Enter The Student Details:
Please Enter The Reg. No. :159101046
Please Enter The Full Name: Bitan Basak
Please Enter The Semester: 3
Please Enter The GPA: 8.86
Please Enter The CGPA: 8.64
Please Enter Branch Name:CSE
Please Enter 3 Preferred Choice:
HP
Dell
Microsoft
Please Enter The Status Of Placement(0/1): 0
Please Enter Status Of Internship(0/1): 0
------------------------------------------
Registration No. :159101046
Full Name: Bitan Basak
Semester: 3
GPA: 8.86
CGPA: 8.64
------------------------------------------
Student Branch:
This is the output given by my program. As you can see the Student Branch is not being printed. I am unable to understand why.
From what I can tell the issue has nothing to do with inheritance but rather that you are feeding an empty line to the constructor.
This means something is wrong with the usage of the Scanner.nextLine() method. If I change your code to this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter The Number Of Students: ");
int n = sc.nextInt();
StudentPlacement obj[] = new StudentPlacement[n];
for(int i = 0; i < n; i++) {
obj[i] = new StudentPlacement();
}
System.out.println("Please Enter The Student Details: ");
for(int i = 0; i < n; i++) {
System.out.print("Please Enter The Reg. No. :");
long RegNo = sc.nextLong();
sc.nextLine();
System.out.print("Please Enter The Full Name: ");
String fname = sc.nextLine();
System.out.print("Please Enter The Semester: ");
short sem = sc.nextShort();
System.out.print("Please Enter The GPA: ");
float gpa = sc.nextFloat();
System.out.print("Please Enter The CGPA: ");
float cgpa = sc.nextFloat();
sc.nextLine();
System.out.print("Please Enter Branch Name:");
String branchName = sc.nextLine();
System.out.println("Please Enter 3 Preferred Choice: ");
String compList[] = new String[3];
for(int x = 0; x < 3; x++) {
compList[x] = sc.nextLine();
}
System.out.print("Please Enter The Status Of Placement(0/1): ");
int statusPlacement = sc.nextInt();
System.out.print("Please Enter Status Of Internship(0/1): ");
int statusIntern = sc.nextInt();
obj[i] = new StudentPlacement(RegNo,fname,sem,gpa,cgpa,branchName,compList,statusPlacement,statusIntern);
System.out.println();
}
for(int i = 0; i < n; i++) {
obj[i].display();
}
sc.close();
}
I.e. move the sc.nextLine() before the Branch Name input the scanner picks up the correct value from the console.
Hope that helps.
Greetings
in void display() method you are calling super display() method so the super display() method is calling not that branch display method and add this.branchname

No Such Element - No Line Found (Java)

I'm creating a program which prints a summary of the situation after interactive input has ended (ctrl - d). So it prints a summary of the average age and percentage of children who have received vaccines after interactive input.
However, I'm always receiving the No Line Found error whenever I press ctrl-d at Name:. My compiler tells me the error is at name = sc.nextLine(); within the while loop but I don't know what is causing the error exactly.
public static void main(String[] args) {
String name = new String();
int age, num = 0, i, totalAge = 0;
boolean vaccinated;
int numVaccinated = 0;
double average = 0, percent = 0, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
while(sc.hasNextLine())
{
sc.nextLine();
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
}
average = (double) totalAge/num;
percent = (double) count/num * 100;
System.out.printf("Average age is %.2f\n", average);
System.out.printf("Percentage of children vaccinated is %.2f%%\n", percent);
}
}
You do not correctly implement an exit condition for your loop if you ask me.
Try something like this:
String input = "";
do {
System.out.print("Name: ");
name = sc.nextLine();
[... all your input parameters ...]
sc.nextLine();
System.out.print("Do you want to enter another child (y/n)? ");
input = sc.nextLine();
} while (!input.equals("n"));
This way you can quit entering new persons without having to enter a strange command that might lead to an error. Furthermore, a do-while loop helps you to reduce your code, because you don't have to use the same code twice, i.e., everything between Scanner sc = new Scanner(System.in); and while(sc.hasNextLine()) in your example.

Categories