Have been struggling with this for a day, reading the discussion forum back and forth, no result. Anyone can tell me why the second call of the function aMenu() returns a zero and does not wait for new user input instead? I tried various things, like hasNextInt(), nextLine(), nothing worked. Shouldn't hasNextInt() block until the user writes something? How can I solve this? Thanks.
package FirstJavaPackage;
import java.util.Scanner;
public class testScanner
{
public static void main(String[] args)
{
int choice = aMenu();
System.out.println("You typed: "+choice);
choice = aMenu();
System.out.println("You typed: "+choice);
}
public static int aMenu()
{
int result = 0;
System.out.println("In aMenu... enter an int: ");
Scanner keyboard = new Scanner(System.in);
if (keyboard.hasNextInt())
result = keyboard.nextInt();
keyboard.close();
return result;
}
}
The output is:
In aMenu... enter an int:
2
You typed: 2
In aMenu... enter an int:
You typed: 0
You need to re-use the same Scanner object across the calls to aMenu():
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int choice = aMenu(keyboard);
System.out.println("You typed: "+choice);
choice = aMenu(keyboard);
System.out.println("You typed: "+choice);
}
public static int aMenu(Scanner keyboard)
{
int result = 0;
System.out.println("In aMenu... enter an int: ");
result = keyboard.nextInt();
return result;
}
For further discussion, see How to use multiple Scanner objects on System.in?
After the first call, you actually close the System.in input stream.
From the Scanner.close() documentation:
When a Scanner is closed, it will close its input source if the source
implements the Closeable interface.
Try not to close your scanner at the end of aMenu: initialize the scanner outside the aMenu method and make the method use it.
Since scanner.close will close the entire input source, you should pass scanner to your aMenu method and do something like this:
import java.util.Scanner;
public class TestScanner
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int choice = 0;
do
{
choice = aMenu(keyboard);
System.out.println("You typed: " + choice);
} while (choice > 0);
keyboard.close();
}
public static int aMenu(Scanner keyboard)
{
int result = 0;
System.out.println("In aMenu... enter an int: ");
if (keyboard.hasNextInt())
result = keyboard.nextInt();
return result;
}
}
Related
Create a program that asks the user to input numbers (integers). The program prints "Type numbers” until the user types the number -1. When the user types the number -1, the program prints "Thank you and see you later!" and ends.
This is the code:
import java.util.Scanner;
public class TheSumOfSetOfNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number=0, sum=0, count=0, even=0, odd=0;
double average=0;
System.out.println("Type numbers: ");
while(true)
{
number=Integer.parseInt(reader.nextLine());
if(number==(-1)) break;
}
}
When I check it, this is the error :
remember to read user input with Integer.parseInt( reader.nextLine() );
call it only once!
If I only call it once, how it will be possible to scan a lot numbers?
This is what you will use in this scenario. Using a do while loop, you can get your output
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int num = 0;
do {
System.out.println("Enter Numbers");
num = scan.nextInt();
} while (num != -1);
System.out.println("Thanks ! See you later");
}
Note: This runs until the user enters -1:
while (reader.hasNextLine()) {
number = Integer.parseInt(reader.nextLine());
if (number == -1) {
System.out.println("Thank you and see you later!");
break;
}
}
If you are always typing numbers I will use this:
final Scanner scanner = new Scanner(System.in);
boolean exit = false;
System.out.println("Type numbers:");
while (!exit){
if (scanner.nextInt() != -1)
exit = true;
}
System.out.println("Thank you and see you later!");
But you have to call scanner object each time you would like to read something from the imput.
You need to put System.out.println("Type numbers: "); inside while loop.
Since you are giving only integers as input, no need to parse it.
Below is required code:
import java.util.Scanner;
public class TheSumOfSetOfNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number=0, sum=0, count=0, even=0, odd=0;
double average=0;
// we need to loop "Type numbers:" each time umtil "-1" is pressed
while(number != -1)
{
System.out.println("Type numbers: ");
number=reader.nextInt();
}
// user must have been typed "-1" therefore it exits from whle loop
System.out.println("Thank you and see you later!");
// now there is nothing in main() fxn, therefore, the program will stop
}
}
Output:
Type numbers:
1
Type numbers:
3
Type numbers:
8
Type numbers:
9
Type numbers:
0
Type numbers:
-1
Thank you and see you later!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = -1;
do {
System.out.println("Welcome to Java Programming!");
System.out.println("Print Again? (y/n)");
num = input.nextLine();
} while (num.equalsIgnoreCase(-1));
}
}
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int flag=0,n;
while(flag!=1){
n=sc.nextInt();
if(n==-1){
flag=1;
}
}
System.out.print("Thank you and see you later!");
}
}
I am trying to write a program that takes a user's input and outputs the number of characters they typed in. I have to do this by creating a method that calculates the amount of characters, then call that method in main to output the results. I was encouraged to use a for loop, but I don't see how that would work. I can calculate the number of characters using length(), but I can't figure out how to make my method work. This is what I have so far:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
return;
}
public static int GetNumOfCharacters(int userCount) {
int i = 0;
String userInput = "";
userCount = userInput.length();
return userCount;
}
}
My method is not returning the length of the string, it just gives me 0 or an error.
Right now, you are never calling your "GetNumOfCharacters" method in your main. The way Java programs work, is by calling the main method and executing line per line what lies there. So you need to call you method from inside the main method. On the other hand, it should get the Stirng as a parameter, so you can get its length. It would look something like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
int lenInput = GetNumOfCharacters(userInput);
System.out.println("The length was: "+lenInput+" characters");
}
public static int GetNumOfCharacters(String userInput) {
int len = userInput.length();
return len;
}
A problem is that you are not actually calling the method
so try
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
System.out.println ("The length is " + GetNumOfCharacters (userInput))
}
// need to pass string into this method
public static int GetNumOfCharacters(String myString) {
int userCount = myString.length();
return userCount;
}
}
Your question included the line:
I was encouraged to use a for loop, but I don't see how that would
work.
There's no elegant way to do this in Java because you are assumed to use String.length() to get the length of strings. There is no 'end of string' marker as there is in, say, C. However you could mimic the same effect by catching the exception thrown when you access past the end of the string:
for (int len = 0; ; len++) {
try {
text.charAt(len);
} catch (StringIndexOutOfBoundsException ex) {
return len;
}
}
That's not a nice, efficient or useful piece of code but it does demonstrate how to get the length of a string using a for loop.
Problems with your code:
No Function call
Add function call in main() as int count=GetNumOfCharacters(userInput);
Parameter datatype mismatch
change the datatype in function definition from int to String as public static int GetNumOfCharacters(String userInput) {
Unwanted return statement in main()
remove the return from main()
Not displaying the value returned from GetNumOfCharacters
Add System.out.print("Number of characters: "+ count); inside main()
Code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
int count=GetNumOfCharacters(userInput);
System.out.print("Number of characters: "+ count);
}
public static int GetNumOfCharacters(String userInput) {
int userCount = userInput.length();
return userCount;
}
OR
Function is not really needed,you can remove the function and do it like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
System.out.print("Number of characters: "+ userInput.length());
}
If you don't want to use predefined methods, you can do like this..
public static void main(String args[]){
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.println("You entered: "+userInput);
char a[]=userInput.toCharArray();
int count=0;
for(char c : a){
count++;
}
System.out.println("length of the string is:"+count);
}
public class Main{
public static void main(String args[]){
int i = nextInt();
}
public int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()){
scanner.nextLine();
Printer.println(Printer.PLEASE_NUMBER);
}
i=scanner.nextInt();
scanner.close();
return i;
}
}
The code above is how I'm trying to force a user to input a int value, but I get the nosuchelement exception, as the scanner.nextLine() reads a NULL.
In c++ the software waits for the user to input something. Is there anything I can do to force the program to stop, wait for the user to input something and then make the check?
EDIT:
So I'm having problems regardless, if I use scanner outside of Main class, it gives that error...
If you want the user to input and the scanner to pick up solely an integer value Scanner provides the method:
int i = scanner.nextInt();
Where i will store the next value entered into the console. It will throw an exception if i is not an integer.
Here is an example: Let's say I want the user to input a number and then I want to spit it back out to the user. Here would be my main method:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please print your number: ");
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
}
Now to check whether i is a integer you can use an if statement. However if you want the program to repeat until the user inputs an integer you can use a while loop or a do while loop where the loop's arguments would check if i is an integer.
Hope this is what you were looking for! By the way avoid naming your method nextInt() as the import java.util.Scanner; already has that method name. Don't forget imports as well!
You can do this:
public static void main(String[] args) {
System.out.println("" + nextInt());
}
public static int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!scanner.hasNextInt()){
System.out.println("Please enter a number:");
scanner.nextLine();
}
i = scanner.nextInt();
scanner.close();
return i;
}
This will cause the program to stop and wait for input each time the loop is executed. It will keep looping until it has an int in the scanner.
This works. There surely is a better solution.
EDIT As predicted. Check this,
import java.util.Scanner;
public class NewMain{
static boolean badNumber;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do{
System.out.print("Please print your number: ");
try{
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
badNumber = false;
}
catch(Exception e){
System.out.println("Bad number");
sc.next();
badNumber = true;
}
}while(badNumber);
}
}
package exercises;
import java.util.*;
public class Try_and_catch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=1;
do
{
System.out.println("Enter first number");
int n1 = input.nextInt();
System.out.println("Enter second number");
int n2 = input.nextInt();
int sum= n1/n2;
System.out.println(sum);
} while(x==1);
}
}
The code above requires input only integers, my question is how to handle the error whenever the user input a character?
Use a try block:
boolean again = true;
int n1;
while (again) {
try {
System.out.println("Enter first number");
input.nextInt();
again=false;
}
catch(InputMismatchException ime)
{
// do nothing!
}
}
What happens here is pretty simple: if we get an exception, then "again" is not set to true and we go back around in the loop. If we get out of the try block without an exception, then again is toggled and we go merrily on our way.
I need int num to only accept numbers. If I input letters I get an error. Is there a way to immediately flag letters, or do I have to take num in as a string and run loops?
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Input a number.");
int num = input.nextInt();
}
}
You must use Scanner.hasNextInt():
It Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
public static void main(String[] args)
{
System.out.println("Input a number.");
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num = sc.nextInt();
System.out.println(num);
}
You probably want to do something like this:
import java.util.InputMismatchException
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input an integer.");
int num = 0; // or any other default value
try {
num = input.nextInt();
} catch (InputMismatchException e) {
System.out.println("You should've entered an integer like I told you. Fool.");
} finally {
input.close();
}
}
}
If the user enters something that is not an integer, the code within the catch block will be executed.