Scanner needs entry to be entered twice - java

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);

Related

Exiting from while loop not working in java

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();
}

How do I get continuous user input?

I need a help trying to set my code to continuously receive user input for factorial numbers. It will produce a question and intake the user input but only once. I want it to continue asking the user for that input.
I tried to do a while loop however nothing shows up.
import java.util.Scanner;
public class FactorialRecursion
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
long userInput;
System.out.println("Please enter a number you would like find the factorial of.");
userInput = scan.nextLong();
long fc = FactorialRecursion.fact(userInput);
System.out.println("Factorial = " + fc);
}
public static long fact(long x)
{
if (x <= 0)
return 1;
else
return FactorialRecursion.fact(x - 1) * x;
}
}
The output is correct but I want my program to continue asking for that input.
public class Test{
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Receiving...");
}
{
System.out.println("Negative number Stopping the system...");
System.exit(1);
}
}
}
Without knowing how you were looping before (my assumption is that you were including the scanner instantiation which might have caused an issue), here is an implementation that I believe will work for you. This will continue to scan for a number, unless a negative number is entered. Therefore you have an actual exit condition that doesn't make sense for factorial, and the user can repeatedly enter and find the factorial of positive numbers.
In order for this to work, I instantiated the userInput variable to be 0 so that the loop will run for the first time. You can alteratively use a do...While loop in stead, but I prefer this method generally.
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
long userInput=0;
while(userInput >=0)
{
System.out.println("Please enter a number you would like find the factorial of. Enter a negative number to exit.");
userInput = scan.nextLong();
long fc = FactorialRecursion.fact(userInput);
System.out.println("Factorial = " + fc);
}
}
If you would like to see what the do-while loop would look like, just comment and I'll put a little more time into answering this. Also any questions you have comment away!

Why is this Scanner assigning null to a variable?

For a college assessment I'm having to use a Scanner called sc with a class-level scope, and the entirety of the program has to be contained in a single class. The main method calls a menu() method, which uses the Scanner and a for loop to call one of two methods in response to user input.
One of the two methods uses the Scanner to calculate the factorial of an input integer. Once the method is executed, the for loop in menu() continues. To avoid an InputMismatchException due to the user entering a float, I used try/catch. However when the program returns back to the menu() for loop the Scanner causes an InputMismatchException when assigning to choice. How can I get Scanner to prompt the user for input again? Apologies if I'm missing something obvious, this is the first programming language I've ever learned. This should be the stripped down compilable code:
package summativeassessment;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SummativeAssessment {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menu();
}
public static void menu(){
String fName;
String sName;
System.out.print("Enter your first name: ");
fName = sc.next();
System.out.print("Enter your last name: ");
sName = sc.next();
try{
for(int choice = 1; choice!=0;){
System.out.print("Option 1 to generate username. Option 2 to calculate factorial. Press 0 to quit: ");
choice = sc.nextInt();
switch(choice){
case 2:
System.out.println(fName+" "+sName+", you have selected option 2");
numberFactorial();
break;
case 0:
break;
default:
System.out.println("Invalid option. Please try again.");
}
}
} catch(InputMismatchException ex){
String msg = ex.getMessage();
System.out.println(msg);
}
}
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
}
}
}
I debugged your code and got this result:
If you enter a float as input you trigger the InputMismatchException but there is still something in your buffer. So the next time sc.nextInt() is called, it won't wait until you input a value because something is in the buffer already, so it takes the next value out of the buffer and tries to interpret is as an integer. However, it fails to do so, because it is not an integer, so an InputMismatchException is raised again and caught in your menu's catch, now leading to the exit of the program.
The solution is to draw whatever is left in the buffer after the exception was raised the first time.
So the working code will contain a buffer clearing sc.next() inside the exception:
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
sc.next();
}
}

I want to take a String input to continue a conditional branch

I want to take a string input from keyboard. But when I ran this program there are no option to take string input. I don't know what my fault is.
Here my code is:
import java.util.Scanner;
public class Input_Program {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int a,b;
System.out.println("Enter the first number :");
a=in.nextInt();
System.out.println("Enter the second number :");
b=in.nextInt();
System.out.println("Value of first number:"+a);
System.out.println("Value of second number:"+b);
System.out.println("Do you want Add two numbers");
System.out.println("To Continue: Type Yes");
String S=in.nextLine();
if("Yes".equals(S)||"yes".equals(S))
{
int sum=a+b;
System.out.println("Summation :"+sum);
}
}
}
I want to take an input from this code. But it's not working.
String S=in.nextLine();
if("Yes".equals(S)||"yes".equals(S))
{
int sum=a+b;
System.out.println("Summation :"+sum);
}
And the result of this code is :
run:
Enter the first number :
2
Enter the second number :
3
Value of second number:3
Do you want the Summation of two numbers
To Continue: Type Yes
BUILD SUCCESSFUL (total time: 9 seconds)
1) nextLine() according to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html "Advances this scanner past the current line and returns the input that was skipped" which is not the behavior you are looking for.
2) It seems that you are new to java, and there are naming conventions. Please do not start variable names with uppercase letters
3) I fixed your indentation, and also generalized the input to take in anything that starts with y. In the future make sure you write your code this way since it's easier to tell which lines of code are in if statements, and loops and such.
import java.util.Scanner;
public class Input_Program {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the first number :");
int a = in.nextInt();
System.out.println("Enter the second number :");
int b = in.nextInt();
System.out.println("Value of first number:" + a);
System.out.println("Value of second number:" + b);
System.out.println("Do you want Add two numbers");
System.out.println("To Continue: Type Yes");
String s = in.next();
if(s.toLowerCase().contains("y")){
int sum=a+b;
System.out.println("Summation :"+sum);
}
}
}

Why must you define the scanner inside the if statement?

Why does the code below work:
import java.util.Scanner;
public class WholeNumber
{
public static void main(String[] args)
{
System.out.println("Please enter a number:");
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt())
{
float number = scanner.nextFloat(); //The if statement is testing THIS scanner value.
System.out.println("The number you entered is an integer.");
}
else
{
System.out.println("The number you entered is not an integer.");
}
}
}
But this code doesn't:
import java.util.Scanner;
public class WholeNumber
{
public static void main(String[] args)
{
System.out.println("Please enter a number:");
Scanner scanner = new Scanner(System.in);
float number = scanner.nextFloat(); //But when I put the scanner out here, it doesn't work??
if (scanner.hasNextInt())
{
System.out.println("The number you entered is an integer.");
}
else
{
System.out.println("The number you entered is not an integer.");
}
}
}
It would seem like you would have to define the scanner first so the if statement could know what it was checking. Otherwise, how does it know what it is trying to check?
When I put the scanner.nextFloat line outside the if statement, though, it will compile but get stuck during run-time when the user is typing in input. And if I put the line outside and change the if statement to "number.hasNextInt," I get a compile-time error.
You are taking the value out of the Scanner before you are testing for the next int:
float year = scanner.nextFloat();
The above line removes the int from the Scanner so hasNextInt() will return false.
Side note: Not sure why you are using hasNextInt() with nextFloat() you should be using Float or Int...
If the "has"-call is after the "next"-call, the scanner will wait for 2 values.
This is because next___() waits for a value, consumes it, AND then returns it, while has___() waits for a value, pushes it back, AND then returns the presence of it.

Categories