So i am trying to implement a very simple program.
i want to set bobi to a variable but without using strings. I am thinking I can do it using just char.
this is what i have so far
System.out.println("Please Enter a four letter name");
char n =
char a =
char m =
char e =
System.out.print("His name is ");
System.out.print(n);
System.out.print(a);
System.out.print(m);
System.out.print(e);
with the program i have it is
your program: Enter four letter name:
user: b
user: o
user: b
user: i
I want to be able to enter in one input
so its like this
program: Enter four letter name:
user: bobi
or is there a better way to approach
The System.in stream is the key here. You need to read each byte coming in and run it through an explicit cast to a char.
char n = (char)System.in.read();
char a = (char)System.in.read();
// And so on.
Reading Material so you understand this
Using the System.in functionality in Java. Click here.
A lesson in Explicit Casts. Click here.
It's certainly possible to read raw data from System.in:
char[] name = new char[4];
try {
char c;
int i = 0;
while((c = (char)System.in.read()) != '\n') {
if(i < name.length)
name[i++] = c;
}
} catch(IOException ioe) {}
There's a couple of notes:
System.in is terminated by a new line character (from user pressing 'enter') unlike other streams which are null or -1 terminated.
System.in should be compatible with UTF-8. It's probably the same as the system property file.encoding. I can't find an official source that says so but in any case you can just cast it to a char. This question seems to suggest compatibility would be a problem for other readers as well.
Note that this may not be simpler. Compare with using Scanner:
String line = new Scanner(System.in).nextLine();
if(line.length() > 4)
line = line.substring(0, 4);
And for both cases, you cannot control what the user enters except after they've entered it. You ask for a 4-character name but they can enter "Joe Brown" and they can enter nothing.
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);
in my intro to programming class. I am supposed to make a program that asks the user to enter his/her name and then use a while loop to print the name in the following manner:
(user entered Caroline)
C
a
r
o
l
i
n
e
Caroline, there are 8 letters in your first name.
--I've tried a bunch of things but still can't figure it out.--This is what I have so far
Assuming you are correctly getting the user entered string from the STDIN.
You may look to do something like this in your language of choice:
Find the length of your string
Use the while loop, with the condition relating to the length of your string, to move through the string character by character
Print out to a newline each individual character in your string
Feel free to ask questions and I would be happy to elaborate. Adding some examples of your code so far and the problems your facing would be useful.
In C++, this would be:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i=0;
string s;
cin>>s;
while(i<s.length())
{ cout<<i+1<<"."<<cout<<s[i]<<endl;
i++;
}
cout<<s<<", "<<"There are "<<s.length()<<" letters in your first name.";
return 0;
}
This is also very similar in Java, you should be able to derive it looking at this if you expected it in a programming language of your choice.
inside your main method try this:
//Asks user name.
System.out.println("What's your name?");
//Instantiates scanner
Scanner sc = new Scanner(System.in);
//With the scanner it reads user input and save it in the variable name
String name = sc.nextLine();
//It is a good programming practice to close the scanner
sc.close();
/*The loop that for each letter of the name also prints the position
number plus 1*/
int i = 0;
while (i < name.length()) {
System.out.println(i+1 + ". " + name.charAt(i));
i++;
}
As per snap shot shared by OP:
Here, you need to modify this lines:
System.out.println(name.charAt(i));
to
System.out.printf("%d. %c%n",(1+i),name.charAt(i));
Also, change this line:
i++;
}}}
to
i++;
}
System.out.printf("%s, there are %d letters in your first name%n",name,i));
}}
I am just polishing my java skills and I wrote out this code to play around with keyboard input and do while loops.
package Chapter3;
import java.io.IOException;
public class convertCase {
public static void main(String args[]) throws IOException {
char ch = 'a';
do {
System.out.println("please type in a value: ");
ch = (char) System.in.read();
if((int) ch < 96) {
ch += 32;
int newCh = (int) ch;
System.out.println("The lowercase version is: " + (char)newCh);
}
else if((int) ch >96) {
System.out.println("You have typed in" + ch);
ch -= 32;
int newCh = (int) ch;
System.out.println("the uppercase version is: " + (char)newCh);
}
} while(ch!='.');
}
}
Problem is that when I test it the 'while loop' runs twice before asking for input instead of just the once:
please type in a value:
a
You have typed ina
the uppercase version is: A
please type in a value:
The lowercase version is: *
please type in a value:
L
The lowercase version is: l
please type in a value:
The lowercase version is: *
please type in a value:
Can someone bring clarity to this situation??
That's because
System.in.read();
takes in every key pressed. that is, in your case, the 'a' key, and the 'return' key.
If you want your functionality then use the following:
Scanner scanner = new Scanner(System.in);
And then use:
String line =(char)scanner.nextLine();
and then parse the value.
It is looping twice because it is processing the newline that follows each character.
You are processing the newline character as if it is legitimate input. You should either read the entire line (including the newline, perhaps using a Scanner) and then process the first character of the line or simply add a test to skip newlines in your loop logic.
P.S. Converting case by adding or subtracting 32 is a really awful approach. It won't work with anything but a-z and A-Z (in the English alphabet). It won't work for most characters outside the Basic Latin block and shouldn't be used at all for characters that have no alternate case (such as newline). You should be using Character.toUpperCase() and Character.toLowerCase() instead.
Answer taken from Book "Java: A Beginner's Guide"
The answers mentioned above are right as well. Just for more clarification, I will post this.
do {
System.out.print("Pres a key followed by Enter: ");
//get a char
ch = (char) System.in.read();
//REFERRING TO THIS PART
do{
ignoreNewLineENTER = (char) System.in.read();
}
while (ignoreNewLineENTER != '\n');
} while (ch != 'q');
console input is line buffered—you have to press ENTER before characters are sent. Pressing ENTER causes a carriage return and a line feed (newline) sequence to be generated. These characters are left pending in the input buffer. Also, if you typed more than one key before pressing ENTER, they too would still be in the input buffer. This loop discards those characters by continuing to read input until the end of the line is reached. If they were not discarded, then those characters would also be sent to the program as guesses, which is not what is wanted. (To see the effect of this, you might try removing the inner do-while loop.) In Chapter 10, after you have learned more about Java, some other, higher-level ways of handling console input are described. However, the use of read( ) here gives you insight into how the foundation of Java's I/O system operates. It also shows another example of Java's loops in action.
I will admit, this is a school assignment... But I simply cannot figure out what I am doing wrong.
I have a hash table with an insert function. The following code is supposed to take a line of data from System.in in the format "Long String" (i.e. "32452 John"). The first token must be a Long for the ID number, and it must be followed by a String token for the name. When I run the program and I get to the portion where this must be executed (It is in a switch statement), I entered 'a' and hit enter. The command line immediately reads "Invalid value." (note: not VALUES, as that would mean it hit the nested if statement. It won't let me type in any data. Thank you in advance!
System.out.println("Enter ID and Name.");
//temp to take in the next line entered by the user
//inScan is the Scanner for System.in
temp = inScan.nextLine();
//Create Scanner for the line
Scanner tempScan = new Scanner(temp);
if(tempScan.hasNextLong()){
thisID = tempScan.nextLong();
if((tempScan.hasNext()) && (thisID>0)){
thisName = tempScan.next();
//The data will only be inserted if both segments of data are entered
myTable.insert(new Student(thisID, thisName));
}else{
System.out.println("Invalid values.");
}
}else{
System.out.println("Invalid value.");
}
Why do you need the second Scanner?
Example
String input = scanner.nextLine();
String[] tokens = input.split(" ");
Long id = Long.parseLong(tokens[0]);
String name = tokens[1];
And if you wanted to add your validation:
String input = scanner.nextLine();
if(input.contains(" ")) {
// You know there's a space in it.
String[] tokens = input.split(" ");
if(tokens.length == 2) {
// You know it's a value, followed by a space, followed by a value.
if(tokens[0].matches("[0-9]+")) {
// You know it only contains numbers.
Long id = Long.parseLong(tokens[0]);
}
}
}
I've not run it, but i guess your problem is that when you enter the text 'a' and hit enter, this line is false:
if(tempScan.hasNextLong()){
as you haven't entered a number. hence why it drops to the next block. If you enter something numerical first, i suspect your code with work. you probably need to add a 'while' loop around it, to run until it gets a number.
You already have a Scanner which reads from System.in, there's no need for another one. The second one you've made is a scanner for a String, which will never have a nextLong as it has nothing to scan after your String.
I won't write any code for you as this is homework, but stick to your original scanner when checking for user input instead.
I've been trying different methods for converting a user string input into an int I could compare and build an "if-then" statement. Every time I tried testing it, it just threw exception. Can anyone look at my Java code and help me find the way? I'm clueless about it (also a noob in programming). If I'm breaking any rules please let me know I'm new here. Thank you.
Anyway, here is the code:
System.out.println("Sorry couldn't find your user profile " + userName + ".");
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try {
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
Character i = new Character(addNewUser.charAt(0));
String s = i.toString();
int answerInDecimal = Integer.parseInt(s);
System.out.println(answerInDecimal);
}
catch(Exception e) {
System.out.println("You've mistyped the answer.");
e.getMessage();
}
It seems like you are trying to convert the string (which should be a single character, Y or N) into its character value, and then retrieve the numerical representation of the character.
If you want to turn Y or N into their decimal representation, you have to perform a cast to int:
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.charAt(0);
int integerChar = (int) i; //The important part
System.out.println(integerChar);
This will return the integer representation of the character that the user input. It may also be useful to call the String.toUpperCase() method in order to ensure that different inputs of Y/N or y/n do not give different values.
However, you could also do an if-else based upon the character itself, rather than converting it to an integer.
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.toUpperCase().charAt(0);
if (i == 'Y') {
//Handle yes
} else if (i == 'N') {
//Handle no
} else {
System.out.println("You've mistyped the answer.");
}
I think you meant to ask them to Enter 0 for yes and 1 for No ? Maybe?
You're asking the user to type Y or N and then you're trying to parse that to an integer. That will always throw an exception.
EDIT -- As others have pointed out, if you want to continue to use Y or N, you should do something along the lines of
String addNewUser = answer.readLine();
if ( addNewUser.toLowerCase().startsWith("y") ) {
// Create new profile
}
parseInt is just for converting text numbers into integers: everything else gets a NumberFormatException.
If you want the decimal ASCII value of a character, just cast it to an int.
Use if (addNewUser.startsWith("Y") || addNewUser.startsWith("y")) { instead.
Or (as Mark pointed) if (addNewUser.toLowerCase().startsWith("y")) {.
BTW maybe look at Apache Commons CLI?
You cannot convert String to int, unless you know the String contains a valid integer.
Firstly, using the Scanner class for input is better, since its faster
and you don't need to get into the hassle of using streams, if you're
a beginner. This is how Scanner will be used to take input:
import java.util.Scanner; // this is where the Scanner class resides
...
Scanner sc = new Scanner(System.in); // "System.in" is the stream, you could also pass a String, or a File object to take input from
System.out.println("Would you like to ... Enter 'Y' or 'N':");
String input = sc.next();
input = input.toUpperCase();
char choice = sc.charAt(0);
if(choice == 'Y')
{ } // do something
else if(choice == 'N')
{ } // do something
else
System.err.println("Wrong choice!");
This code could also be shortened to one line (however you won't be
able to check a third "wrong choice" condition):
if ( new Scanner(System.in).next().toUpperCase().charAt(0) == 'Y')
{ } // do something
else // for 'N'
{ } // do something
Secondly, char to int conversion just requires an explicit type
cast:
char ch = 'A';
int i = (int)ch; // explicit type casting, 'i' is now 65 (ascii code of 'A')
Thirdly, even if you take input from a buffered input stream, you
will take input in a String. So extracting the first character from
the string and checking it, simply requires a call to the charAt()
function with 0 as a parameter. It returns a character, which can
then be compared to a single character in single quotes like this:
String s = in.readLine();
if(s.charAt(0) == 'Y') { } // do something
Fourthly, its a very bad idea to put the whole program in a try
block and catch Exception at the end. An IOException can be
thrown by the readline() function, and parseInt() could throw a
NumberFormatException, so you won't be able to handle the 2
exceptions separately. In this question, the code is small enough for
this to be ignored, but in practice, there will be many functions
that can throw exceptions, hence it becomes easy to lose track of exactly which function threw what exception and proper exception handling becomes quite difficult.