How to comapre chars in Java - java

I wrote a code for calculator and I use char variable to get the mathematical operator (+, -, *, /). I need to check what operator did user input, but for some reason this code is not working. How can I compare char in Java?
import java.util.Scanner;
public class test_2 {
public static void main(String args[]) throws InterruptedException {
double val1, val2, total;
char thevindu;
Scanner input = new Scanner (System.in);
System.out.println("enter frist number");
val1 = input.nextDouble();
System.out.println("type operation");
thevindu = input.next().charAt(0);
System.out.println("enter second number");
val2 = input.nextDouble();
if (thevindu.equals ("+")) {
}
}
}

Since String is not one of the primitive types, that's why you compare it with equals() for thevindu you could just do thevindu == '+'

As others have said, chars can be directly compared using ==. This is because to a computer, a char is simply a number; only you defining what it should be interpreted as (when you declare the variable) sets apart a lowercase 'a' from the int 97. So even if in natural language asking if a variable is "equal" to the letter 'a' is strange, to a computer it makes perfect sense.
Strings cannot be compared in this way because they are non-primitive; they're actually an array of characters, and can't be directly compared.

Related

Write a program to receive input from user and check its spelling

I have written code to find if two strings are equal or not. The first string input should be given by the user and it should be compared with a second string which is predefined. But even when I am giving an input that is the same as the second string, the output is incorrect.
import java.util.Scanner;
public class correction {
public static void main(String[] args) {
int i,c=0;
String[] s1=new String[] {"F","R","I","E","N","D","S"};
String[] s2=new String[7];
System.out.println("enter a alphabet");
Scanner sc=new Scanner(System.in);
s2[0]=sc.next();
s2[1]=sc.next();
s2[2]=sc.next();
s2[3]=sc.next();
s2[4]=sc.next();
s2[5]=sc.next();
s2[6]=sc.next();
int length = s1.length;
for(i=0;i<length;i++)
{
if(s1.equals(s2[i]))
c++;
}
if(c==7)
System.out.println("right way");
else
System.out.println("wrong way");
}
}
I expected the output to be "right way" but the output is "wrong way". And c value is also 0.
You're currently comparing the entire array s1 with a specific letter in s2 in each iteration of your for loop. What you should be doing instead is to compare s1[i] with s2[i] like so,
int length = s1.length;
for(i=0;i<length;i++)
{
if(s1[i].equals(s2[i]))
c++;
}
if(c==7)
System.out.println("right way");
else
System.out.println("wrong way");
This way, you're now comparing each letter in s1 with each letter in s2, assuming you're only entering letters as input to s2.
Quick tips:
First, add a .lower() method to the .equals() method to avoid problems resulting from capital letters.
You are comparing the entire s1 array with an s2[i] value, you can change the s1 to s1[i].
New here so please ignore the crappy formatting.
s1 is a reference to an array, while s2[i] is reference to a String, which is why s1.equals(s2[i]) is evaluating to false, which is why c++ never runs.

I cast the scanners int to a char why is this giving me a mismatch exception?

public class Practice {
public static void main(String []args){
Scanner ScanMe=new Scanner(System.in);
char ch,answer='K';
System.out.println("I am thinking of a letter between A and Z.");
ch=(char)ScanMe.nextInt();
System.out.println(ch);
if(answer==ch){
System.out.println("CORRECT");
}
}
}
I created a new scanner, I created my char variables and then I read my char variables in and its giving a mismatch error???
Matt's solution is correct, but I wanted to add a bit of clarification. ch=(char)ScanMe.nextInt(); throws an exception because ScanMe.nextInt() gets evaluated first. Assuming you entered a letter, nextInt would throw an exception because a letter is not a decimal integer (which nextInt expects).
However, things will work if you enter a decimal integer. For instance, if you enter 75, this method call will work, and when you cast 75 to a char, it's actually 'K', so your program as originally written would say "CORRECT".
Check an ASCII table if that casting doesn't make sense.
Try using this to get a char
ch = ScanMe.next().charAt(0);
also K is not the same as k.
An Integer is not a char
Try using next and then just using the first char of the String
use String.charAt(int);
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int)

The operator < is undefined for the argument type(s) String, int

