How the scannner input for character ( Operators ) work? - java

I wrote a code about result for operator input taken by user and please explain me how this character input work because when i was using
char operation = s.nextLine().charAt(0);
instead of
char operation = s.next().charAt(0);
Eclipse showed Error.
Code -
System.out.println("Enter First Number:");
int a = s.nextInt();
System.out.println("Enter Second Number:");
int b = s.nextInt();
System.out.println("Which Operation you want to execute?");
s.hasNextLine();
char operation = s.next().charAt(0);
int result = 0;
switch (operation) {
case '+' :
result = a + b;
break;
case '-' :
result = a - b;
break;
case '*' :
result = a * b;
break;
case '/' :
result = a / b;
break;
case '%' :
result = a % b;
break;
default:
System.out.println("Invalid Operator!");
}
System.out.println(result);
s.close();
}
}

The problem is not because of s.nextLine(); rather, it is because of s.nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Use
int a = Integer.parseInt(s.nextLine());
instead of
int a = s.nextInt();
I would recommend you create a utility function e.g. getInteger as created in this answer to deal with exceptional scenarios as well.

From the documentation of Scanner https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
So if you put .nextLine() you're in fact reading what has left since the last input to the next line (ie nothing). This can be demonstrated with this code
Scanner s = new Scanner(System.in);
System.out.println("Enter First Number:");
int a = s.nextInt();
System.out.println("Enter Second Number:");
int b = s.nextInt();
System.out.println("Which Operation you want to execute?");
s.hasNextLine();
String s1 = s.nextLine();
String s2 = s.nextLine();
System.out.println(s1);
System.out.println(s2);
//char operation = s1.charAt(0); -> error
char operation = s2.charAt(0);//operator is read
The first print (s1) will not print anything. The second will print the operator.

Related

Calculator Java Input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm trying to make a calculator in java that can multiply subtract and add depending if the user wants that they can choose what they want. For some reason its giving me a weird output
Code
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.nextLine();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a * b);
break;
default:
System.out.print("Invalid input!");
}
}
}
Output
Enter first number- 2
Enter second number- 2
Do you want to multiply, add, divide, or subtract? Invalid input!
Like I didnt even type Invalid input it just does it by itself for some reason
There can be input left in the scanner before you request a value. In this case, the line break marks the end of the integer, but is not consumed as part of the integer. The call to nextLine() sees there is already an unused line break at the end of the buffer and returns that result. In this case, an empty string is returned. One way to fix this is to consume that unused line break first before requesting the next line or requesting a full line then parsing an integer from it.
Scanner scan = new Scanner(System.in);
// Always request a full line
int firstInt = Integer.parse(scan.nextLine());
int secondInt = Integer.parse(scan.nextLine());
String option = scan.nextLine();
// Use an extra call to nextLine() to remove the line break causing the issues
int firstInt = scan.nextInt();
int secondInt = scan.nextInt();
scan.nextLine(); // Consume the unused line break
String option = scan.nextLine();
sc.nextInt() does not read the enter key that you entered, so sc.nextLine() will read that new line and return it. Use sc.next() instead of sc.nextLine() to avoid this issue. Your code also multiplies the numbers when the user inputs add, so I changed that as well.
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.next();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a + b);
break;
default:
System.out.print("Invalid input!");
}
}
}

How to read characters and integers separately

