No Such Element - No Line Found (Java) - 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.

Related

I have a program where i would like to validate user input in java i want the user to input a double value and only a double value any suggestions?

I did what i could and now the code works however when the user inputs the wrong value and is prompted to try again you have to hit enter and then you are asked to input a value, i cant think of what it is.
i also want to be able to get the program to start again after completing, i tried a do, while loop but it looped infinitely
public static void main(String[] args) {
String nameOfIngredient = null;
Float numberOfCups = null;
Float numberOfCaloriesPerCup = null;
Float totalCalories;
while(nameOfIngredient == null)
{nameOfIngredient = setIngredients(); }// Allows us to loop
while(numberOfCups == null)
{numberOfCups = setNumberOfCups(); }// Allows us too loop
while(numberOfCaloriesPerCup == null)
{numberOfCaloriesPerCup = setNumberOfCalories();} // Allows us to loop
totalCalories = numberOfCups * numberOfCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberOfCups + " cups and this amount contains " + totalCalories + " total calories.");
System.out.print("\n");
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static String setIngredients() {
System.out.println("Please enter the name of the ingredient: ");
Scanner scan = new Scanner(System.in);
try {
String ingredients = scan.nextLine();
System.out.println("\r");
return ingredients;
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCups() {
System.out.println("Please Enter Number Of Cups: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCups = scan.nextLine();
Float numberOfCupsFloat = Float.parseFloat(numberOfCups);
System.out.println("\n");
return numberOfCupsFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid Input must be a numeric value Please Try Again: ");
System.out.println("\n");
scan.nextLine();
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again.");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCalories() {
System.out.println("Please Enter Number Of Calories per cup: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCalories = scan.nextLine();
Float numberOfCaloriesFloat = Float.parseFloat(numberOfCalories);
System.out.println("\n");
return numberOfCaloriesFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid value Please enter a numeric value:");// if the input is incorrect the user gets prompted for the proper input
scan.nextLine();// if the input is incorrect the user gets prompted for the proper input
}
catch (Exception e){
scan.nextLine();
System.out.println("Error in input please try again.");
}
return null;
}
You may want to accept it as a string and check if it is numeric or not using String methods. Post that you can either move forward if format is correct or re prompt the user for correct value while showing the error.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(!numCups.chars().allMatch( Character::isDigit ))
{
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
numberCups = Double.parseDouble(numCups);
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
Alternatively you could also do this using try catch statements. I believe this would be a better way to parse double values
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(numberCups==0.0)
{
try {
numberCups = Double.parseDouble(numCups);
} catch (NumberFormatException e) {
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
}
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
I've taken your code and added support for input of fractional numbers. Comments added on important changes.
parseCups returns an Optional so we can tell if the input was valid or not.
parseIngredientValue does the work of deciding whether or not the input is a fraction and/or attempting to parse the input as a Double.
package SteppingStone;
import java.util.Optional;
import java.util.Scanner;
public class SteppingStone2_IngredientCalculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
String cupsStr = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); // In case ingredient is more than one word long.
Optional<Double> cups = Optional.empty();
while (cups.isEmpty()) { // repeat until we've got a value
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
cupsStr = scnr.nextLine();
cups = parseCups(cupsStr);
}
numberCups = cups.get();
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
// Using String.format to allow rounding to 2 decimal places (%2.2f)
System.out.println(String.format("%s uses %2.2f cups and this amount contains %2.2f total calories.",
nameOfIngredient, numberCups, totalCalories));
}
private static double parseIngredientValue(String input) {
if (input.contains("/")) { // it's a fraction, so do the division
String[] parts = input.trim().split("/");
double numerator = (double) Integer.parseInt(parts[0]);
double denomenator = (double) Integer.parseInt(parts[1]);
return numerator / denomenator;
} else { // it's not a fraction, just try to parse it as a double
return Double.parseDouble(input);
}
}
private static Optional<Double> parseCups(String cupsStr) {
double result = 0.0;
String input = cupsStr.trim();
String[] parts = input.split(" +"); // split on any space, so we can support "1 2/3" as an input value
switch (parts.length) {
case 2:
result += parseIngredientValue(parts[1]); // add the 2nd part if it's there note that there's no
// break here, it will always continue into the next case
case 1:
result += parseIngredientValue(parts[0]); // add the 1st part
break;
default:
System.out.println("Unable to parse " + cupsStr);
return Optional.empty();
}
return Optional.of(result);
}
}
Sample run:
Please Enter Ingredient Name:
Special Sauce
Please enter the number of cups of Special Sauce required:
2 2/3
Please enter the number of calories per cup of Special Sauce :
1500
Special Sauce uses 2.67 cups and this amount contains 4000.00 total calories.

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.

Java! How to go to the specific line?

I just started to code in Java and I have a question. After my "else" statement, I want to repeat my code again. How do I do that? Is there a keyword or something?
import java.util.Scanner;
public class UserInputStory {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println(
"Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
}
else {
System.out.println("Let's try again then!");
}
}
}
Place the body of your code that you want repeating inside a while loop and break when your end-condition is true:
public static void main(String[] args) {
while(true) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println("Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
break;
}
else {
System.out.println("Let's try again then!");
}
}
}
You can envelop our whole code by:
while(1)
ut its not a good approach and there must be some condition applied (depending upon the xontext of your program) which can take you out of the loop

