What does this code want me to do? - java

Print the prompt "Character: " then use the Scanner object to read a string from the keyboard into a temporary variable that you must declare. Next extract the first character of the temporary string into myCharacter.
(Scanner is already initialized)
This is what I have so far but I don't understand what the question is asking.
char myCharacter;
char myCharacter1;
Scanner kbd = new Scanner(System.in);
System.out.println("Character: ");
myCharacter1 = kbd.next().charAt(0);

Your code looks like it's doing what you were asked. The question is asking you to read in a string from user input and get the first character out of the string, which is this part of your code:
myCharacter1 = kbd.next().charAt(0);
As far as I can tell, it only cares about having the temporary string variable only so you can grab the first character out of it and store it in to your myCharacter1 variable. It might just be that it's trying to illustrate the idea that strings are an array of characters? I hope that helps!
-Frank
EDIT:
You had a comment that you weren't reading the string into a temporary string variable. That's an important step from your question. As far as I know, your code should work fine, but if this is a homework problem for a class your professor will likely deduct points for not reading into a String variable first.

// Scanner declaration and initialization.
Scanner scanner = new Scanner(System.in);
// 1. Prompting 'Character: '
System.out.print("Character: ");
// 2. Temporary variable declaration and initialization.
String tempVar = scanner.next();
// 3. Extraction of the first character of the temporary variable into char variable
char myCharacter = tempVar.charAt(0);

Related

Is there a way to accept a single character as an input?

New to programming, so my apologies if this is dumb question.
When utilizing the Scanner class, I fail to see if there is an option for obtaining a single character as input. For example,
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a = input.nextLine();
}
}
The above code allows me to pull the next line into a string, which can then be validated by using a while or if statement using a.length() != 1 and then stored into a character if needed.
But is there a way to pull a single character instead of utilizing a string and then validating? If not, can someone explain why this is not allowed? I think it may be due to classes or objects vs primitive types, but am unsure.
You can use System.in.read() instead of Scanner
char input = (char) System.in.read();
You can also use Scanner, doing something like:
Scanner scanner = new Scanner(System.in);
char input = scanner.next().charAt(0);
For using Stringinstead of char, you can also to convert to String:
Scanner scanner = new Scanner(System.in);
String input = String.valueOf(input.next().charAt(0));
This is less fancy than other ways, but for a newbie, it'll be easier to understand. On the other hand, I think the problem proposed doesn't need amazing performance.
Set the delimiter so every character is a token:
Scanner input = new Scanner(System.in).useDelimiter("(?<=.)");
String c = input.next(); // one char
The regex (?<=.) is a look behind, which has zero width, that matches after every character.

How to add a char into an array?

I have a question based on character arrays. At the moment I have an input variable that takes the first letter of the word.
char input = scanner.nextLine().charAt(0);
What I want to do is for every enter, I want to put it in an array so that I can keep a log of all the letters that have been retrievied. I am assuming this is using char[] but I am having trouble implementing added each input into the array.
char input = scanner.nextLine().charAt(0);
First thing that's unclear is what Object type is scanner?
But for now I'll assume scanner is the Scanner object from Java.util.Scanner
If that's the case scanner.nextLine() actually returns a String.
String has a charAt() method that will allow you to pick out a character anywhere in the string.
However scanner.nextLine() is getting the entire line, not just one word. So really scanner.nextLine().charAt(0) is getting the first character in the line.
scanner.next() will give you the next word in the line.
If the line contained "Hello World"
scanner.next().charAt(0) would return the character 'H'.
the next call of scanner.next().charAt(0) would then return the character 'W'
public static void main(String[] args) {
boolean finished = false;
ArrayList<Character> firstLetters = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (!finished) {
firstLetters.add(scanner.next().charAt(0));
}
}
The above code sample might give you the behavior you're looking for.
Please note that the while loop will run forever until finished becomes true.
Your program will have to decide when to set finished to true.
AND here's a couple of links about Java's Scanner class
tutorials point
Java Docs

