This question already has answers here:
What is the use of System.in.read()?
(10 answers)
Closed 4 years ago.
I am really new to Java, and I was following a book tutorial on how to read user input. Their code was...
class Example {
public static void main(String args[]) throws java.io.IOException {
// System.out.println()
char ch;
System.out.print("Press a key followed by ENTER: ");
ch = (char) System.in.read();
System.out.println("Your key is: " + ch);
}
}
I tried to experiment and read user input as an integer like this...
class Example {
public static void main(String args[]) throws java.io.IOException {
int foo;
System.out.print("Enter a number: ");
foo = (int) System.in.read();
System.out.print("Your number was: " + foo);
}
}
However, upon typing for example number 12, I get the output as 49. Why is that? How come the book tutorial worked then?
EDIT: When I type in 'w' in my program, it still prints out 119. Surely I thought the throws thing was dealing with that? Or is it not?
And what is a Scanner (just saw it in the comments)?
System.in.read() Reads the next byte of data from the input stream.
So you are just reading 1 from input and you are printing ASCII code of 1 which is 49. If you want to show the character you should read it as char or convert it:
System.out.print("Your number was: " + (char) foo)
Answering Your Question
However, upon typing for example number 12, I get the output as 49.Why
is that?
The reason you got 49, is because you only read the first char of the input (the program only read the '1' digit). The ASCII value of 1, surprisingly equals to 49.
Better Approach
I would suggest to use the Scanner object to read inputs from System.in, like this.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
This approach will populate the 'sentence' String, with the entire line entered in the console.
If you need a number and not a String, parse that string to an int using Integer.valueOf(yourString);
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm doing the Java MOOC by Helsinki University. Stuck on the following problem:
Write a program which prints the integers from 1 to a number given by the user.
Sample output
Where to? 3
1
2
3
The code below outputs the expected results but is not accepted as valid. Any suggestions or pointers are welcome, thank you!
import java.util.Scanner;
public class FromWhereToWhere {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = Integer.valueOf(scanner.nextLine());
int start = 1;
while (start <= userInput) {
System.out.println(start);
start++;
}
}
}
Most likely the system that tests your program is stuffing values into standard input (System.in) with spaces, and assumes that you will read with .nextInt().
If that's not it, double check the program description; what is supposed to happen if I enter -1? 0? 1985985410395831490583440958230598? FOOBAR?
If it doesn't say, then presumably the verifier won't throw those inputs at you (if it does, file a bug with the MOOC provider, the course itself needs fixing if that is the case), but if it does, you're going to have to code those rules in, probably.
This shouldn't be it, but to exactly mirror the desired result, it's System.out.print("Where to? "); - note, no ln, and a trailing space.
You did not check if the user input is valid, I would suggest starting off with the following:
check if userInput is a valid number (includes numeric characters).
check if userInput is larger or equal to 1.
your answer is ok but can be optimized to the beginners levels if that is what your teacher is expecting because:
you can get an int directly from scanner, no need to use the wrapper class Integer.
you can use another loop ... a for loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = scanner.nextInt();
System.out.println("ok!");
for (int i = 1; i <= userInput; i++)
{
System.out.println(i);
}
}
Just try by Removing
System.out.println("Where to?");
with
System.out.print("Where to?");
I'm trying to allow the user to put in multiple inputs from the user that contain a char and integers.
Something like this as input: A 26 16 34 9
and output each int added to an array.
I was thinking I could have the first input as a character and then read the rest as a string which then I separate and put into an array.
I'm not new to coding but new to java. I've been doing c++ so the syntax is a bit different.
This is what I have so far, I haven't set up my array yet for the integers.
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
int firstNumber;
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
int n = reader.nextInt();
if (n=='A') {
//if array is full System.out.println("The list is full!");
//else
System.out.println("Integer " + " " + "has been added to the list");
}
else if (n=='Q') {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Could you specify better how should your input be given? From your question, if I understand well, the user simply type "A" followed by a list of numbers separated by a space. So I would simply read the next line, split it in words (separated by a space) and check if the first word is the letter "A". Here it goes:
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
String line = reader.nextLine();
String[] words = line.split(" ");
if (words.length > 0 && words[0].equals("A")) {
//if array is full System.out.println("The list is full!");
// => I don't understand this part
//else
for(int i = 1; i<words.length; i++){
int integer = Integer.parseInt(words[i]);
System.out.println("Integer " + integer + " has been added to the list");
//do your stuff here
}
}
else if (words.length > 0 && words[0].equals("Q")) {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Note that in your solution, you read the next int from your scanner and then try to compare it with the character 'A'. This will not work because A is not an int. If you really want to get the first character from your scanner, you could do:
String line = reader.nextLine();
if(line.length() > 0){
char firstChar = line.charAt(0);
//do your stuff here
}
A character is not an int. You cannot read an int to expect something like 'A'. You can read a String and take its first character though. Scanner doesn't offer a convenient method to read the next String and expect it to be only one-character long. You'd need to handle that yourself.
But considering you don't know in advance how many numbers there will be to read, your solution to read the entire line and interpret it entirely, is the better one. That means you can't use nextInt() nor nextDouble() nor next() nor nextWhateverElse().
You need nextLine(), and it will give you the entire line as a String.
Then you can split() the result, and check if the first is one-char-long. Then you can parse all the others as int.
I don't immediately recall how to write this in Java – it's been a bit of a while – but what I'd do is to first separate the string by spaces, then attempt to do ParseInt on each piece.
If the string isn't a valid integer, this method will throw an exception, which you can catch. So:
If you make it to the next statement, an exception didn't happen, so the value is an integer.
If, instead, you find yourself in the exception-handler (having caught [only ...] the expected kind of exception, the value is a string.
Of course, don't "catch" any exception-type other than the NumberFormatException that you're expecting.
By the way, it is perfectly routine to use exceptions in this way. Let Java's runtime engine be the authority as to whether it's an integer or not.
public class Pack1 {
public static void main(String ar[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the character");
char c=(char)br.read();
System.out.println(c);
System.out.println("enter the integer");
long l=Integer.parseInt(br.readLine());
System.out.println("long l="+l);
System.out.println(c);
}
}
Let's say the user types X and presses Enter on the first question, then types 123 and presses Enter on the second question, that would mean that the input stream contains the following characters:
X <CR> 1 2 3 <CR>
When you call read(), you only read the X. When you then call readLine(), you read the <CR> and get a blank string back.
The 1 2 3 <CR> is still sitting unread in the input stream.
Solution: Call readLine() after reading the X to skip past the rest of the line, or use readLine() to read the X as a String, instead of as a char.
FYI: This is the exact same problem people keep having when using Scanner and mixing calls to nextLine() with calls to other nextXxx() methods, like nextInt().
Change this:
long l=Integer.parseInt(br.readLine());
to :
long l=Long.parseLong(br.readLine(), 10);
This is because you are trying to convert the String to Long and not an Integer type.
I recently ran into some trouble with Java's Scanner. When calling methods such as nextInt(), it doesn't consume the newline after pressing Enter. My solution is:
package scannerfix;
import java.util.Scanner;
public class scannerFix {
static Scanner input = new Scanner(System.in);
public static int takeInt() {
int retVal = input.nextInt();
input.nextLine();
return retVal;
}
public static void main(String[] args) {
int num = scannerFix.takeInt();
String word = input.nextLine();
System.out.println("\n" + num + "\t" + word);
}
}
It works, but here's my question: Is this in any way bad?
"Enter" is not consumed because it equals "\n" (in Windows / Linux etc) which is a standard delimiter. You already skip to the next line with input.nextLine();
So your solution is fine!
For more info on how delimiters work regarding the Scannerclass see: How do I use a delimiter in Java Scanner?
One issue is that it can hide some errors in the input. If you expect there to be an integer on one line, and another on the next, but instead the first line contains "2 a" then you will read it as a 2. For some cases, you might want to reject this input instead and display an error.
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