Print array at given position

I am trying to print out two arrays at given position.
The program has two parts. One where the user is asked to enter a string(student name) and an int (student grade) at the end the user is asked to search for the name entered and to print out the student name and the grade
So far I cant't print any.
This is my code for populating the arrays...
System.out.println("Please Enter The Number Of Students In The Class!!");
int numberOfStudents = input.nextInt();
String []studentNames = new String[numberOfStudents];
int [] StudentGrades = new int[numberOfStudents];
int i;
for (i =0; i<numberOfStudents; i++)
{
System.out.println("Enter Student Name!");
studentNames[i]= input.next();
System.out.println("_________________");
System.out.println("Enter Student Grade");
StudentGrades[i] = input.nextInt();
System.out.println("_________________");
}
... and this for searching the name:
Scanner input = new Scanner(System.in);
String nameInput = input.next();
int cheak;
cheak = 0;
for ( String student : studentNames)
{
if (nameInput.equals(student))
{
cheak++;
}
}
if (cheak !=0)
{
System.out.println("Name Found ");
}
else
{
System.out.println("Name Not Found");
}
Now I want to print the student name that is entered in the search with the corresponding grade.
How do I accomplish that?
You have to just keep a record of the index of target name in the studentNames array.
You can modify the loop in the following way to get the index in the cheak variable -
cheak = 0;
for ( String student : studentNames)
{
if (nameInput.equals(student))
{
break;
}
cheak++;
}
if (cheak != numberOfStudents)
{
System.out.println("Name Found. Name = " + studentNames[cheak] + " Grade = " + StudentGrades[cheak]);
}
else
{
System.out.println("Name Not Found");
}
try the following:
for ( String student : studentNames) {
if (nameInput.equals(student)) {//if the student is found, stop the loop
break;
}
cheak++;
}
if (cheak != studentNames.length){
System.out.println("Name Found ");
System.out.println("The name is: " + studentNames[cheak]);
System.out.println("Grade is: " + studentGrades[cheak]);
} else {
System.out.println("Name Not Found");
}

Java scanner restrict integer < 1 & string input

