JAVA
What is wrong in this program intelij is giving warnings and its not working
Please help
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter s or y or i");
String InputedData = sc.nextLine();
if(InputedData=="s"){
System.out.println("s was entered");
}
else if (InputedData=="y"){
System.out.println("y was entered");
}
else if (InputedData=="i"){
System.out.println("i was entered");
}
}
}
Answers
Correction :
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter s or y or i");
char InputedData = sc.nextChar();
if(InputedData=='s'){
System.out.println("s was entered");
}
else if (InputedData=='y'){
System.out.println("y was entered");
}
else if (InputedData=='y'){
System.out.println("i was entered");
}
else{
System.out.println("Wrong Input ");
}
}
}
Read my bio once
Question:-
Find the errors in the following code.
Answer:-
Given code,
import java.util.*;
class Scratch
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter s or y or i");
String InputedData = sc.nextLine();
if(InputedData=="s"){
System.out.println("s was entered");
}
else if (InputedData=="y"){
System.out.println("y was entered");
}
else if (InputedData=="i"){
System.out.println("i was entered");
}
}
}
Remember that, two strings are compared using equals() or equalsIgnoreCase() method.
After correction,the code will be,
import java.util.*;
class Scratch
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter s or y or i");
String InputedData = sc.nextLine();
if(InputedData.equalsIgnoreCase("s")){
System.out.println("s was entered");
}
else if (InputedData.equalsIgnoreCase("y")){
System.out.println("y was entered");
}
else if (InputedData.equalsIgnoreCase("i")){
System.out.println("i was entered");
}
}
}