Simple Calculator cant get past println - java

So here's my code.
https://ideone.com/ok42QZ
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
int z = sc.nextInt();
System.out.println("setvalueA");
int a = sc.nextInt();
System.out.println("setvalueB");
The main problem is that I cant get past System.out.println("setcaculatorinput") as it crashes right after that line.

Let me format your code...
first:
if ("+".equals(z))
; // it's an empty condition!
{ // this is an init block
System.out.println(c);
}
All your code "formated":
public static void main(String[] args) throws java.lang.Exception {
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
int z = sc.nextInt();
System.out.println("setvalueA");
int a = sc.nextInt();
System.out.println("setvalueB");
int b = sc.nextInt();
int c, d, e, f;
c = (a + b);
d = (a - b);
e = (a * b);
f = (a / b);
if ("+".equals(z))
;
if ("-".equals(z))
;
if ("*".equals(z))
;
if ("/".equals(z))
;
{ // init block
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(f);
}
System.exit(0);
}
The error is shown because you try to read an non integer character, read the Javadoc of new Scanner("").nextInt(); and you'll see that it throws: "InputMismatchException - if the next token does not match the Integer regular expression, or is out of range".
I give you a short solution, but I don't recommend it since no checks are performed on the inputs..
public static void main(String[] args) {
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
int result = 0;
System.out.println("setvalueA=");
int a = sc.nextInt();
System.out.println("setOperator=");
String op = sc.next();
System.out.println("setvalueB=");
int b = sc.nextInt();
if ("+".equals(op))
result = a + b;
else if ("-".equals(op))
result = a - b;
else if ("*".equals(op))
result = a * b;
else if ("/".equals(op))
result = a / b;
System.out.println("The result is=" + result);
System.exit(0);
}

1) for starter change your line 17 to String z = sc.next();
you are reading integer, passing character, and further treat it as string
2) after your each if statement, you have ; so each block after will be executed anyway

System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
int z = Integer.parseInt(sc.nextLine());
System.out.println("setvalueA");
int a = Integer.parseInt( sc.nextLine());
System.out.println("setvalueB");
Basically what is happenning is , While you are reading double as sc.nextInt(), you are reading only the int, however there would be ENDLINE character when you hit enter on the stream that is not read by sc.nextInt().

The problem is with trying to parse the input + as an integer in line 13 of your code (along with your first input on stdin). You can switch the call from .nextInt() to .nextLine() and change the type of z to a String
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
//switch z out for a String instead of an int, and use .nextLine()
String z = sc.nextLine();
System.out.println("setvalueA");
int a = sc.nextInt();
System.out.println("setvalueB");
int b = sc.nextInt();
...
}

This code will work :
import java.util.Scanner;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
String z = sc.next();
System.out.println("setvalueA");
int a = sc.nextInt();
System.out.println("setvalueB");
int b = sc.nextInt();
int c;
int d;
int e;
int f;
c = ( a + b );
d = ( a - b );
e = ( a * b );
f = ( a / b );
if("+".equals(z))
{
System.out.println(c);
}
if("-".equals(z))
{
System.out.println(d);
}
if("*".equals(z))
{
System.out.println(e);
}
if("/".equals(z))
{
System.out.println(f);
}
System.exit(0);
}
}
Thank you

Related

How to avoid InputMismatchException in java while taking input in int,char and int

I am new to Java and I want to solve a simple problem in java.
In input I need to take an integer a and then a character c and then another integer b And print the output if the character is '+' then print a+b And so on like this.
The input looks like : 6+4
But I find an error continuously like this
Exception in thread "main" java.util.InputMismatchException
My Code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
try {
int a, b, ans = 0;
char c;
a = sc.nextInt();
c = sc1.next().charAt(0);
b = sc.nextInt();
if (c=='+') {
ans = a + b;
} else if (c=='-') {
ans = a - b;
} else if (c=='*') {
ans = a * b;
} else if (c=='/') {
ans = a / b;
}
System.out.println(ans);
} finally {
sc.close();
sc1.close();
}
}
remove the double scanner object and try this
Scanner sc = new Scanner(System.in);
int a, b, ans = 0;
String c;
String input = sc.nextLine();
Pattern pattern = Pattern.compile("([0-9]+)([+*/-])([0-9]+)");
Matcher matcher = pattern.matcher(input);
if (!matcher.find()) {
System.out.println("Invalid command");
} else {
a = Integer.valueOf(matcher.group(1));
c = matcher.group(2);
b = Integer.valueOf(matcher.group(3));
if (c.equals("+")) {
ans = a + b;
} else if (c.equals( "-")) {
ans = a - b;
} else if (c.equals( "*")) {
ans = a * b;
} else if (c.equals("/")) {
ans = a / b;
}
System.out.println(ans);
}