Trying to figure out how to get my program to restrict the input of a integer less then 1 and also restrict input of strings in the scanner. Here's my code:
import java.util.Scanner; // Import scanner object
import java.io.*; // Import for file and IOException
public class Distance {
public static void main(String[] args) throws IOException {
int distance;
int speed, time;
String filename;
System.out.println("Welcome to Distance Calculator.");
// Create a scanner keyboard for user input
Scanner keyboard = new Scanner(System.in);
// Vehicle speed
System.out.print("Vehicle speed (MPH): ");
speed = keyboard.nextInt();
while (!keyboard.hasNextInt()) {
System.out.print("Please enter a valid #: ");
speed = keyboard.nextInt();
if (speed < 1) {
System.out.print("Please enter a # greater then 1: ");
keyboard.nextInt();
}
}
System.out.print("Time vehicle traveled (HR): ");
while (!keyboard.hasNextInt()) {
time = keyboard.nextInt();
if (time < 1) {
System.out.print("Please enter a valid time: ");
speed = keyboard.nextInt();
}
}
time = keyboard.nextInt();
keyboard.nextLine(); // Consume next line
// Get filename
System.out.print("File name for saving: ");
filename = keyboard.nextLine();
// Open file
String filePath = "C:/Users/Nik/Desktop/";
PrintWriter outputFile = new PrintWriter(filePath + filename);
outputFile.println("Hour Distance Traveled");
outputFile.println("-----------------------------");
for (int hour = 1; hour <= time; hour++) {
distance = (speed * hour);
outputFile.println(hour + "\t\t\t" + (distance + " Mi"));
}
outputFile.close();
System.out.print("Date written to " + filePath + filename);
}
}
Would really appreciate the assistance.
Well I believe that changing the "whiles" a bit like this might work like you want it to. It takes care of both the input problem when you insert something that's not an integer and the positive integer problem when a non positive integer is inserted. I tested it and I think it worked how it's supposed to. Try it out.
public static void main(String[] args) throws IOException{
int distance;
int speed, time;
String filename;
System.out.println("Welcome to Distance Calculator.");
// Create a scanner keyboard for user input
Scanner keyboard = new Scanner(System.in);
// Vehicle speed
System.out.print("Vehicle speed (MPH): ");
while (!keyboard.hasNextInt() ||
((speed = keyboard.nextInt()) < 1) ) {
System.out.print("Please enter a valid #: ");
keyboard.nextLine();
}
System.out.print("Time vehicle traveled (HR): ");
while (!keyboard.hasNextInt() ||
((time = keyboard.nextInt()) < 1) ) {
System.out.print("Please enter a valid #: ");
keyboard.nextLine();
}
keyboard.nextLine(); // Consume next line
// Get filename
System.out.print("File name for saving: ");
filename = keyboard.nextLine();
// Open file
String filePath = "C:/Users/Nik/Desktop/";
PrintWriter outputFile = new PrintWriter(filePath + filename);
outputFile.println("Hour Distance Traveled");
outputFile.println("-----------------------------");
for (int hour = 1; hour <= time; hour++) {
distance = (speed * hour);
outputFile.println(hour + "\t\t\t" + (distance + " Mi"));
}
outputFile.close();
System.out.print("Date written to " + filePath + filename);
}
I think this should work:
System.out.print("Vehicle speed (MPH): ");
speed = -1;
do {
System.out.println("Please enter a valid integer greater than 1");
if (keyboard.hasNextInt() {
speed = keyboard.nextInt();
}
} while (speed < 1)
I'm pretty sure the problem is coming from the ! in your while loop, however I think I have managed to clean up the code.
Disclaimer: I have not tested this code to see if it works, however I thought I would give it a shot, hope it helps.
My final code:
int distance;
int speed = 0, time;
String filename;
boolean validInput = false; // Boolean for validating scanner input
System.out.println("Welcome to Distance Calculator.");
// Create a scanner keyboard for user input
Scanner keyboard = new Scanner(System.in);
// Vehicle speed
System.out.print("Vehicle speed (MPH): ");
// Method for validating user input
while (validInput == false) {
if (!keyboard.hasNextInt()) { // check if keyboard scanner !integer
System.out.print("Please enter a valid #: "); // prompts user for valid input
keyboard.nextLine(); // consumes next line
}
else {
speed = keyboard.nextInt();
if (speed < 1) { // validates if speed > 0
System.out.print("Please enter a value greater then 1: "); // prompts user for valid speed
keyboard.nextLine(); // consumes next line
}
else validInput = true; // if statements are passed then set bool to True and end loop
}
}

Categories