Incompatible operand types Scanner and String? - java

I keep getting the following errors:
Incompatible operand types Scanner
and String
Incompatible operand types int and
String
before I added the int op = Integer.valueOf(operator) line it kept giving me errors when I would name my cases. I'm still very new it's the second code I've written for my class so please keep the explanation simple if at all possible (there is also a calculator class not shown here if there's any confusion about that) :
//change the package name to calculatorClass///////////////
import java.util.Scanner;
public class assignmentB {
public static String String(int y,int x, String name, String str) throws Exception {
if (y < 1)
throw new Exception("Value must be larger than 0.");
if (x < 1)
throw new Exception("Value must be larger than 0");
return name;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Calculator c1 = new Calculator();
Scanner input = new Scanner(System.in);
c1.name = "The total is $";
try {
} catch (Exception e1){
System.out.println(e1);
}
{
int x, y, s, a, m;
String name1;
System.out.println("Red River College");
System.out.println("Custom Calculator");
System.out.println("Enter first value: ");
x = input.nextInt();
System.out.println("Enter second value: ");
y = input.nextInt();
System.out.println("Enter operation(a=Add, s=Subtract, m=multiply): ");
String operator = input.nextLine();
int op =Integer.valueOf(operator);
switch (op) {
case 1:
if (input == "s") {
System.out.println(c1.name + c1.subtract(x,y));
}
case 2:
if (input == "a") {
System.out.println(c1.name + c1.add(x,y));
}
case 3:
if (input == "m") {
System.out.println(c1.name + c1.multiply(x,y));
}
}
}
}
}
```

You have defined input to be a Scanner, with this line:
Scanner input = new Scanner(System.in);
You can then use input to do scanner things, as you're doing here:
x = input.nextInt();
So far so good.
But later in the code, you do this (and a few variations that are similar):
if (input == "s") {
...
}
This isn't valid. The Java compiler is telling you that it will not allow you to use == to compare a Scanner (that is, input) against a String (which in this example is "s"). The compiler is giving you an error to say: input == "s" isn't allowed.
It isn't clear what your intent is (that is, how you want the code to actually behave), but the issue is definitely with those three if statements. Each is attempting to compare a java.util.Scanner with a java.lang.String (one is "s", one is "a", the last is "m"). So you'll need to fix those to do whatever it is you're trying to do.
As a guess, maybe you want to read a new String input from the scanner, and then compare that to "s", etc.? If so, that could look something like below. Note that to compare strings you should use equals() (don't use == to compare strings, or any other objects).
String newString = input.next();
switch (op) {
case 1:
if (newString.equals("s")) {
System.out.println(c1.name + c1.subtract(x, y));
}
...
}

Related

How to do repeated sequence check

Question: Repeated Sequence Check
The program should enter a string (possibly containing blanks), and determine whether the characters are in
lexicographic order.
For example:
“12AABab” is in order since each character is less than or equal to the one following it (‘1’ < ‘2’, ‘2’ <
‘A’, ‘B’ < ‘a’, etc.) according to the Unicode character sequence.
“abCDef” is out of order, because ‘b’ > ‘C’ (lower-case letters come after upper-case letters in the
Unicode sequence).
If the string is in order, the program should display “The input is in order”; otherwise, it should display
“The input is out of order”
The program should repeat this process until the user enters the string “quit”, regardless of case. It should
not check the sequence of “quit”.
Finally, the program should display “Goodbye”.
Notes:
This program will require nested loops. The inner loop will check the sequence of the input, while
the outer loop will repeat the input and check process.
Be sure to reinitialize all variables at the start of the outer loop.
A string of length 0 or 1 is considered to be in order by definition.
what I could do best is: (I tried with 2 other different methods I could send it too if you like)
package homelab03;
import java.util.Scanner;
public class Quest3deneme3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String whole,remain,d,e;
char h1,h2;
int lenght,b,c,sayac;
//int[] a;
String[] a;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
whole=whole.replaceAll("\\s+","");
lenght=(int)whole.length();
//System.out.println(+lenght);
remain=whole;
sayac=0;
c=0;
b=0;
a= new String[lenght];
//boolean cem = d.compareTo(e);
while(b<lenght)
{
a[b]=remain.substring(b,b+1);
remain=remain.substring(b+1);
System.out.println(a[b]);
d=a[b];
e=a[c];
while(a[b]<a[c] )
{
sayac=sayac+1;
h1=h2;
}
}
if(sayac==lenght)
{
System.out.println("oley");
}
else
{
System.out.println("nooo");
}
}
//a[b]=remain.substring(b,b+1);
//remain=whole.substring(b+1);
//System.out.println(a[b]);
}
note we haven't learned a[b] <= this thing yet but I find it online if the solution won't require that that would be better.
note 2: we haven't learned regex either I think that might be dissalowed (I found some answers with that online but I think I won't get credit for that)
You could check this code. Maybe it will inspire you :)
import java.util.Scanner;
public class howToDoRepeatedSequanceCheck {
public void repeatedTests() {
String whole;
int inputLength,i;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
while(!whole.equals("quit")) {
whole=whole.replaceAll("\\s+","");
inputLength = whole.length();
boolean isInOrder = true;
i = 0;
while(isInOrder && i<inputLength-1 ) {
if(whole.charAt(i)<whole.charAt(i+1)) {
// System.out.println("ok " + whole.charAt(i)+ " < " +whole.charAt(i+1));
}else {
// System.out.println("error");
isInOrder = false;
}
i++;
}
if(isInOrder == true) {
System.out.println("The input is in order");
}else {
System.out.println("The input is out of order");
}
System.out.println();
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
}
System.out.println("Goodbye");
}
}

Need advice on code java efficiency

I am new to java programming and I just created a calculator program and it seems to work fine but other programmers seem to use "parsing a lot" in their calculator programs. Just wanted to ask whether I'm taking a wrong approach and might run into problems in the future using this kind of logic.Thanks.
class Refresh {
private final String a;
private final String b;
private final String c;
private final String d;
private double x, y;
public Refresh() {
a = "Enter the first number: ";
b = "Enter the function; ";
c = "Enter the second number: ";
d = "The result is: ";
}
public void types() {
Scanner typ = new Scanner(System.in);
try {
System.out.println(a);
x = typ.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Please use only numbers!");
System.exit(1);
}
System.out.println(b);
String func = typ.next();
try {
System.out.println(c);
y = typ.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Please use only numbers!");
System.exit(1);
}
switch (func) {
case "+":
System.out.println(d + (x + y));
break;
case "-":
System.out.println(d + (x - y));
break;
case "/":
if (y == 0) {
System.out.println("Cannot divide by zero!");
} else {
System.out.println(d + (x / y));
}
break;
case "*":
System.out.println(d + (x * y));
break;
default:
System.out.println(func + " is not valid function");
}
}
public static void main(String[] args) {
Refresh fin = new Refresh();
fin.types();
}
}
Your program is fine as a demo or as a step in learning Java, but you probably would not use it as a production program. The reason is that your code assumes a command line interface (static void main(), Scanner, System.out.println()).
Users are used to graphical solutions nowadays. They expect the input and output to be given in a graphical front end and the calculations should be done in separate logic.
In this view, I would restructure your program in 3 parts:
A back end class which does the calculations (the Calculator class in the following sample code)
A front end class (called SimpleFrontEnd below) which builds on your code, but could later be replaced with e.g. a web interface
Data objects to communicate between back end and front end (the Calculation class below to send info from the front end to the back end)
Having these 3 parts, you can modify them independently of each other. You could decide that in the front end you only enter a single String, which is then parsed before being sent to the back end.
I would probably NOT use a single String in the front end that needs to be parsed, but a JSON object that maps directly to the Calculation class below, for the following reason: the front end can easily modify the operands and operator of the JSON object independently of each other, whereas modifying a string that has to be parsed is more complex.
Here is sample code that separates front end from back end:
public class Calculation {
private double leftOperand;
private String operator;
private double rightOperand;
public double getLeftOperand() {
return leftOperand;
}
public void setLeftOperand(double leftOperand) {
this.leftOperand = leftOperand;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public double getRightOperand() {
return rightOperand;
}
public void setRightOperand(double rightOperand) {
this.rightOperand = rightOperand;
}
}
public class Calculator {
public double calculate(Calculation calculation) {
switch (calculation.getOperator()) {
case "+":
return calculation.getLeftOperand() + calculation.getRightOperand();
case "-":
return calculation.getLeftOperand() - calculation.getRightOperand();
case "/":
if (calculation.getRightOperand() == 0) {
throw new IllegalArgumentException("Cannot divide by zero!");
}
return calculation.getLeftOperand() / calculation.getRightOperand();
case "*":
return calculation.getLeftOperand() * calculation.getRightOperand();
default:
throw new IllegalArgumentException(String.format("%s is not valid function", calculation.getOperator()));
}
}
}
public class SimpleFrontEnd {
public static void main(String[] args) {
try {
//1. input, could be later replaced with a front end
Scanner typ = new Scanner(System.in);
System.out.println("Enter the first number: ");
double x = typ.nextDouble();
System.out.println("Enter the function: ");
String func = typ.next();
System.out.println("Enter the second number: ");
double y = typ.nextDouble();
//2. store input in an data object that will be sent to the back end (later on, a web interface could send this as a JSON)
Calculation calculation = new Calculation();
calculation.setLeftOperand(x);
calculation.setOperator(func);
calculation.setRightOperand(y);
//3. retrieve the result from the back end
Calculator calculator = new Calculator();
try {
double result = calculator.calculate(calculation);
System.out.println(String.format("The result is: %f", result));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
} catch (InputMismatchException e) {
System.out.println("Please use only numbers!");
}
}
}
Parsing just means to scan a group of characters and then separate them into their own structures (tokenize them).
String aStr = "10";
The variable aStr would be of type String. You could then parse the string.
int aInt = Integer.parseInt(aStr);
Just for your information, Java has a built in calculator library.
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
String result = "100/10";
System.out.println(scriptEngine.eval(result));
Alright, this is actually very basic example. And honestly you did a great job. and even better at asking this question at this time. Usually people ignore efficiency during the learning process and get too late.
Why do they do parsing?
If you donot know about the below, then you should probably try reading more on it.
Scanner reads all the key inputs from users. Lets take example
Enter a number> 12
Scanner will hold 12\n
Now you see that? scanner is holding on to just number it is actually hold on to a string. which contains 12 and \n
When you ask scanner nextDouble it will just give you 12.
But then it is still holding on to that \n so the next string input, the string \n will be assigned.
By parsing, you will ignore this issue. And you will have better control over user input.

How to count blank spaces in a string using for loop [duplicate]

When I run the Javac, it tells me that i have an incomparable data types char and String in the
while(responseChar == "y")
not sure what to change to fix this error
import java.util.Scanner;
public class UseOrder
{
public static void main(String[] args)
{
int answer, num, q;
String name, response;
double p;
char responseChar;
Scanner keyboard = new Scanner(System.in);
Order order1 = new Order();
order1.setCustomerName();
order1.setCustomerNum();
order1.setQuantity();
order1.setUnitPrice();
order1.computePrice();
order1.displayInfo();
keyboard.nextLine();
System.out.println("Do you need the shipping and handling service?");
System.out.println("Enter y or n :");
response = keyboard.nextLine();
responseChar = response.charAt(0);
while(responseChar == "y")
{
ShippedOrder order2 = new ShippedOrder();
order2.getCustomerName();
order2.getCustomerNum();
order2.getQuantity();
order2.getUnitPrice();
order2.computePrice();
order2.displayInfo();
}
}
}
To define a character literal, use a single quote: '. Double quotes define string literals.
while(responseChar == 'y')
Optionally you could use the big C Character class to convert your char to a String:
String converted = Character.toString(responseChar);
while(converted.equalsIgnoreCase("y"))
{
// ...
}
But this version is much more verbose than the literal comparison suggested by Jeffrey
Instead of "y" do this 'y'. "" Represents string.

Java: if / else not responding even with no compile errors

I wrote a simple if / else that is supposed to print the answer to the if else. but does not respond even with the correct input. I can't see what I'm missing.
import java.util.Scanner;
public class MarriageQuiz{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String marStat;
System.out.print("Please enter your Marital Status (M or S) >> ");
marStat = input.nextLine();
marStat = marStat.toUppercase();
if(marStat.equals('M')){
System.out.print("You are married");
}
else if(marStat.equals('S')){
System.out.print("You are single");
}
}
}
Your code is comparing a String object against a character literal, which I believe the JVM will box into a Character object. Well, these two objects don't belong to the same class, so "M".equals('M') will return false. To remedy this, use "M".equals("M").
change toUppercase() to toUpperCase() and marStat.equals('M') to marStat.equals("M") also marStat.equals('S') to marStat.equals("S")
import java.util.Scanner;
public class MarriageQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String marStat = "";
System.out.print("Please enter your Marital Status (M or S) >> ");
marStat = input.nextLine();
marStat = marStat.toUpperCase();
if (marStat.equals("M")) {
System.out.print("You are married");
} else if (marStat.equals("S")) {
System.out.print("You are single");
}
}
}
On the other hand, you can use Character type instead of 'String'. Rather using Character would be more accurate as you are dealing with only one character.
Scanner input = new Scanner(System.in);
Character marStat;
System.out.print("Please enter your Marital Status (M or S) >> ");
marStat = input.next().charAt(0);
marStat = Character.toUpperCase(marStat);
if (marStat.equals('M')) {
System.out.println("You are married");
} else if (marStat.equals('S')) {
System.out.println("You are single");
}
use ""
if(marStat.equals("M")){
System.out.print("You are married");
}
else if(marStat.equals("S")){
System.out.print("You are single");
}
As mentioned in a comment above, you are comparing a String object to an autoboxed Character object. One fix is obviously using double quotes, which Java will autobox to a String object your code will work.
A few tips to save a few lines of code: use String.equalsIgnoreCase() to save a line converting the incoming string to uppercase.
Next, consider using a constant for marital status:
public class MarriageQuiz{
private static final String STATUS_MARRIED = "M";
...
if (marStat.equalsIgnoreCase(STATUS_MARRIED)) {
...
That way you can use STATUS_MARRIED all over your code but can change it from, say, "M" to "Married" easily.

How do you prompt a user for an input in java

So I just started learning Java, its literally like my 1st day and I wanted to try to make a coinflip game. I already know a decent amount of Javascript and so i was trying to apply that knowledge to java. So everything has been working so far except one thing: Prompting a user for a choice. So read online that i have to import a scanner so i did that as you can see from my code. I also tried some code where you can have the user import a string but you can see a bit later in my program i change the variable userChoice into a number. So basically i just need help with this. If there is some way to have a variable type that can store both numbers or strings that would be best. But im tottaly open to other ways of doing this! Thanks in advanced! Here is the code:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hi");
int bob;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
System.out.println("You entered "+ userChoice);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(userChoice == "Heads") {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!")
}
}
}
Use a scanner, as you said:
Scanner in = new Scanner(System.in);
Then, prompt the user to enter something in:
String userChoice = in.nextLine();
Also, when you compared strings:
if(userChoice == "Heads") {...
that's bad to do for none-primitive objects. It's best to only use the == to compare values that are ints or enums. If you compare a String like this, it won't work, because it's checking if the objects are the same. Instead, compare like this:
if(userChoice.equals("Heads")) {...
Also, to convert to an int (NOTE: You can't convert one type of object to another that aren't related in any way! You'll have to create a new object if you're wanting to do that), do this:
int myInt = Integer.parseInt(myString); // NOTE: Can throw NumberFormatException if non-number character is found.
So your program should look somewhat like:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
//System.out.println("hi");
Scanner in = new Scanner(System.in);
int bob;
int userChoice;
String input;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
input = in.nextLine(); // waits for user to press enter.
System.out.println("You entered "+ input);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(input.equals("Heads")) {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!");
}
in.close(); // IMPORTANT to prevent memory leaks
}
}
You've already imported the Scanner class so you can now create a variable of the type Scanner for taking inputs.
Scanner in = new Scanner();
userChoice = in.nextLine();
nextLine() can be used to input a character or a string from the user.
To convert the string into a integer, You can assign the integer value to the string in the following way.
if(userChoice == "Heads") {
userChoice = "" + 0;
}
else {
userChoice = "" + 1;
}
"String" datatype in Java can hold both numbers and strings (as you asked). You can get user input using Scanner utility as below:
Scanner input = new Scanner();
userChoice = input.nextLine(); // if it is a string
//userChoice = input.nextInt(); // if it's integer choice
If your string is an integer then you can also parse it to get its integer value. For parsing:
int value = Integer.parseInt(userChoice);
Also for comparing String values you should use "equals" function rather than "==".
if(userChoice.equals("Heads")){...} //rather than if(userChoice == "Heads"){...}
Having imported java.util.Scanner, to get input from the user as a String, create a Scanner object that parameterizes System.in and assign userChoice the value of nextLine() invoked by the Scanner object:
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
A few things about your code. The relational operator, ==, is used for comparing primitive data - not objects. Use string1.equals(string2) to see if two strings are equal.
Also, bob = (int) Math.floor(Math.random()*2); is really bob = (int)(Math.random() * 2);
because casting a double as an integer truncates the double to the highest integer less than or equal to it.
It might help you to get the ideas.
public static void main(String[] args) {
Random rd = new Random();
//Enter 1 0R 0
int bob = rd.nextInt(2);
String userChoice;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number");
userChoice = sc.nextLine();
System.out.println("You entered " + userChoice + " and bob is " + bob);
int uc = Integer.parseInt(userChoice);
if (uc == bob) {
System.out.println("Hehe");
} else {
System.out.println("Sorry");
}
}

Categories