I'm having a problem when trying to run my program. What my program is supposed to do is to receive a number and compare it to an int. I understand that the program thinks that I'm trying to compare String with an int and not happy about it. What can I do?
import java.util.Scanner;
public class C {
public static void main(String args[]) {
Scanner input = new Scanner (System.in);
String age = input.nextLine();
if (age < 50){
System.out.println("You are young");
}else{
System.out.println("You are old");
}
}
}
You cannot compare a String to an int using a numerical comparison-operator. §15.20.1 of the Java Language Specification describes exactly what you are seeing:
The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
Since String is not convertible to a primitive numeric-type, you cannot compare it against an integer. Therefore you have two options:
You can convert the String into an int using Integer#parseInt:
int age = Integer.parseInt(ageString);
But in your case, since you are already reading in input, it would be better to bypass the whole parseInt bit and read in an int directly:
int age = input.nextInt();
Keep in mind though that you still have to deal with the possibility of invalid input.
You need age to be an integer in order to compare it to 50.
You have two options :
int age = input.nextInt();
or
int age = Integer.parseInt(input.nextLine());
Note that both options would throw exceptions if the input you enter is not an integer.
Before comparing you need to convert it to integer using parseInt().
You need to parse the String as an Integer.
String age = input.nextLine();
if (Integer.parseInt(age) < 50) {
System.out.println("You are young");
}
The scanner class actually has an input method called nextInt() that you can use:
Scanner input = new Scanner(System.in);
int age = input.nextInt();
// Comparisons
You cannot compare a String and a int values using "<",">","<=",">=" operators. That is the problem with your code. to fix that you can either,
take input from the user as int by replacing the line 5 as int age = input.nextInt();
or you can convert your age String to integer after taking inputs from the user using something like this int intage=Integer.parseInt(age);. Then you can replace your age variable with intage variable

How to convert an integer to char?

I am suppose to write a program that accepts an integer from the user using the Scanner class and displays the char data type representation of it. Assume the user will only enter a number from 0 to 127. As of now I have this.
import java.util.Scanner;
public class ASCIICharacterMcAfooseMark {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//This should allow the user to enter a number
System.out.print("Enter a number:");
String str = input.nextLine();
System.out.println(input);
//Need to get this to allow the entered number to show char value
int num = 0 - 127;
char c;
c = (char)num;
System.out.println(c);
}
}
When I enter this into command prompt it lets me enter a number, but all I get is a bunch of words and then a question mark. Any help would be appreciated. I am using Notepadd++ in Java.
Edit: For 32, the char representation would be space.
Edit: For the System.out.println(input); I was going by what I saw in my teacher's powerpoint. Should I get rid of it?
What do you mean by "char data type representation"? Given an input of
32 (for example), what would be the correct "char data representation"
to display in this case?
When I enter this into command prompt it lets me enter a number, but
all I get is a bunch of words and then a question mark.
Not all ints map to plain text chars. Some of them map to spaces, some to backspaces, some to "print line feeds", some to "modem control characters". For starters, look to positions 0-127 in the ACII table; however, Java really uses Unicode, so look to Unicode if you want to know how things happen above 127 (which includes your negative numbers).
Also, keep in mind that if you do not have a fully populated "glyph set" (the part of the font that draws to the screen, then various "code points" (the numbers that correspond to the glyphs) can't be drawn. Typically this is resolved by many systems with a substitution glyph, which is that funky question mark you're seeing.
Change your line:
int num = 0 - 127;//your num will always hold -127
To
int num = Integer.parseInt(str);//so you get integer representation of number string you just entered.
Notes apart:
Perhaps here System.out.println(input); you are trying to print string user entered, so you might need to change it to System.out.println(str);
There is an api which is specifically to read int from scanner and may be worth looking at here
Let's have a look at what your program is doing.
Scanner input = new Scanner(System.in);
Note that input is a Scanner object.
System.out.println(input);
Here you are displaying the Scanner object itself. Not what the user entered, because that is in the variable str. Maybe you wanted to do this instead:
System.out.println(str);
Then this line:
int num = 0 - 127;
This just sets num to -127. What you wanted to do instead is parse whatever is in str into an int:
int num = Integer.parseInt(str);
if you're assuming the user will put a number from 0 to 127, then try it like this:
import java.util.Scanner;
public class ASCIICharacterMcAfooseMark {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number:");
String str = input.nextLine();
System.out.println(input);
int num = Integer.parseInt(str); //you weren't using the value from the input
char c;
c = (char)num;
System.out.println(c);
}
}
char c;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number:");
int ip = input.nextInt();//<---- get integer
c = (char)ip;// cast int value to char
System.out.println(c);
if input is 97 output will be a

Java Comparing numbers and displaying largest, comparing strings and displaying lexiographically first

I need to create two different programs. One that does the following:
Enter your first number: 15
Enter your second number: 25
25 is larger than 15
and a second separate one that does the following:
Enter the first string: apple
Enter the second string: bananas
apple comes before bananas lexiographically
This is what I tried for the first one:
import java.util.Scanner;
public class ClosedLab03 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your first number: ");
int firstNumber = keyboard.nextInt();
System.out.println("Enter your second number: ");
int secondNumber = keyboard.nextInt();
int result;
if (firstNumber > secondNumber)
{
result = System.out.println(firstNumber +" is larger than " + secondNumber);
}
else
{
result = System.out.println(secondNumber + " is larger than " firstNumber);
}
Obviously I'm doing something wrong, but I don't really know what. In terms of comparing the strings, I really don't know how to compare them lexicographically. Our textbook shows us how to compare two strings and say whether or not they are the same, but not how to compare them and display which one is lexicographically first.
String.compareTo(String) does this for you. It implements the java.lang.Comparable interface.
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
Example
System.out.println("apples".compareTo("bananas")); // returns -1
System.out.println("bananas".compareTo("apples")); // returns 1
System.out.println("apples".compareTo("apples")); // return 0

Categories