Java Scanner get number from string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The string is, for example "r1" and I need the 1 in an int form
Scanner sc = new Scanner("r1");
int result = sc.nextInt(); // should be 1
compiles correctly but has a runtime error, should I be using the delimiter? Im unsure what the delimiter does.
Well, there's a few options. Since you literally want to skip the "r" then read the number, you could use Scanner#skip. For example, to skip all non-digits then read the number:
Scanner sc = new Scanner("r1");
sc.skip("[^0-9]*");
int n = sc.nextInt();
That will also work if there are no leading non-digits.
Another option is to use non-digits as delimiters, as you mentioned. For example:
Scanner sc = new Scanner("x1 r2kk3 4 x56y 7g");
sc.useDelimiter("[^0-9]+"); // note we use + not *
while (sc.hasNextInt())
System.out.println(sc.nextInt());
Outputs the six numbers: 1, 2, 3, 4, 56, 7.
And yet another option, depending on the nature of your input, is to pre-process the string by replacing all non-digits with whitespace ahead of time, then using a scanner in its default configuration, e.g.:
String input = "r1";
input = input.replaceAll("[^0-9]+", " ");
And, of course, you could always just pre-process the string to remove the first character if you know it's in that form, then use the scanner (or just Integer#parseInt):
String input = "r1";
input = input.substring(1);
What you do depends on what's most appropriate for your input. Replace "non-digit" with whatever it is exactly that you want to skip.
By the way I believe a light scolding is in order for this:
Im unsure what the delimiter does.
The documentation for Scanner explains this quite clearly in the intro text, and even shows an example.
Additionally, the definition of the word "delimiter" itself is readily available.
There are some fundamental mistakes here.
First, you say:
One = sc.nextInt("r1");
compiles correctly ...
No it doesn't. If sc is really a java.util.Scanner, then there is no Scanner.nextInt(String) method, so that cannot compile.
The second problem is that the hasNextXXX and nextXXX methods do not parse their arguments. They parse the characters in the scanner's input source.
The third problem is that Scanner doesn't provide a single method that does what you are (apparently) trying to do.
If you have a String s that contains the value "r1", then you don't need a Scanner at all. What you need to do us something like this:
String s = ...
int i = Integer.parseInt(s.substring(1));
or maybe something this:
Matcher m = Pattern.compile("r(\\d+)").matcher(s);
if (m.matches()) {
int i = Integer.parseInt(m.group(1));
}
... which checks that the field is in the expected format before extracting the number.
On the other hand if you are really trying to read the string from a scanner them, you could do something like this:
String s = sc.next();
and then extract the number as above.
If the formatting is the same for all your input where the last char is the value you could use this:
String s = sc.nextLine()
Int i = Integer.parseInt(s.charAt(s.length() -1));
Else you could for instance make the string a char Array, iterate trough it and check whether each char is a number.

Get input from user in one line without space in java

I am a beiggner in java programming and i have a problem i want to get input from user in one line such as in c++
in c++ if i want to make a calculator i make 2 variable for example a band third is op and make user input them by
cin>>a>>op>>b;
if (op=='+')
{
cout<<a+b<<endl;
}
and so on how to make that in Java ?
i make a try in java but i get Error
and one more question how to make user input a char i try char a=in.next(); but get error so i make it string
code java
Scanner in=new Scanner(System.in);
int a=in.nextInt();
String op=in.nextLine();
int b=in.nextInt();
if (op=="+")
{
System.out.println(a+b);
}
else if (op=="-")
{
System.out.println(a-b);
}
.........
First of all, in Java you compare String with a.equals(b), in you example it would be op.equals("+"). And also, after reading a line it have the line break character (\n), so you should remove it to avoid problems. Remove it using String op = in.nextLine().replace("\n", "");.
And answering the how to read a character part, you can use char op = reader.next().charAt(0)

Scanner delimiter passed with parameter?

I need to parse an input-line character by character, and this will be done through several methods. To do it char by char, I am using useDelimiter(""). My question is: do i need to set this delimiter in every method? Or is it enough once, at the beginning?
e.g.
void start() {
Scanner in = new Scanner(System.in);
in.useDelimiter("");
char first = in.next();
readSecond(in);
...
}
void readSecond(Scanner in) {
//in.useDelimiter(""); <-- is this needed?
char second = in.next();
...
}
Example input: A5c*vd
Thanks !
You wouldn't have to set it every time if you declare and initialize the Scanner object in the class body that the methods are in. If you initialize the Scanner in each method, then I think you would have to set the delimiter in each method body.
Once set, the delimiter stays the same.
Therefore, you do not need to set it again to the same value.

Categories

Resources