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.
Related
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.
I'm trying to allow the user to put in multiple inputs from the user that contain a char and integers.
Something like this as input: A 26 16 34 9
and output each int added to an array.
I was thinking I could have the first input as a character and then read the rest as a string which then I separate and put into an array.
I'm not new to coding but new to java. I've been doing c++ so the syntax is a bit different.
This is what I have so far, I haven't set up my array yet for the integers.
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
int firstNumber;
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
int n = reader.nextInt();
if (n=='A') {
//if array is full System.out.println("The list is full!");
//else
System.out.println("Integer " + " " + "has been added to the list");
}
else if (n=='Q') {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Could you specify better how should your input be given? From your question, if I understand well, the user simply type "A" followed by a list of numbers separated by a space. So I would simply read the next line, split it in words (separated by a space) and check if the first word is the letter "A". Here it goes:
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
String line = reader.nextLine();
String[] words = line.split(" ");
if (words.length > 0 && words[0].equals("A")) {
//if array is full System.out.println("The list is full!");
// => I don't understand this part
//else
for(int i = 1; i<words.length; i++){
int integer = Integer.parseInt(words[i]);
System.out.println("Integer " + integer + " has been added to the list");
//do your stuff here
}
}
else if (words.length > 0 && words[0].equals("Q")) {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Note that in your solution, you read the next int from your scanner and then try to compare it with the character 'A'. This will not work because A is not an int. If you really want to get the first character from your scanner, you could do:
String line = reader.nextLine();
if(line.length() > 0){
char firstChar = line.charAt(0);
//do your stuff here
}
A character is not an int. You cannot read an int to expect something like 'A'. You can read a String and take its first character though. Scanner doesn't offer a convenient method to read the next String and expect it to be only one-character long. You'd need to handle that yourself.
But considering you don't know in advance how many numbers there will be to read, your solution to read the entire line and interpret it entirely, is the better one. That means you can't use nextInt() nor nextDouble() nor next() nor nextWhateverElse().
You need nextLine(), and it will give you the entire line as a String.
Then you can split() the result, and check if the first is one-char-long. Then you can parse all the others as int.
I don't immediately recall how to write this in Java – it's been a bit of a while – but what I'd do is to first separate the string by spaces, then attempt to do ParseInt on each piece.
If the string isn't a valid integer, this method will throw an exception, which you can catch. So:
If you make it to the next statement, an exception didn't happen, so the value is an integer.
If, instead, you find yourself in the exception-handler (having caught [only ...] the expected kind of exception, the value is a string.
Of course, don't "catch" any exception-type other than the NumberFormatException that you're expecting.
By the way, it is perfectly routine to use exceptions in this way. Let Java's runtime engine be the authority as to whether it's an integer or not.
I am trying to take a user inputted string and move the first letters before the first vowel to the end of the string. I'm stuck here, and just need a suggestion.
This is in java by the way
Find the index at which the first vowel is (suppose x), then use substring..
String modified = mystring.substring(x, mystring.length()) + mystring.substring(0, x);
Read the api for what substring actually does.
Okay. Here's the main method of the program that does what you need.
public static void main(String args[]){
String s;
int i=0;
//presume s gets user's input here
for(i=0;i<s.length();i++){
char c=s.charAt(i);
if(c=='a'||c=='A'||c=='e' || ...)
break;
}
if(i!=(s.length()-1)){
for(int j=i;j<s.length();j++)
System.out.print(s.charAt(j));
//displays from first vowel to end of string
}
else{
System.out.println("String ain't got any vowels.");
}
}
I'm new to the Java programming language and want to create a program that reads in three words using scanner class and lexicoggraphically order the three words doing this in the main method for example user enters Tom Harry Dick, answer should be Dick Harry and Tom.. I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void.
public class SortWords {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String firstWord;
String secondWord;
String thirdWord;
System.out.println("Enter three words seperated by white space");
firstWord = userInput.next();
System.out.println(firstWord);
secondWord = userInput.next();
System.out.println(secondWord);
thirdWord = userInput.next();
System.out.println(thirdWord);
}
}
Then try to read as an array elements then sort that array
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] strings = new String[3];
for (int i = 0; i < strings .length; i++)
{
System.out.println("Please enter name");
strings [i] = input.next();
}
}
Arrays.sort(strings);
"I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void."
This is incorrect.
First, we do not say an if statement 'returns anything', we say that it chooses to either execute its statement block or not (the one enclosed by { }) based on whether its condition (enclosed by ( )) evaluates to true or false. (Similar idea when else and else if are thrown in)
Second, this is not effected by the return type of the method it's in, since it has nothing to do with return.
You should use print and println statements to print out the results of your comparisons of the three strings, since this is the main method and there is no higher method to return to.
I'm trying to ask the user to enter a character ("y"/"n") and check whether or not that was the right answer. I'm getting the following error: "incomparable types: java.util.Scanner and java.lang.String"
Scanner userInput = new Scanner(System.in);
System.out.printf("Is this word spelled correctly?: %s", wordToCheck);
rightCheck(userInput);
public boolean rightCheck(Scanner usersAnswer)
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
Yes, because a scanner is a way of getting input rather than the value itself. You want to fetch the next value from the input, and then compare it. Something like this:
String answer = scanner.next();
if (answer.equals("y")) {
...
} else if (answer.equals("n")) {
...
}
Note that you should usually (including this case) not compare strings with ==, as that compares whether the two operands refer to the exact same string object - you're only interested in whether they refer to equal objects. (See this question for more details.)
I have modified your code, haven't tested it but it should work:
Scanner userInput = new Scanner(System.in);
System.out.println("Is this word spelled correctly?:" + wordToCheck);
rightCheck(userInput.next());//send the string rather than the scanner
public boolean rightCheck(String usersAnswer)//convert the parameter type to String
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
I believe you should first get the String from Scanner (through next() maybe?). Then in your method, do not use "==" as a string comparator.