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.
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 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!
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 am trying to read an integer from the user, then print even if that number is an even number or odd otherwise. I have been told I can assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
What am I missing? Any ideas on how I can get the desired inputs and expected outputs? Test1[3][Test4]4
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int even = scan.nextInt();
int odd = scan.nextInt();
if ((even%2)==0){
System.out.println("Type a number:"+ even);
}
else {
System.out.println("Type a number:"+ odd);
}
}
}
The problem is that you have all your variables and order of the flow of your program mixed up. In English this is what you are doing
Prompt user for an integer, call that integer "even"
Prompt user for an integer, call that integer "odd"
If the integer called "even" is divisible by 2 without a remainder then print "type a number" and then the value of the integer called "even"
Otherwise print "type a number" and then the value of the integer called "odd"
You only need to read a value from the user once, then decide which message to print based on that value:
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
System.out.println("Type a number:");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if ((number%2)==0){
System.out.println("even");
}
else {
System.out.println("odd");
}
}
}
I have pointed out some issues in your code. Please correct them.
import java.util.Scanner;
//follow java naming convention and name class as "EvenOdd"
public class evenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt(); //renamed to number
int odd = scan.nextInt(); //do not need this variable
if ((number %2)==0){
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
}
Ask the user the question first so that he knows he has to input a number
System.out.println("Type a number: ");
You can simply just get 1 input from the user and store on the same variable
int input = scan.nextInt();
Then you would just check that 1 input with the if/else and display the correct output
if ((input%2)==0){
System.out.println(input + " is even.");
}
else {
System.out.println(input + " is odd.");
}
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);