In order to make my program more streamlined (Without try and catch everywhere), I tried to create a seperate method just for getting data. I have one for Doubles, and Strings, as well.
For some reason, when I try to use this method, it is completely ignored, and passed by like a comment. Is there something I'm doing wrong?
public int inputint(){
Scanner sc = new Scanner (System.in);
int variable = 0;
boolean valid = true;
do{
try{
if (variable >= 0 && valid){
}
else if(valid){
System.out.print("Please enter positive values only: ");
}
valid = true;
}
catch (InputMismatchException e){
System.out.print("Please enter numerical values only: ");
sc = new Scanner(System.in);
valid = false;
}
}while (!valid || variable < 0);
return variable;
}
Well first of all, you're code is insanely hard to understand. (or could just be me I guess)
But if you look at your code
Scanner sc = new Scanner (System.in);
int variable = 0;
boolean valid = true;
You are creating the Scanner object, but nowhere in the method are you actually using it.
The next few lines,
if (variable >= 0 && valid){
}
both of those conditions are met. So with nothing in the brackets, no code is executed. So from there, it just returns the value of the variable, which is 0.
So you need to actually use your Scanner class to grab an integer. Which I believe, though I'm not sure, the method for that is
Scanner.nextInt();
Edit: From the JavaDocs http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
You can simply use
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
to read an integer from the Scanner.
Your variable variable is assigned 0 and the valid variable is assigned true. Consequently, the while (!valid || variable < 0) expression will always be evaluated to false and the do-while loop will only be executed once (without the Scanner ever being created).
I guess that you would like to read the user input before checking the variable variable, so you would probably like create the Scanner and read the input before doing the if (variable >= 0 && valid) check.
Side note, you can probably skip the valid variable and use variable =sc.nextInt();, compare with #Austin's answer.
Related
I'm trying to make it for that the program will continue to request input of a 5 digit number until the user gives a 5 digit number. When I run the following:
//import scanner to read keyboard input
import java.util.Scanner;
class NumberInverter {
public static void main(String[] args) {
//create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
//display message propmt and input for number
//conditional statement loop to check if the length is any number other than 5
do {
System.out.print("Enter any 5 digit whole number you wish to invert!");
int num = keyboard.nextInt();
int numSize = String.valueOf(num).length();
} while(!isValid(numSize));
}
private static boolean isValid(int numSize){
if(numSize != 5){
System.out.println("Oops! Looks like you gave a number that isn't exactly a 5 digit whole number. Try again!");
return false;
} else return true;
}
}
I get the following error:
NumberInverter.java:20: error: cannot find symbol
} while(!isValid(numSize)); ^
symbol: variable numSize
location: class NumberInverter
1 error
I've tried a bunch of different things, can anyone fluent in java help me out I'm very new?
Thanks ahead of time!
The variable numSize is not in the same scope as the while condition check.
In Java, any variable declared inside a block (a region surrounded by {}) cannot be accessed outside of that block. In this case, since you are declaring numSize right inside the loop, the loop's condition (which is outside that block) cannot access it. Each block creates something called a "block scope", and variables created in there cannot be accessed outside it.
The fix for this is very simple: Declare the variable in the same scope as the while loop. This can be done by putting it right above the do. Notice that you only need to int numSize;, outside, once. You don't put int when you are assigning to it inside the loop, you just do numSize = .... since you are assigning to a previously-declared variable.
You can still assign to the variable from inside the loop, but since it was originally declared outside the loop, stuff outside the loop can access it.
int numSize;
do {
System.out.print("Enter any 5 digit whole number you wish to invert!");
int num = keyboard.nextInt();
numSize = String.valueOf(num).length();
} while(!isValid(numSize));
Some more information about scopes can be found at What is 'scope' in Java?.
Num size is declared inside the loop scope, you're trying to access it outside that scope. For this to work, declare numSize just before the do statement and assign it within the loop. This way, the variable is visible in the whole statement and also inside the loop (for assignment).
int numSize;
do {
// The rest of your code, all variables declared here are
// gone outside the brackets, however you can access the ones
// in outer scopes.
numSize = String.valueOf(num).length();
} while(!isValid(numSize));
See this for more information about different types of scope: https://www.geeksforgeeks.org/variable-scope-in-java/
Create a local variable numSize.
For exemple :
//import scanner to read keyboard input
import java.util.Scanner;
class NumberInverter {
public static void main(String[] args) {
//create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
int numSize;
// int numSize;
//display message propmt and input for number
//conditional statement loop to check if the length is any number other than 5
do {
System.out.print("Enter any 5 digit whole number you wish to invert!");
int num = keyboard.nextInt();
numSize = String.valueOf(num).length();
} while(!isValid(numSize));
}
private static boolean isValid(int numSize){
if(numSize != 5){
System.out.println("Oops! Looks like you gave a number that isn't exactly a 5 digit whole number. Try again!");
return false;
} else return true;
}
}
I'm wondering how the program with "java scanner" can be finished
especially when I use this with System.in and scanner.hasNext()
Scanner sc = new Scanner(System.in);
For example, when I run the code below on some IDE
public static void main(String[] args){
Scanner sc = new Scanner(System.in)
int[] arr = new int[3];
int i = 0;
// put all the number from scanner to the array.
while(sc.hasNext()){
arr[i++] = sc.nextInt();
}
System.out.println(Arrays.toString(arr));
and input some numbers(for the inputs for scanner) in the console,
it doesn't stop receiving the numbers.
I wanted to use sc.hasNext() for the purpose of after finishing getting some input for the user, putting all the numbers received, as I commented on the code.
How can I finish the scanner getting the input on console?
Your code will run while stdin (System.in in Java) is open. You could close it programmatically if you want but it's usually done by pressing Ctrl+d
in the terminal that program is running (Shortcut is for Linux/macOS in Windows console it's Ctrl+z I think).
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
However, to put the input from the user in your array, can be done by replacing your while condition with this:
while (sc.hasNext() && i!=arr.length) {
arr[i++] = sc.nextInt();
}
Since your store the user's input inside a fixed size (4) structure, you can use a for loop,
after all this is the case to use it:
when the number of repetitions is predefined
for (int i = 0; i < arr.length; i++){
arr[i] = sc.nextInt();
}
You don't need to put the condition for hasNext as it will always return true after entering an input.
You should have a condition on array length.
try this
int[] arr = new int[3];
int i = 0;
while(i<arr.length)
arr[i++] = sc.nextInt();
System.out.println(Arrays.toString(arr));
just add a condition in while as you limit your array to a specific length so when it reach this length t can't take any more input and it will just close the loop and print your array
like this:
Scanner sc = new Scanner(System.in);
int[] arr = new int[3];
int i = 0;
// put all the number from scanner to the array.
while(sc.hasNext() && i < arr.length){
arr[i++] = sc.nextInt();
}
System.out.println(Arrays.toString(arr));
You can change your while loop and put a conditional break when your number of integers reach array length. Try this,
while (sc.hasNext()) {
arr[i++] = sc.nextInt();
if (i == arr.length) {
break;
}
}
Or you can write it as a simple for loop,
// int i = 0;
for (int i = 0; i<arr.length;i++) {
arr[i] = sc.nextInt();
}
Here it will be useful for you to understand how sc.nextInt() works.
Whenever sc.nextInt() gets executed, the scanner objects sc looks for an integer and returns the next integer it finds in the stream scanned by sc object. If it doesn't find an integer in the stream, it will throw some Exception.
Now coming to your code, when your while loop gets executed, every time the code gets inside while loop, it calls sc.nextInt() and one integer is read and assigned into the array but as you have declared your array size as 3 only you need to break the loop else it will try to access an index greater than 3 in your array and will result into ArrayIndexOutOfBounds exception which you will not want. Due to which I have put that condition in while loop and it breaks as soon as the index reaches 3. Similar thing is achieved in the for loop. Hope my explanation helps. Let me know if you have any queries further.
Another thing you could have done is, change sc.hasNext() to sc.hasNextInt() in your while loop as hasNext() captures any data (integer or non-integer) from the stream and returns true and you would not want it to return true if the next incoming data is not an integer else that will run into exception.
Once you change sc.hasNext() to sc.hasNextInt() in while loop condition, your program will automatically end once you provide 3 integers as input to your program but if user tried to enter more than 3 integers, it will run into ArrayIndexOutOfBounds exception as your array length is limited to 3 only. Hence you need that condition if (i==arr.length) { break; } So your while loop can also be like this,
while (sc.hasNextInt()) {
arr[i++] = sc.nextInt();
if (i == arr.length) {
break;
}
}
My objective is to make sure the user inputs an int. Else, exit the program. Then I do some coding that requires that int.
Code Snippet :
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
//check if user enters an int
int userinput = input.nextInt();
// assign that int input to variable userinput
// over 100+ lines of code using nextInt var "userinput"
} else {
System.exit(1);
// user did not enter an int
}
Is there a better way to check for whether a user has entered an int and then use that int that doesn't require my entire program to be coded into that if-statement (because nextInt's scope is limited to that if-statement)?
It feels messy to me to put everything into one if-statement.
I wouldn't be allowed to use separate objects/classes since it's early in the semester for my class. This all goes in the main method, and I'm just using simple if-statements/scanner inputs.
Thanks
Definitely! Just negate the if statement and early exit:
Scanner input = new Scanner(System.in);
if (!input.hasNextInt()) {
System.exit(1);
}
// "else"
doMagicalThings(input.nextInt());
Oh, I guess also to note: replace the 100 lines of code with a method call and break it up a bit. That'd be good to do in addition to the above.
Here is a simple example of using hasNextInt () to validate a positive integer input
Scanner input = new Scanner(System.in);
int number;
do {
System.out.println("Input Number ");
while (!input.hasNextInt()) {
System.out.println(" not a number!");
input.next();
}
number = input.nextInt();
} while (number <= 0);
System.out.println("Númber válid " + number);
I have been using the following code in c and c++ for looping till user feeds the correct value till the program comes out of it:
while((scanf("%d",&num)==1)//same way in for loop
{
//some code
}
Can i some how use the same way to accept and loop the program till i keep entering let's say an integer and floating or a char or a special character breaks it.
Use :
Scanner sc = new Scanner(System.in); // OR replace System.in with file to read
while(sc.hasNext()){
//code here
int x = sc.nextInt();
//...
}
There are different variants of hasNext() for specific expected input types: hasNextFloat(), hasNextInt()..
Same goes for next() method so you can find nextInt(), nextFloat() or even nextLine()
You can go to Java doc for more info.
As proposed in comments, you can use the Scanner class.
Note you need to read the in buffer with a nextLine() when it is not an int.
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Enter an int: ");
while (!in.hasNextInt()) {
System.out.println("That's not an int! try again...");
in.nextLine();
}
int myInt = in.nextInt();
System.out.println("You entered "+myInt);
}
}
Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}