I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
You can do this by using Scanner class :
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
int j = scan.nextInt();
System.out.println("i = "+i +" j = "+j);
nextInt() : -Scans the next token of the input as an int and returns the int scanned from the input.
For more.
or to get user input you can also use the Console class : provides methods to access the character-based console device, if any, associated with the current Java virtual machine.
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
or you can also use BufferedReader and InputStreamReader classes and
DataInputStream class to get user input .
Use the Scanner class to get the values from the user. For integers you should use int, for decimal numbers (also called real numbers) use double and for strings use Strings.
A little example:
Scanner scan = new Scanner(System.in);
int intValue;
double decimalValue;
String textValue;
System.out.println("Please enter an integer value");
intValue = scan.nextInt(); // see how I use nextInt() for integers
System.out.println("Please enter a real number");
decimalValue = scan.nextDouble(); // nextDouble() for real numbers
System.out.println("Please enter a string value");
textValue = scan.next(); // next() for string variables
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
If you still don't understand something, please look further into the Scanner class via google.
As you will likely continue to run into problems like this in your class and in your programming career:
Lessons on fishing.
Learn to explore the provided tutorials through oracle.
Learn to read the Java API documentation
Now to the fish.
You can use the Scanner class. Example provided in the documentation.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Related
I'm doing a project for a Uni course where I need to read an input of an int followed by a '+' in the form of (for example) "2+".
However when using nextInt() it throws an InputMismatchException
What are the workarounds for this as I only want to store the int, but the "user", inputs an int followed by the char '+'?
I've already tried a lot of stuff including parseInt and valueOf but none seemed to work.
Should I just do it manually and analyze char by char?
Thanks in advance for your help.
Edit: just to clear it up. All the user will input is and Int followed by a + after. The theme of the project is to do something in the theme of a Netflix program. This parameter will be used as the age rating for a movie. However, I don't want to store the entire string in the movie as it would make things harder to check if a user is eligible or not to watch a certain movie.
UPDATE: Managed to make the substring into parseInt to work
String x = in.nextLine();
x = x.substring(0, x.length()-1);
int i = Integer.parseInt(x);
Thanks for your help :)
Try out Scanner#useDelimiter():
try(Scanner sc=new Scanner(System.in)){
sc.useDelimiter("\\D"); /* use non-digit as separator */
while(sc.hasNextInt()){
System.out.println(sc.nextInt());
}
}
Input: 2+33-599
Output:
2
33
599
OR with your current code x = x.substring(0, x.length()-1); to make it more precise try instead: x = x.replaceAll("\\D","");
Yes you should manually do it. The methods that are there will throw a parse exception. Also do you want to remove all non digit characters or just plus signs? For example if someone inputs "2 plus 5 equals 7" do you want to get 257 or throw an error? You should define strict rules.
You can do something like: Integer.parseInt(stringValue.replaceAll("[^\d]","")); to remove all characters that are no digits.
Hard way is the only way!
from my Git repo line 290.
Also useful Javadoc RegEx
It takes in an input String and extracts all numbers from it then you tokenize the string with .replaceAll() and read the tokens.
int inputLimit = 1;
Scanner scan = new Scanner(System.in);
try{
userInput = scan.nextLine();
tokens = userInput.replaceAll("[^0-9]", "");
//get integers from String input
if(!tokens.equals("")){
for(int i = 0; i < tokens.length() && i < inputLimit; ++i){
String token = "" + tokens.charAt(i);
int index = Integer.parseInt(token);
if(0 == index){
return;
}
cardIndexes.add(index);
}
}else{
System.out.println("Please enter integers 0 to 9.");
System.out.print(">");
}
Possible solutions already have been given, Here is one more.
Scanner sc = new Scanner(System.in);
String numberWithPlusSign = sc.next();
String onlyNumber = numberWithPlusSign.substring(0, numberWithPlusSign.indexOf('+'));
int number = Integer.parseInt(onlyNumber);
Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!
I am suppose to write a program that accepts an integer from the user using the Scanner class and displays the char data type representation of it. Assume the user will only enter a number from 0 to 127. As of now I have this.
import java.util.Scanner;
public class ASCIICharacterMcAfooseMark {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//This should allow the user to enter a number
System.out.print("Enter a number:");
String str = input.nextLine();
System.out.println(input);
//Need to get this to allow the entered number to show char value
int num = 0 - 127;
char c;
c = (char)num;
System.out.println(c);
}
}
When I enter this into command prompt it lets me enter a number, but all I get is a bunch of words and then a question mark. Any help would be appreciated. I am using Notepadd++ in Java.
Edit: For 32, the char representation would be space.
Edit: For the System.out.println(input); I was going by what I saw in my teacher's powerpoint. Should I get rid of it?
What do you mean by "char data type representation"? Given an input of
32 (for example), what would be the correct "char data representation"
to display in this case?
When I enter this into command prompt it lets me enter a number, but
all I get is a bunch of words and then a question mark.
Not all ints map to plain text chars. Some of them map to spaces, some to backspaces, some to "print line feeds", some to "modem control characters". For starters, look to positions 0-127 in the ACII table; however, Java really uses Unicode, so look to Unicode if you want to know how things happen above 127 (which includes your negative numbers).
Also, keep in mind that if you do not have a fully populated "glyph set" (the part of the font that draws to the screen, then various "code points" (the numbers that correspond to the glyphs) can't be drawn. Typically this is resolved by many systems with a substitution glyph, which is that funky question mark you're seeing.
Change your line:
int num = 0 - 127;//your num will always hold -127
To
int num = Integer.parseInt(str);//so you get integer representation of number string you just entered.
Notes apart:
Perhaps here System.out.println(input); you are trying to print string user entered, so you might need to change it to System.out.println(str);
There is an api which is specifically to read int from scanner and may be worth looking at here
Let's have a look at what your program is doing.
Scanner input = new Scanner(System.in);
Note that input is a Scanner object.
System.out.println(input);
Here you are displaying the Scanner object itself. Not what the user entered, because that is in the variable str. Maybe you wanted to do this instead:
System.out.println(str);
Then this line:
int num = 0 - 127;
This just sets num to -127. What you wanted to do instead is parse whatever is in str into an int:
int num = Integer.parseInt(str);
if you're assuming the user will put a number from 0 to 127, then try it like this:
import java.util.Scanner;
public class ASCIICharacterMcAfooseMark {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number:");
String str = input.nextLine();
System.out.println(input);
int num = Integer.parseInt(str); //you weren't using the value from the input
char c;
c = (char)num;
System.out.println(c);
}
}
char c;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number:");
int ip = input.nextInt();//<---- get integer
c = (char)ip;// cast int value to char
System.out.println(c);
if input is 97 output will be a
I have a file with contents
v1 0 2 v2 0 3 v3 1 2 v4 1 2 v5 1 3
I need to be able to get the information and store this in three different variables (a String and 2 ints). I am having trouble getting my head around the pattern I would use with the useDelimiter function.
Also is there a way that I don't have to first split it into separate strings, then parseInt from that string? So I have a class called Task which has a String and two Ints. I need to be able to go through the file and create multiple tasks e.g. Task(v1,0,2), Task(v2,0,3).
Thanks.
I think you're over-thinking things -- you don't need to use useDelimiter since Java's Scanner object automatically will split via whitespace.
Scanner scan = new Scanner(new File("myFile"));
ArrayList<Task> output = new ArrayList<Task>();
while (scan.hasNext()) {
String s = scan.next();
int num1 = scan.nextInt();
int num2 = scan.nextInt();
output.add(new Task(s, num1, num2));
}
Note that the above code will fail if the input does not exactly match the pattern of string-int-int -- the nextInt method in a Scanner will fail if the next token cannot be interpreted as an int, and the code will throw an exception if the number of tokens in the input is not a multiple of three.
Default delimiter is ok
while(sc.hasNext()) {
String s = sc.next();
int i1 = sc.nextInt();
int i2 = sc.nextInt();
...
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm taking user input from System.in using a java.util.Scanner. I need to validate the input for things like:
It must be a non-negative number
It must be an alphabetical letter
... etc
What's the best way to do this?
Overview of Scanner.hasNextXXX methods
java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:
hasNext() - does it have any token at all?
hasNextLine() - does it have another line of input?
For Java primitives
hasNextInt() - does it have a token that can be parsed into an int?
Also available are hasNextDouble(), hasNextFloat(), hasNextByte(), hasNextShort(), hasNextLong(), and hasNextBoolean()
As bonus, there's also hasNextBigInteger() and hasNextBigDecimal()
The integral types also has overloads to specify radix (for e.g. hexadecimal)
Regular expression-based
hasNext(String pattern)
hasNext(Pattern pattern) is the Pattern.compile overload
Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.
The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.
Example 1: Validating positive ints
Here's a simple example of using hasNextInt() to validate positive int from the input.
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
Here's an example session:
Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5
Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.
Related questions
How to use Scanner to accept only valid int as input
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Example 2: Multiple hasNextXXX on the same token
Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!
This has two consequences:
If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!
Here's an example of performing multiple hasNextXXX tests.
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
System.out.println(
sc.hasNextInt() ? "(int) " + sc.nextInt() :
sc.hasNextLong() ? "(long) " + sc.nextLong() :
sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
"(String) " + sc.next()
);
}
Here's an example session:
5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit
Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.
Example 3 : Validating vowels
Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);
Here's an example session:
Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e
In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.
API links
hasNext(String pattern) - Returns true if the next token matches the pattern constructed from the specified string.
java.util.regex.Pattern
Related questions
Reading a single char in Java
References
Java Tutorials/Essential Classes/Regular Expressions
regular-expressions.info/Character Classes
Example 4: Using two Scanner at once
Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:
Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
Scanner lineSc = new Scanner(sc.nextLine());
int sum = 0;
while (lineSc.hasNextInt()) {
sum += lineSc.nextInt();
}
System.out.println("Sum is " + sum);
}
Here's an example session:
Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit
In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.
Summary
Scanner provides a rich set of features, such as hasNextXXX methods for validation.
Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
Always remember that hasNextXXX does not advance the Scanner past any input.
Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.
Here's a minimalist way to do it.
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
For checking Strings for letters you can use regular expressions for example:
someString.matches("[A-F]");
For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want.
Here
public int readInt(String prompt, int min, int max)
{
Scanner scan = new Scanner(System.in);
int number = 0;
//Run once and loop until the input is within the specified range.
do
{
//Print users message.
System.out.printf("\n%s > ", prompt);
//Prevent string input crashing the program.
while (!scan.hasNextInt())
{
System.out.printf("Input doesn't match specifications. Try again.");
System.out.printf("\n%s > ", prompt);
scan.next();
}
//Set the number.
number = scan.nextInt();
//If the number is outside range print an error message.
if (number < min || number > max)
System.out.printf("Input doesn't match specifications. Try again.");
} while (number < min || number > max);
return number;
}
One idea:
try {
int i = Integer.parseInt(myString);
if (i < 0) {
// Error, negative input
}
} catch (NumberFormatException e) {
// Error, not a number.
}
There is also, in commons-lang library the CharUtils class that provides the methods isAsciiNumeric() to check that a character is a number, and isAsciiAlpha() to check that the character is a letter...
If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here:
http://java.sun.com/developer/technicalArticles/releases/1.4regex/
Otherwise, to parse an int from a string, try
Integer.parseInt(string). If the string is not a number, you will get an exception. Otherise you can then perform your checks on that value to make sure it is not negative.
String input;
int number;
try
{
number = Integer.parseInt(input);
if(number > 0)
{
System.out.println("You positive number is " + number);
}
} catch (NumberFormatException ex)
{
System.out.println("That is not a positive number!");
}
To get a character-only string, you would probably be better of looping over each character checking for digits, using for instance Character.isLetter(char).
String input
for(int i = 0; i<input.length(); i++)
{
if(!Character.isLetter(input.charAt(i)))
{
System.out.println("This string does not contain only letters!");
break;
}
}
Good luck!
what i have tried is that first i took the integer input and checked that whether its is negative or not if its negative then again take the input
Scanner s=new Scanner(System.in);
int a=s.nextInt();
while(a<0)
{
System.out.println("please provide non negative integer input ");
a=s.nextInt();
}
System.out.println("the non negative integer input is "+a);
Here, you need to take the character input first and check whether user gave character or not if not than again take the character input
char ch = s.findInLine(".").charAt(0);
while(!Charcter.isLetter(ch))
{
System.out.println("please provide a character input ");
ch=s.findInLine(".").charAt(0);
}
System.out.println("the character input is "+ch);