This code is working for the first scanner to accept ints but the second scanner throws a mismatch error. I cannot seem to find why it is doing this. Can anyone help me out?
I have tried everything and it is not working. I can get the first scanner to accept strings multiple times. The second scanner will accept ints but if i try to input a string even one time then the program crashes. How can this be resolved?
For more details of full program click here:
pastebin.com/iMgNncMH
Password: ENdu4mWLNm
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter two integers:");
while (!scanner.hasNextInt()) {
scanner.next();
}
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
System.out.println();
I looked through the code, and it is working fine on BlueJ Here is the console image. Could you explain a little more about what error you are getting while compilation? Also here's the full code
import java.util.*;
public class prime {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter two integers:");
while (!scanner.hasNextInt()) {
scanner.next();
}
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
System.out.println();
}
}
}
The error being thrown is InputMismatchException. Its happening on the n2 why this is happening... idk I'm about as surprised as you are. Weird how it doesn't throw on n1 its the same issue. Perhaps it has something to do with the next int your looking for. Here's what I would suggest. Basic error handling using a Boolean while loop. If the catch is thrown it will never hit that true so two integers must be entered.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n1 = 0;
int n2 = 0;
System.out.println("Enter two integers:");
boolean validEntry = false;
while(!validEntry) {
try {
n1 = scanner.nextInt();
n2 = scanner.nextInt();
validEntry = true;
}
catch(InputMismatchException ex){
System.out.println("Please refrain from entering words. only numbers aloud");
scanner.nextLine();
}
}
}
Ps that other while loop you had is never hit. I can see what you were going for though.
Related
I am new to java programming.I want to calculate the sum and want to exit the program if user enters "N" and again loop if user enters "Y".But,it is not getting me out of loop even I enter "N".
public class Program {
public static void main(String[] args) {
boolean a=true;
while (a) {
System.out.println("enter a number");
Scanner c=new Scanner(System.in);
int d=c.nextInt();
System.out.println("enter a number2");
Scanner ce=new Scanner(System.in);
int df=ce.nextInt();
int kk=d+df;
System.out.println("total sum is"+kk);
System.out.println("do you want to continue(y/n)?");
Scanner zz=new Scanner(System.in);
boolean kkw=zz.hasNext();
if(kkw) {
a=true;
}
else {
a=false;
System.exit(0);
}
}
}
I didnt know where I made the mistake? Is there any other way?
First of all, your a variable is true if scanner.hasNext() is true, leading to a being true with every input, including "N" which means, your while loop will keep on going until there are no more inputs.
Second of all, you could optimize your code the next way:
I suggest getting rid of a and kkw to make your code cleaner and shorter.
Use only one Scanner and define it outside of the loop. You don't need more than one Scanner for the same input. Also, initializing a Scanner with every loop is resource-consuming.
Use meaningful variable names. Programming should not only be efficient, but also easy to read. In this tiny code it's a minor issue but imagine having an entire program and, instead of adding features and bug-fixing, you had to search for the meaning of every variable.
Here's an optimized and working version of your code:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number");
int input1 = scanner.nextInt();
scanner.nextLine(); // nextInt() doesn't move to the next line
System.out.println("Enter a second number:");
int input2 = scanner.nextInt();
scanner.nextLine();
System.out.println("Total sum is " + (input1 + input2)); /* Important to
surround the sum with brackets in order to tell the compiler that
input1 + input2 is a calculation and not an appending of
"Total sum is "*/
System.out.println("Do you want to continue? (Y/N)");
if (scanner.hasNext() && scanner.nextLine().equalsIgnoreCase("n"))
break;
}
scanner.close();
try (Scanner in = new Scanner(System.in)) {
boolean done = false;
while (!done) {
System.out.println("enter first number");
int d = in.nextInt();
System.out.println("enter second number");
int df = in.nextInt();
int kk = d + df;
System.out.println(String.format("total sum is %d", kk));
System.out.println("do you want to continue(y/n)?");
String cont = in.next();
done = cont.equalsIgnoreCase("n");
}
} catch(Exception e) {
e.printStackTrace();
}
I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}
My application always crashs when it gets to scan.getLine() in main.
The error I get is "java.util.NoSuchElementException: No line found".
Here is the code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = new String();
int operation=0;
operation = getOperation();
System.out.print("Enter string:");
s = scan.nextLine(); // program crashes before I have the chance to input anything
System.out.println(s);
scan.close();
}
public static int getOperation(){ //get operation between 1-10
Scanner scan= new Scanner(System.in);
boolean input=true;
int op=0;
while (input){ // get correct input from the user
if (scan.hasNextInt())
{
op=scan.nextInt();
if (op < 1 || op > 10)
System.out.print("Please enter valid operation 1-10:");
else
input=false;
}
else
System.out.print("Please enter valid operation 1-10:");
scan.nextLine(); // to clear the buffer
}
scan.close();
return op;
}
The strange thing is that when I insert before I write getOperation function , and the entire getOperation was inside main, the application worked fine. Only after I moved the code to getOperation method , then the scan.nextLine() crashes, before I even have a change to enter anything in the console.
Try using this tiny code snippet
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
Scanner s2 = new Scanner(System.in);
s2.close();
s1.nextLine();
}
The close function closes the InputStream System.in
Since you are closing a scanner with scan.close(); in getOperation() a following call on another scanner with the same InputStream will cause the exception that you are running into.
You don't need the Scanner in main:
public static void main(String[] args) {
String s = new String();
System.out.print("Enter string:");
int operation = 0;
operation = getOperation();
s = "" + operation; // program crashes before I have the chance to input anything
System.out.println(s);
}
output:
Enter string:11
Please enter valid operation 1-10:1
1
I did see other questions like mine but my program was quite different so I couldn't figure out the problem. Basically, when I'm asked to enter code using this program, it needs to be entered twice. I can't figure out why.
Anyone know what I'm doing wrong? I'm sure it's something simple I'm missing.
package prac4;
import java.util.Scanner;
public class PrintNums {
public static void main(String[] args) {
int number=1;
Scanner sc = new Scanner(System.in);
System.out.println("What number should I count to?");
while (sc.nextInt()<0){
System.out.println("Please enter a positive integer: ");
if(sc.nextInt()>0){
number = sc.nextInt();
}
}
number = sc.nextInt();
sc.close();
System.out.println(number);
}
}
you are asking input 2 times (sc.nextInt()), so if you want to get the value once you should call sc.nextInt() once. you can change the snippet like below.
package prac4;
import java.util.Scanner;
public class PrintNums {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number=sc.nextInt();
System.out.println("What number should I count to?");
while (number<0){
System.out.println("Please enter a positive integer: ");
number = sc.nextInt();
}
sc.close();
System.out.println(number);
}
}
Every time you call sc.nextInt() program hangs and waits for your input. You need to call sc.nextInt() only once and assign number only once per cycle and then check your condition:
while ((number = sc.nextInt()) < 0) {
System.out.println("Please enter a positive integer: ");
}
System.out.println(number);
I tried using following code for reading int input
import java.util.*;
public Add{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<>();
while(scan.hasNextInt()){
arr.add(scan.nextInt());
}
System.out.println(arr);
}
}
When I run the program with any input say -
1 2 4
It does not stop till I press CTRL+c. I have also tried some other variations(for example tried to read it as array of String but that also did not work) but they are the same.Problem is that I don't want to give the size of the input in advance. How can I parse int from console input?
You will need to check for certain input and break from the loop as hasNextInt will wait for input from keyboard. You could solve it by following:
int number;
while(scan.hasNextInt()){
number = scan.nextInt();
if (number == -1) {//if user types in -1, then you will come out of the loop.
break;
}
arr.add(number);
}
Since you are using scanner, you may try the following trick instead of using the ArrayList -
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while (sc.hasNextInt()) {
int num = sc.nextInt();
System.out.println("Your entered number is: " + num);
}
If you use hasNextInt() then you don't have to think about the parsing of number. A token that is not a integer will break out you from the loop.