I am allowing the user to enter numbers via command line. I would like to make it so when the user enters more then one number on the command line at a time it displays a message asking for one number then press enter. then carries on.
here is my code. If someone could show me how to implement this I would appreciate it.
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
try{
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
catch (InputMismatchException e) {
System.out.println("Stop it swine! Numbers only! Now you have to start over...");
main(args);
return;
}
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
}
As suggested in the comments to the question: Just do not scan the line you read for numbers, but parse it as a single number instead using Double.valueOf (I also beautified the rest of your code a little, see comments in there)
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
// we can use a for loop here to break on q and read the next line instead of that while you had here.
for (String inputs = scan.nextLine() ; !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
try{
myArr.add(Double.valueOf(inputs));
count++; //that'S even shorter than count += 1, and does the exact same thing.
System.out.println("Please enter another number or press Q for your average");
}
catch (NumberFormatException e) {
System.out.println("You entered more than one number, or not a valid number at all.");
continue; // Skipping the input and carrying on, instead of just starting over.
// If that's not what you want, just stay with what you had here
}
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
(Code untested, so there may be errors in there. Please notify me if you got one ;))
String[] numbers = inputs.split(" ");
if(numbers.length != 1){
System.out.println("Please enter only one number");
}
Related
I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
I'm trying to create a loop by entering the number to be added and then blocking the loop with a "exit" input from the user..but it's not working properly.
import java.util.Scanner;
public class main {
public static void main(String[] args)
{
int i,n=0,s=0;
double avg;
{
System.out.println("Input the numbers : ");
}
for (i=0;i<100;i++)
{
String input = new java.util.Scanner(System.in).nextLine ();
if(input.equals("exit")){
break;
}
Scanner in = new Scanner(System.in);
n = in.nextInt();
s +=n;
}
System.out.println("The sum of numbers is : " +s);
}
}
You have a couple of problems. One (minor) is that you are creating two scanners. Another (medium) is that your loop is set up to only go up to 100 - this is a magic number, and there's no reason to put in this artificial constraint. But your biggest problem is that you are ignoring the first entry in the loop if it is a number and not 'exit'
{
int i,n=0,s=0;
double avg;
boolean adding = true;
System.out.println("Input the numbers : ");
Scanner sc = new java.util.Scanner(System.in);
while(adding)
{
String input = sc.nextLine ();
if(input.equals("exit")){ // should proably be "EXIT" or equalsIgnoreCase
adding = false;
} else {
try {
int val = Integer.parseInt(input);
s += val;
} catch (NumberFormatException nfe) {
System.err.println ("expecting EXIT or an integer");
}
}
}
System.out.println("The sum of numbers is : " +s);
}
After this line your console does not have any next line or entry to read.
String input = new java.util.Scanner(System.in).nextLine ();
This program is for computing the digits of an integer. So there is chances to enter the input by user may string("raju" whatever it may be), number(12334), combination(string & number i.e, 234dsd) and nothing(he doesn't enter anything), isn't it? There might be another chances too I don't know(If there is mention it here).Try out with various inputs and the problems here are when I entered number and nothing. If input is number "result not coming" cmd prompt not continuing further and input is nothing(not entered) if statement is not executing. when the cmd prompt goes like that?
//computing digits of integer.
import java.util.Scanner;
class Main
{
public static void main (String w[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a number");
String g=s.nextLine();
System.out.println("Entered value is"+g);
if(g==null)
{
System.out.println("Enter atleast one number");
}
else
{
try
{
int st=Integer.parseInt(g);
int sum=0;
while(st>=0)
{
int value=st%10;
st=st/10;
sum=value+sum;
}
System.out.println("the sum of digits: "+sum);
}catch (NumberFormatException nfe)
{
System.err.println("Invalid input. Enter only number...");
}
}
}
}
It is hard to understand you are asking here, but if you are asking you code is not trying again when the user inputs invalid input, the answer is that it is because your code has no loop to do that.
Repetition of something (in this case, the task of asking for input) generally requires a loop of some kind.
If you indented your code properly, this would probably be more obvious to you.
Try this one
//computing digits of integer.
import java.util.Scanner;
public class Main {
public static void main(String w[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
String g = s.nextLine();
System.out.println("Entered value is " + g);
try {
int st = Integer.parseInt(g);
int sum = 0;
while (st > 0) {
int value = st % 10;
st = st / 10;
sum = value + sum;
}
System.out.println("the sum of digits: " + sum);
} catch (NumberFormatException nfe) {
System.err.println("Invalid input. Enter only number...");
}
}
}
None of the answers so far explicitly mentioned the problem: There is an endless loop here:
int st=Integer.parseInt(g);
int sum=0;
while(st>=0)
{
int value=st%10;
st=st/10;
sum=value+sum;
}
because st never becomes negative when you start with a positive value.
I want the user to enter integers into an array. I have this loop I wrote which has a try and catch in it, in case a user inserts a non integer. There's a boolean variable which keeps the loop going if is true. This way the user will be prompted and prompted again.
Except, when I run it, it gets stuck in a loop where it repeats "Please enter # " and "An Integer is required" without letting the user input a new number. I reset that number if an exception is caught. I don't understand.
import java.util.*;
public class herp
{
//The main accesses the methods and uses them.
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array"+" and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize+1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length)
{
// Not into will turn true and keep the loop going if the user puts in a
// non integer. But why is it not asking the user to put it a new checkint?
while(notint)
{
try
{
notint = false;
System.out.println("Please enter #"+ prompt);
checkint = scan.nextInt();
}
catch(Exception ex)
{
System.out.println("An integer is required." +
"\n Input an integer please");
notint = true;
checkint = 1;
//See, here it returns true and checkint is reset.
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
}
}
Once the scanner has thrown an InputMismatchException it cannot continue to be used. If your input is not reliable, instead of using scanner.nextInt() use scanner.next() to obtain a String then convert the string to an int.
Replace:
checkint = scan.nextInt();
With:
String s = scan.next();
checkint = Integer.parseInt(s);
I have corrected it like below. I don't rely on exception, but check if the next Scanner input is int (using hasNextInt()). If not int, just consume Scanner token and wait for the next user input.
Looks like it is working, apart from 0 being inserted as a first array element, because you started indexing prompt from 1.
public class Herp {
//The main accesses the methods and uses them.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array" + " and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize + 1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length) {
while (notint) {
notint = false;
System.out.println("Please enter #" + prompt);
// check if int waits for us in Scanner
if (scan.hasNextInt()) {
checkint = scan.nextInt();
} else {
// if not, consume Scanner token
scan.next();
System.out.println("An integer is required."
+ "\n Input an integer please");
notint = true;
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
for (int i : mainarray) {
System.out.print(i + " ");
}
}
}
Hey guys so i've been trying to answer this question for hours:
Write a program that asks the user to input a set of floating-point values. When the
user enters a value that is not a number, give the user a second chance to enter the
value. After two chances, quit reading input. Add all correctly specified values and
print the sum when the user is done entering data. Use exception handling to detect
improper inputs.
I've tried a few different things but i always have the same problem. Once something that isn't a number is given as input, the program outputs the message prompting for another input however the chance is not given, that is to say after 1 incorrect input it prints that message and jumps straight to printing the sum. The best i could do is below i'm just not sure how to approach this problem. Any help is greatly appreciated.
import java.util.Scanner;
import java.util.InputMismatchException;
public class q6{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean firstChance = true;
boolean secondChance = true;
double sum = 0;
while (secondChance){
try{
while (firstChance){
try{
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
}
catch (InputMismatchException ex){
firstChance = false;
}
System.out.print("Please enter a number to continue or something else to terminate: ");
double input = in.nextDouble();
sum = sum + input;
firstChance = true;
}
}
catch (InputMismatchException e){
secondChance = false;
}
}
System.out.print("The sum of the entered values is " + sum);
}
}
i'm just not sure how to approach this problem
Pseudocode could be as follows:
BEGIN
MAX_INPUT = 2;
i = 0;
WHILE i < MAX_INPUT
TRY
num = GET_NUM();
CATCH
continue;
FINALLY
i++
END WHILE
END
Since the parsing of input to double is not successful, the scanner does not go past the given input. From javadoc Scanner
Scans the next token of the input as a double. This method will throw
InputMismatchException if the next token cannot be translated into a
valid double value. If the translation is successful, the scanner
advances past the input that matched.
Since the translation is not successful, it does not advance. So, in the catch block you could call in.next() to skip the token.
You could use an integer counter instead of the boolean variables firstChance and secondChance and do something like:
int attempts = 0;
while(attempts < 2) {
try {
//Get user input - possible exception point
//Print sum
} catch(InputMismatchException e) {
attempts++;
//Continue?
}
}
import java.util.*;
public class q6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double inputNumber, sum = 0.0;
int correctCount = 0, wrongCount = 0;
while(wrongCount <=1) {
System.out.println("Please enter a numeric floating value:");
try {
inputNumber = in.nextDouble();
correctCount++;
sum += inputNumber;
if(correctCount >= 2)
break;
} catch(InputMismatchException e) {
wrongCount++;
in = new Scanner(System.in);
continue;
}
}
System.out.println(sum);
}
}
You need to break your while loop when you encounter a "bad" input. Then, you'll need to set firstChance to true again, so you can access the second while, you also will need a counter that counts the number of the attempts (I named it chances):
int chances = 0;
while (secondChance){
firstChance = true;
try{
while (firstChance){
try{
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
}
catch (InputMismatchException ex){
chances ++;
in = new Scanner(System.in);
firstChance = false;
}
if(!firstChance && chances < 2)
break;
if(chances >= 2) {
System.out.print("Please enter a number to continue or something else to terminate: ");
double input = in.nextDouble();
sum = sum + input;
firstChance = true;
}
}
}
catch (InputMismatchException e){
secondChance = false;
}
}
As stated in my comment, in order to not deal with Scanner wrong read, it would be better to use Scanner#nextLine() and read the data as String, then try to parse it as double using Double#parseDouble(String) since this method already throws NumberFormatException and you can handle this error. Also, it would be better that your code could handle more than 1 request (if your teacher or somebody else asks to do this):
final int REQUEST_TIMES = 2;
double sum = 0;
for(int i = 1; i <= REQUEST_TIMES; i++) {
while (true) {
try {
if (i < REQUEST_TIMES) {
System.out.print("Please enter a number: ");
} else {
System.out.print("Please enter a number to continue or something else to terminate: ");
}
String stringInput = in.nextLine();
double input = Double.parseDouble(stringInput);
sum += input;
} catch (NumberFormatException nfe) {
System.out.println("You haven't entered a valid number.");
break;
}
}
}
The logic is to read the input once, if it is correct then display the sum, else read the input again and display the sum if the input is correct.
public class q6 {
static int trial = 0;
public static void main(String[] args) {
double sum = 0;
while (trial <= 2) {
Scanner in = new Scanner(System.in);
try {
trial++;
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
trial=3;
} catch (InputMismatchException ex) {
trial++;
if (trial == 4){
System.out.println("You have entered wrong values twice");
}
}
}
if (trial <= 3){
System.out.print("The sum of the entered values is " + sum);
}
}
The above program is just a rough idea, you can improve this to adapt to your need.