Why can I not do sum of a and b?

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
int a = sc.nextInt();
boolean aValid = sc.hasNextInt();
System.out.println(aValid);
System.out.println("Enter Second number");
int b = sc.nextInt();
boolean bValid = sc.hasNextInt();
System.out.println(bValid);
if(aValid && bValid){
System.out.println("Sum of number is "+(a+b));
}
else{
System.out.println("Enter integer number");
}
}
}
I try to get input of a and b and validate that a and b are integers. But it takes three input. It gives the sum of the first two numbers and gives the validity of the last two.
you need to place check integer statements before taking input
boolean aValid = sc.hasNextInt();
int a = sc.nextInt();
boolean bValid = sc.hasNextInt();
int b = sc.nextInt();
Running this code makes the error fairly obvious. Some additional debug statements, running the code in debug or testing would also make it clear.
Scanner.nextInt() will throw an exception if it gets a non integer.
Scanner.hasNextInt() on the other hand returns a boolean value to warn you in advance whether it has an integer or not - it does not take the value from the Scanner.
This code has a couple of tiny corrections that will achieve the outcome you stated.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
} else {
sc.next(); //Discard the non-integer input.fr
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}

Resource leak: 'sc' is never closed

Program to count how many times a particular character, letter or number occur in a sentence.
However I keep getting message:
Resource leak: 'sc' is never closed
I am using Java and Eclipse. What should I do?
import java.util.Scanner;
class Number-count {
public static void number - count(String args[]) {
String s;
char ch;
int count = 0;
Scanner SC = new Scanner(System. in );
System.out.println("Enter a sentence");
String str = sc.nextLine();
System.out.println("Enter a character to be searched for occurence");
s = sc.nextLine();
char c = s.charAt(0);
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (ch == c) {
count++;
}
}
System.out.println("Character " + c + " occur " + count + " times");
}
}
Scanner objects need to be closed after one is done using them. So, after you're done with it you should call the following before the end of your main method
SC.close();
after your scanner work completed put: sc.close();
It is working 100%
Try this code
public static void number - count(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
try{
//your code
}
finally {
sc.close();
}
}
If you want to use the scanner globally in a class(which is the case sometimes)
try this:
static Scanner sc = new Scanner(System.in);
/* Making it easy for beginners, when we use Scanner sc it is required to be close once we have taken all inputs from user, to close use sc.close(); */
package basicjava;
import java.util.*;
public class sumbyuser {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your numbers for summation : ");
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a+b;
System.out.println("Summation is : "+sum);
}
}
Try sc.close();
After the using the scanner inputs :
import java.util.*;
public class Func1 {
public static void CalculateSum() {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a + b;
System.out.println("The sum is " + sum);
}
public static void main(String[] args) {
CalculateSum();
}
}

Reading space separated numbers from a file

I'm on my winter break and trying to get my Java skills back up to snuff so I am working on some random projects I've found on codeeval. I'm having trouble opening a file in java doing the fizzbuzz program. I have the actual fizzbuzz logic part down and working just fine, but opening the file is proving problematic.
So presumably, a file is going to be opened as an argument to the main method; said file will contain at least 1 line; each line contains 3 numbers separated by a space.
public static void main(String[] args) throws IOException {
int a, b, c;
String file_path = args[0];
// how to open and read the file into a,b,c here?
buzzTheFizz(a, b, c);
}
You can use the Scanner like so;
Scanner sc = new Scanner(new File(args[0]));
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
By default scanner uses whitespace and newline as seperators, just what you want.
try {
Scanner scanner = new Scanner(new File(file_path));
while( scanner.hasNextInt() ){
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
buzzTheFizz( a, b, c);
}
} catch( IOException ioe ){
// error message
}
Using a loop it reads the whole file, have fun:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
int c = 0;
String file_path = args[0];
Scanner sc = null;
try {
sc = new Scanner(new File(file_path));
while (sc.hasNext()) {
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
System.out.println("a: " + a + ", b: " + b + ", c: " + c);
}
} catch (FileNotFoundException e) {
System.err.println(e);
}
}
}

JAVA: Get 2 values for integer variables from the user in 1 line?

I'm trying to figure out if there is a way for the user to enter two values on one line and put each value in a separate variable.
For example, I have an integer variable "x" and an integer variable "y". I prompt the user saying: "Enter the x and y coordinates: ". Lets say the user types: "1 4". How can I scan x=1 and y=4?
Scanner scn = new Scanner(System.in);
int x = scn.nextInt();
int y = scn.nextInt();
You could do it something like this:
public class ReadString {
public static void main (String[] args) {
System.out.print("Enter to values: x y");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String values = null;
try {
values = br.readLine();
String[] split = values.split(" ");
if(split.length == 2)
{
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
}else{
//TODO handle error
}
} catch (IOException ioe) {
System.out.println("IO error!");
System.exit(1);
}
}
}
String[] temp;
String delimiter = "-";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
/* print substrings */
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
int[] arr = new int[2];
for (int i = 0; i < arr.length; ++i){
try{
int num = Integer.parseInt(in.next()); // casting the input(making it integer)
arr[i] = num;
} catch(NumberFormatException e) { }
}
input is your input of type String
String[] values = input.split(" ");
x = Integer.valueOf(values[0]);
y = Integer.valueOf(values[1]);

Categories

Resources