I have to read the following symbols with Scanner and process them separately.
The input is:
###xx#*
1 -1 -1 4
The first line is the life and food of a game animal, the second row are her moves the - to the left, + to the right
I start with something, but not enough:
Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
while (!sc.hasNext("z")) {
char ch = sc.next().charAt(0);
System.out.print("[" + ch + "] "); // to check what is happening
}
How to read the second row of integers with - and + and then operate with them?
You can use Scanner 's built-in methods like nextInt() and next() also look for something like hasNextInt() it can be usefull.
You can use various scanner class functions to do that. Input is:
1 -1 -1 4
Create two arrays to store characters '-' and '+' and one to store integers
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
if(sc.hasNextInt()){
intArray = sc.nextInt();
}
else charArray = sc.next();
}
You can parse the input character to integer if it parses then you can continue your code if it throws number format exception then you should know input character is not a number.
Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
while (!sc.hasNext("z")) {
char ch = sc.next().charAt(0);
try {
int a = Integer.parseInt(String.valueOf(ch));
switch (a){
case 1:
// your condition
case -1:
// your condition
case -4:
//condition
default:
// your condition
}
}catch (NumberFormatException ex){
System.out.printf("input character is not number");
}
System.out.print("[" + ch + "] ");// to chack what is happening
}
The Java Scanner class has a whole bunch of methods for grabbing and parsing the next part of a string, e.g. next(), nextInt(), nextDouble(), etc.
The code looks like this:
String input = "1 -1 -1 4";
Scanner s = new Scanner(input);
int i1 = s.nextInt();
int i2 = s.nextInt();
int i3 = s.nextInt();
int i4 = s.nextInt();
Will read all four values
as most of the people is saying you can use scanner.nextInt() and about watching if you have to go the left or to the right you have the method Math.signum() which tells you were to go and then you can take the Math.abs() to get the value as an absolute number.
You could read whole line instead read by characters. Then split line into String array which will be contains chars of lines and operate with array. Here the solution of your case line.replaceAll("(-*[\\W\\d\\w])(\\s*)", "$1 ")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("z")) {
String line = sc.nextLine();
String[] split = line.replaceAll("(-*[\\W\\d\\w])(\\s*)", "$1 ").trim().split(" ");
Arrays.asList(split).forEach(ch -> System.out.print(ch + " "));
}
}
Output:
###xx#*
# # # x x # *
1 -1 -1 4
1 -1 -1 4

Read integers and strings from a single line of a console

The problem is like this:
I have two programs which takes input from a console but in different manner:
1)
Scanner input = new Scanner(System.in);
int temp1 = input.nextInt();
input.nextLine();
String str = input.nextLine();
int temp2 = Integer.parseInt(str);
int total = temp1+temp2;
System.out.println(total);
2)
Scanner input = new Scanner(System.in);
int temp1 = input.nextInt();
// input.nextLine();
String str = input.nextLine();
int temp2 = Integer.parseInt(str);
int total = temp1+temp2;
System.out.println(total);
In 1st case 1 take inputs in 2 different lines like
1
2
so it gives correct answer but in 2nd case I removed the input.nextLine() statement to take inputs in a single line like:
1 2
it gives me number format exception why?? and also suggest me how I can read integers and strings from a single line of a console.
The problem is that str has the value " 2", and the leading space is not legal syntax for parseInt(). You need to either skip the white space between the two numbers in the input or trim the white space off of str before parsing as an int. To skip white space, do this:
input.skip("\\s*");
String str = input.nextLine();
To trim the space off of str before parsing, do this:
int temp2 = Integer.parseInt(str.trim());
You can also get fancy and read the two pieces of the line in one go:
if (input.findInLine("(\\d+)\\s+(\\d+)") == null) {
// expected pattern was not found
System.out.println("Incorrect input!");
} else {
// expected pattern was found - retrieve and parse the pieces
MatchResult result = input.match();
int temp1 = Integer.parseInt(result.group(1));
int temp2 = Integer.parseInt(result.group(2));
int total = temp1+temp2;
System.out.println(total);
}
Assuming the input is 1 2, after this line
String str = input.nextLine();
str is equal to " 2", so it can't be parsed as int.
You can do simply:
int temp1 = input.nextInt();
int temp2 = input.nextInt();
int total = temp1+temp2;
System.out.println(total);
in your next line there is no integer ... its trying to create and integer from null ... hence you get number formate exception. If you use split string on temp1 then you get 2 string with values 1 and 2.

Java: can you change the value of the same string every time it loops?

