Get input from user in one line without space in java - 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)

Related

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: Scanning string, then search for integer

I am programing in java and have also very little programming experience.
I am trying to make a program there you first write in a number of integers in a scanner. In the next window you are supposed to write only one integer and that integer the program will search for and tell if it is or isn't in the "Scanner numbers"
My problem is that when i for example write 1 2 3 and in the next window write 2 it doesn't recognize there is a 2 in the scanner but if I instead write a 1 it works nicely.
Heres the code:
public class Inlämningsuppgift_kap9 {
public static void main(String[] args) {
String s1 = JOptionPane.showInputDialog("Write any number of integers!");
Scanner sc1 = new Scanner(s1);
String s2 = JOptionPane.showInputDialog(
"Chose a integer that the program will search for!"
);
int a = Integer.parseInt(s2);
while(sc1.hasNextInt()){
if(a == sc1.nextInt()){
JOptionPane.showMessageDialog(null, "The integer can be found");
System.exit(0);
}
else {
JOptionPane.showMessageDialog(null, "The integer cannot be found");
System.exit(0);
}
}
}
}
Thanks for any help!
Not going to do your homework for you, but a hint there: it is not a good idea to mix Swing UIs and a scanner that reads from stdin.
In other words: either use a graphical UI for all input/output; or just read/write from/to stdin (using out.println and that scanner code).
And then: assuming that the user first enters a string such as "1 2 3 4 5"; you need some further processing. You have to split that string (for example on spaces); and then turn each of that substrings ... into a real number. As your next step is to ask the user to input a number. And when you want to know if one number is in a list of other numbers, then you need to turn your initial string into that list of numbers!
So, you want to study javadoc for:
String.split()
Integer.parseInt()
you should not parse the input. makes it much easier to do what you want.
String s1 = JOptionPane.showInputDialog("Write any number of integers!");
String s2 = JOptionPane.showInputDialog("Chose a integer that the program will search for!");
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)==s2.charAt(0)){
JOptionPane.showMessageDialog(null, "The integer can be found");
System.exit(0);
}
}
JOptionPane.showMessageDialog(null, "The integer cannot be found");
System.exit(0);
i like this solution more since it has less code an still works fine
lets just anylyze your code and hope i'm not mistaken :) , the variables are initialized,then You start a loop with
while(sc1.hasNextInt())
it basically runs for x times where x is the number of inputs (sc1 variable's length) then you test if the number in current iteration is the number you look for. If it's you print success code and close the loop. if it isn't you print failure code and also close the loop. So when you provide 1 as input the execution is fine because 1 is the 1st element but 2 as second argument is never tested because of
System.exit(0);
in else's brackets

How to count the amount of space delimiters in a string using the for loop?

I am new to Java and am working on an assignment where you need to count the amount of delimiters or spaces in a string that the user inputs.
I have to use a method that prompts the user to input a string using the Keyboard class. However, I am using BlueJ and Keyboard is not compatible with the BlueJ library thing. I do know that Scanner could be as an alternative with Keyboard but I am not sure how to read a string using Scanner.
Furthermore, I am not sure how I am suppose to structure my for loop to count the delimiters in a string. I am sorry for my high misunderstanding with this and I know that I am asking a lot but please don't feel obligated to answer everything, just whatever you want to or what you can easily answer. Here is my code below:
import cs1.keyboard;
import java.util.StringTokenizer;
public class Counting_Chars
{
public static void main (String []args)
{
int spaceCount = 0, characterCount = 0;
String line, word;
StringTokenizer tokenizer;
System.out.println("Please enter text (type DONE to quit):");
line = scan.nextLine();
String phrase = line;
for (String ch = phrase.charAt(line);; ch <= line; count++)// I don't really know what I am doing here
{
System.out.println (count);
}
}
}
it sounds like you are having multiple issues here. Perhaps it would be good to break the problem down into smaller parts and build your way back up again.
I would suggest something like:
write a program that just prints out some text (like 'Hello World')
write a program that asks the user to type in a line of text and
then just prints out that exact same text again
then worry about counting the spaces in the string

How to accept strings or integers in the same user input

I want to accept user input as either an integer or a string in Java but I always get an error no matter what I do.
My code is very simple (I'm a beginner):
System.out.println(
"Enter the row number (or enter e to quit the application):"
);
Scanner rowInput = new Scanner(System.in);
int row1 = rowInput.nextInt();
I want the user also to be able to press "e" to exit.
I have tried several things:
1) To convert row1 to a String and and say:
if((String)(row1).equals("e"){
System.out.println("You have quit") }
2) To convert "e" to an integer and say:
if(row1 == Integer.ParseInt("e"){
System.out.println("You have quit") }
3) To do the switch statement but it said I had incompatible types (String and an int).
My errors usually say: Exception in thread "main" java.util.InputMismatchException
Is there somebody who could help me?
Many thanks in advance!
You can try something like this
Scanner rowInput = new Scanner(System.in);
String inputStr = rowInput.nextLine();
try{
int row1 = Integer.parseInt(inputStr);
} catch (NumberFormatException e) //If exception occurred it means user has entered 'e'
{
if ("e".equals(inputStr)){
System.out.println("quiting application");
}
}
you should read the input from your scanner as String type and the try to convert that String input into integer using Integer.parseInt().
If its successful in parsing, it means user has input an Integer.
And If it fails, it will throw an exception NumberFormatException which will tell you that its not an Integer. So you can go ahead and check it for e if it is, do whatever you want as per your requirement.
You can't use nextInt() if you aren't sure that you will have a number coming in. Also, you can't parse e as an integer, because it is not an integer, it's either char or string (I'll suggest string in this case).
That means, your code should look like:
System.out.println("Enter the row number (or enter e to quit the application):");
Scanner rowInput = new Scanner(System.in);
string row1 = rowInput.next();
Then you have the data in a string. You can simply check if the string is e:
if (row1.Equals("e")) ...
It is also a good idea to check if the input is actually an integer then. Good way to check it is described here:
How to check if a String is numeric in Java
1) you should say Integer.parseInt() instead of Integer.ParseInt()
2) if you pass "e" to Integer.parseInt() you'll get java.lang.NumberFormatException
3) get your input as a string this way (cause it's safer)*:
Scanner rowInput = new Scanner(System.in);
String row = rowInput.next();
if (row.equals("e")) {
//do whatever
}
else if(row.matches("\\d+$")) {
//do whatever
}
*In your approach if user enters a non-integer input you'll encounter java.util.InputMismatchException
I have tried several things ....
Attempting to solve this problem by "trying things" is the wrong approach.
The correct approach is to understand what is going on, and then modify your solution to take this into account.
The problem you have is that you have a line of input that could be either a number or the special value e which means quit. (And in fact, it could be a couple of other things too ... but I will come to that.)
When you attempt to either:
call Scanner.nextInt() when the next input is not an integer, OR
call Integer.parseInt(...) on a String that is not an integer
you will get an exception. So what do you do?
One way is to change what you are doing so that you don't make those calls in those situations. For example:
call Scanner.hasInt() to see if the next token is an integer before calling nextInt(), or
test for the "e" case before you attempt to convert the String to an integer.
Another way to deal with this is to catch the exception. For example, you could do something like this:
String s = ...
try {
number = Integer.parseInt(s);
} catch (NumberFormatException ex) {
if (s.equals("e")) {
...
}
}
Either way will work, but I'm going to leave you to work out the details.
But the real point I'm trying to make is that the right way to solve this is to understand what is happening in your original version / versions, and based on your understanding, modify what you were doing. If you just randomly "try" alternatives that you found with Google, you won't progress to the point of being a productive programmer.
I said there were other cases. They are:
The user types something that is neither a number of your special e character. It could be anything. An empty line, hi mum ...
The user types the "end of file" character; e.g. CTRL-D on Linux or CTRL-Z on windows.
If you want your program to be robust you need to deal with these cases too.
Try this:
public class Demo{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String choice = null;
System.out.println("Enter e to exit or some other key to stay:");
choice=s.next();
if(choice.equals("e"))
{
System.out.println("quits");
System.exit(0);
}
else
{
System.out.println("stays");
}
}
}
You can't convert a string into integer, use char ASCII codes instead.

What does this code want me to do?

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);

Categories

Resources