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 + " ");
}
}
}
Related
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 ();
Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
{
System.out.println("What is the answer to the following problem?");
Generator randomNum = new Generator();
int first = randomNum.num1();
int second = randomNum.num2();
int result = first + second;
System.out.println(first + " + " + second + " =");
int total = Keyboard.nextInt();
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
}
}
}
}
I'm trying to keep the program to continue but if the user enters y and closes if he enters n.
I know that I should use a while loop but don't know where should I start the loop.
You can use a loop for example :
Scanner scan = new Scanner(System.in);
String condition;
do {
//...Your code
condition = scan.nextLine();
} while (condition.equalsIgnoreCase("Y"));
That is a good attempt. Just add a simple while loop and facilitate user input after you ask if they want to continue or not:
import java.util.*;
class Main
{
public static void main(String [] args)
{
//The boolean variable will store if program needs to continue.
boolean cont = true;
Scanner Keyboard = new Scanner(System.in);
// The while loop will keep the program running unless the boolean
// variable is changed to false.
while (cont) {
//Code
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
}
}
}
}
You may also read up on other kinds to loop and try implementing this code in other ways: Control Flow Statements.
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");
}
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.
I have tried various techniques to check the values of user input in this method. The user should only be able to enter a '1' or a '0'. If any other input is used there should be an error message and the program exits. Any ideas? I got it to work for the first digit but not the second through the tenth.
System.out.println("Enter a ten digit binary number. Press 'Enter' after each digit. Only use one or zero. :");
binary[0] = keyboard.nextInt();
for (index = 1; index < 10; index++)
binary[index] = keyboard.nextInt();// fill array with 10 binary
// digits from user. User
// must press 'Enter' after
// each digit.
Try this:
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext())
{
final String input = scanner.next();
try
{
int num = Integer.parseInt(input, 2);
}
catch (NumberFormatException error)
{
System.out.println(input + " is not a binary number.");
//OR You may exit here, if you don't want to continue
}
}
Try this code part :
import java.util.Scanner;
public class InputTest
{
public static void main(String... args) throws Exception
{
Scanner scan = new Scanner(System.in);
int[] binary = new int[10];
for (int index = 0; index < 10; index++)
{
int number = scan.nextInt();
if (number == 0 || number == 1)
{
binary[index] = number;
System.out.println("Index : " + index);
}
else
System.exit(0);
}
}
}