I'm doing a very basic calculator program in java that asks for the users input, and based on what he inputs(if "add" or else) either adds up the two values or subtracts them.
The problem is, i want it to loop, so after every equation is finished and the result is displayed, it asks the user again if he wants to add or subtract. Is there any way, without using arrays, to change the value of the String each time the program loops?
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int i = 0; i<999; i++) {
System.out.println("Do you want to add or subtract?");
String answer1 = input.nextLine();
if (answer1.equalsIgnoreCase("add")) {
System.out.println("Enter first value");
int addv1 = input.nextInt();
System.out.println("Enter second value");
int addv2 = input.nextInt();
int ans = addv1 + addv2;
System.out.println("The answer is: " + ans);
} else {
System.out.println("Enter first value");
int subv1 = input.nextInt();
System.out.println("Enter second value");
int subv2 = input.nextInt();
int ans2 = subv1 - subv2;
System.out.println("The answer is: " +ans2);
}
}
}
}
Each time you assign a value to the String variable, answer1, it refers to a new String object, and the reference to the old String object is lost. So, no, you are not changing the value of the same String (and you can't, since String is immutable), you are changing the String that the variable is referring to.
I'm not clear on what your problem is, but I suspect it's this: Each line you input ends with a "new line" character. The nextInt functions will retrieve the next integer from the input, but they do not "consume" the newline character. Therefore, when you go back to the top of the loop and say
String answer1 = input.nextLine();
it will give you everything on the current line, up to the newline character. What this actually means is that it will give you an empty string, since that's all that's left on the current line after the previous integer is consumed.
If your program isn't working, try putting an additional nextLine() at the end of the loop:
for(int i = 0; i<999; i++) {
System.out.println("Do you want to add or subtract?");
String answer1 = input.nextLine();
if (answer1.equalsIgnoreCase("add")) {
// etc.
}
input.nextLine(); // ADD THIS
}
This will "consume" the leftover newline character, so that when you go back to the top, it will actually let the user enter another line.
P.S. See David's answer, which gives you a much better way of deciding when to leave the loop. (But you still need to add the nextLine.)
The problem is after you call int subv2 = input.nextInt();, the buffer has a newline character left, so that the following loop iteration, input.nextLine()is just an empty line. To fix this add a call to nextLine() after each iteration.
While the other posters are correct that "strings are immutable", you can achieve the effect you want with an "infinite" do..while loop that checks for a condition to break out of it, like so:
do {
System.out.println("Do you want to add, subtract, or quit?"); // changed this
String answer1 = input.nextLine();
if (answer1.equalsIgnoreCase("quit")) {
// check for "quit" value, and call break if that's what the user wants
break;
}
if (answer1.equalsIgnoreCase("add")) {
System.out.println("Enter first value");
int addv1 = input.nextInt();
System.out.println("Enter second value");
int addv2 = input.nextInt();
int ans = addv1 + addv2;
System.out.println("The answer is: " + ans);
} else { // this will catch anything that's not "add" or "quit". You might want to guard against that
System.out.println("Enter first value");
int subv1 = input.nextInt();
System.out.println("Enter second value");
int subv2 = input.nextInt();
int ans2 = subv1 - subv2;
System.out.println("The answer is: " +ans2);
}
} while (true); // will repeat forever until `break` is called

How to count instances of an specified char in a string in Java?

I've looked through everything relevant I can find on here, but for some reason nothing is helping. Whenever I run this I always end up with a result of 0. And no, I can not use other libraries for this (I saw some awesome solutions that have it down to one line, but I can't do that)
public void process()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your String:");
String in_string = input.nextLine();
Scanner input2 = new Scanner(System.in);
System.out.println("Press 1 to count the occurrence of a particular letter.");
System.out.println("Press 2 to count the total words in your input sentance.");
System.out.println("Press 3 to change your input sentance.");
System.out.println("Press 4 to exit.");
int option = input2.nextInt();
if (option==1)
{
System.out.println("Choose your letter: ");
String in_occurence = input.nextLine();
for(int i = 0 ; i < in_string.length(); i++)
{
if(in_occurence.equals(in_string.charAt(i)))
{
charCount++;
}
}
System.out.println(charCount);
}
You are comparing a String with a char using String#equals(). That will always give you false.
For example:
System.out.println("a".equals('a')); // false
You should convert the String to char by getting character at index 0 before comparison:
if(in_occurence.charAt(0) == in_string.charAt(i))
or, just declare in_occurrence as char type:
char in_occurence = input.nextLine().charAt(0);
You are comparing a String to a char which is never equal even if the String contains that char.
What you want is
if (in_occurance.charAt(0) == in_string.charAt(i)) // compare char

Categories