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
}
}
Related
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.
I have the following code:
import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = keyboard.nextDouble();
while (go){
String next = keyboard.next();
if (next.equals("done") || next.equals("calculate")){
System.out.print(grade);
go = false;
}else{
grade+=keyboard.nextInt();
}
}
I am trying to find the average as it is a grade calculator, what i want to know is how would I apply The addition operation only to scanner inputs, and then ultimately find the average by how mnay inputs were entered.
Sample input:
60
85
72
done
Output:
72 (average) ===> (217/3)
You need a counter (e.g. count as shown below). Also, you need to first check the input if it is done or calculate. If yes, exit the program, otherwise parse the input to int and add it to the existing sum (grade).
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = 0;
int count = 0;
while (go) {
String next = keyboard.nextLine();
if (next.equals("done") || next.equals("calculate")) {
go = false;
} else {
grade += Integer.parseInt(next);
count++;
}
}
System.out.println((int) (grade / count) + " (average) ===> (" + (int) grade + "/" + count + ")");
}
}
I've been having issues catching non numbers.
I tried try / catch but I can't grasp a hold of it. If anything I get it to catch non numbers, but doesn't let the user try entering again... It just stops my code completely.
Here is my code:
package triangle;
import java.util.Scanner;
public class traingle {
public static void main(String[] args){
//explaining what the program is going to do
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");
//creating input 1,2,3 for user
Scanner angle1 = new Scanner(System.in); // Reading from System.in
System.out.println("Enter angle degree number 1: ");
int n = angle1.nextInt();
Scanner angel2 = new Scanner(System.in);
System.out.println("Enter angle degree number 2: ");
int n2 = angel2.nextInt();
Scanner angel3 = new Scanner(System.in);
System.out.println("Enter angle degree number 3: ");
int n3 = angel3.nextInt();
//this is just telling how much degrees the user had in total if they didnt match up to triangle standards
This should get you started.
package triangle;
import java.util.Scanner;
public class triangle {
public static void main(String[] args){
//explaining what the program is going to do
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\n");
System.out.println("this automated program will tell you if the angle you entered is isoceles, eqilateral or scalene");
//creating input 1,2,3 for user
Scanner s = new Scanner(System.in); // Reading from System.in
String line;
int [] angles = new int [3];
int count = 0;
do {
System.out.print("Enter angle degree number " + (count+1) + ": ");
line = s.nextLine();
while (true ) {
try {
angles[count] = Integer.parseInt(line);
System.out.println("You entered " + angles[count]);
count++;
break;
} catch (NumberFormatException e ) {
System.out.println("Invalid number: try again: ");
line = s.nextLine();
}
}
} while (count < 3);
}
}
You have a simple issue.. You just use one Scanner for the code in main method.
package triangle;
import java.util.Scanner;
public class traingle {
public static void main(String[] argc){
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");
Scanner angle1 = new Scanner(System.in);
System.out.println("Enter angle degree number 1: ");
int n = angle1.nextInt();
System.out.println("Enter angle degree number 2: ");
int n2 = angel2.nextInt();
System.out.println("Enter angle degree number 3: ");
int n3 = angel3.nextInt();
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.
I'm having an issue with the code below. It's all working fine, except I want the program to restart if the user types in "Y" at the end, and end if anything else is pressed.
However, whenever I type anything at the "Restart Calculator" prompt, it will stop running, regardless of whether I type in "Y" or "N". Validation with the Y/N is not too important here, I just want it to restart if Y is typed and end if anything else is typed.
Apologies for the noob code, Java beginner here.
import java.util.Scanner;
import java.text.*;
public class Savings {
public static void main(String[] args)
{
//Imports scanner, to read user's input
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
do {
//Asks for and receives user's initial deposit
int initial_Deposit;
do {
System.out.print("Enter initial deposit in dollars (Between $1 - $50000: ");
while (!scan.hasNextInt()) {
System.out.println("Please enter a valid number between '1-50000'");
scan.next();
}
initial_Deposit = scan.nextInt();
} while (initial_Deposit <= 0 || initial_Deposit >= 50001);
//Asks for and receives user's interest rate
double interest_Rate;
do {
System.out.print("Enter interest rate as a percentage between '0.1-100.0' (e.g. 4.0):");
while (!scan.hasNextDouble()) {
System.out.println("Enter interest rate as a percentage between '0.1-100.0' (e.g. 4.0):");
scan.next();
}
interest_Rate = scan.nextDouble();
} while (interest_Rate <= 0.0 || interest_Rate >= 100.1);
//Asks for and receives user's monthly deposit
int monthly_Deposit;
do {
System.out.print("Enter monthly deposit in dollars between '$1 - $5000: ");
while (!scan.hasNextDouble()) {
System.out.println("Enter monthly deposit in dollars between '$1 - $5000: ");
scan.next();
}
monthly_Deposit = scan.nextInt();
} while (monthly_Deposit <= 0 || monthly_Deposit >= 5001);
//Asks for and receives user's investment duration
int monthly_Duration;
do {
System.out.print("Enter investment duration (Between 1 and 12): ");
while (!scan.hasNextDouble()) {
System.out.println("Enter investment duration (Between 1 and 12): ");
scan.next();
}
monthly_Duration = scan.nextInt();
} while (monthly_Duration <= 0 || monthly_Duration >= 13);
//Asks for and receives user's first name
String first_Name;
System.out.print("Enter first name: ");
first_Name = input.next();
//Asks for and receives user's surname
String last_Name;
System.out.print("Enter surname: ");
last_Name = input.next();
//Formats first name to only first letter
char firstLetter = first_Name.charAt(0);
//Changes name to correct format
String formatted_Name;
formatted_Name = "Savings growth over the next six months for " + last_Name + ", " + firstLetter;
System.out.println(formatted_Name);
//Calculates the first balance
double balanceCurrent;
balanceCurrent = initial_Deposit + monthly_Deposit;
//Prepares to format currency
DecimalFormat df = new DecimalFormat("#.##");
//Defining variables
double balanceNew;
double interestEarned;
//Defining counter for while loop
int counter;
counter = monthly_Duration;
int month_Counter;
month_Counter = 1;
//While loop to calculate savings
while (counter > 0) {
balanceNew = balanceCurrent + (balanceCurrent *((interest_Rate /12)/100));
interestEarned = balanceCurrent *((interest_Rate /12)/100);
balanceCurrent = balanceNew + monthly_Deposit;
System.out.println("Balance after month " + month_Counter + ": $" + df.format((balanceNew)));
System.out.println("Interest earned for this month: $" + df.format(interestEarned));
counter = counter - 1;
month_Counter = month_Counter + 1;
}
//Formats data into a table
balanceCurrent = initial_Deposit + monthly_Deposit;
counter = monthly_Duration;
int month;
month = 0;
String dollarSign = "$";
String stringHeadingOne = "Month";
String stringHeadingTwo = "New Balance";
String stringHeadingThree = "Interest Earned";
String dividerOne = "----- ----------- ---------------";
System.out.println("");
System.out.printf("%-9s %s %19s \n", stringHeadingOne, stringHeadingTwo, stringHeadingThree);
System.out.println(dividerOne);
while (counter > 0) {
balanceNew = balanceCurrent + (balanceCurrent *((interest_Rate /12)/100));
interestEarned = balanceCurrent *((interest_Rate /12)/100);
balanceCurrent = balanceNew + monthly_Deposit;
month = month + 1;
System.out.printf("%-11s %s %s %13s %s \n", month, dollarSign, df.format((balanceNew)), dollarSign, df.format(interestEarned));
counter = counter - 1;
}
System.out.print("Restart Calculator? Y/N);");
} while (scan.next() == "Y");
}
}
while (scan.next() == "Y"); // Is checking for reference equality
When doing object comparisons in Java, use equals()
while (scan.next().equals("Y"));
Or, as the previous answer pointed out you can compare characters with the == operator
Try this:
scan.nextLine().charAt(0) == 'Y'
When comparing Strings or anyother object for that matter you need to use the .equals(Object other) method. You can only use == with primatives ( boolean, int, double,...)
scan.nextLine().equals("Y");
//or
scan.next().equals("Y");
There is also an method to take the string to Uppercase that would allow the user to enter "y" or "Y"
scan.next().toUpperCase().equals("Y");
You should be using the Equals method for Strings:
while ("Y".equals(scan.next()));