Difference between next( ) and next( ).CharAt(0); - java

I have created an abstract class Employee which displays and calculates the Details of Weekly and Hourly Employee.In the main method i have used switch case for a menu and do while to continue using the program as long as the user want.But I'm getting an Error when compiling the code.:
*javac "AbstractDemo.java" (in directory: /home/user/Desktop)
AbstractDemo.java:52: error: incompatible types
ch=s.next();
^
required: char
found: String
1 error
Compilation failed.*
This is the Source Code:
import java.util.*;
abstract class Employee{
Employee(float amt,int n){
float sal;
System.out.println("The amount paid to Employee is:"+amt);
sal=amt*n;
System.out.println("Total Salary is:"+sal);
}
}
class WeeklyEmployee extends Employee{
WeeklyEmployee(float a,int n){
super(a,n);
}
}
class HourlyEmployee extends Employee{
HourlyEmployee(float amt,int hrs){
super(amt,hrs);
}
}
public class AbstractDemo {
public static void main (String args[]) {
int a;
char ch;
float amount;
int hours;
int weeks;
Scanner s=new Scanner(System.in);
do{
System.out.println("Enter the choice");
a=s.nextInt();
switch (a) {
case 1 :
System.out.println("Enter the salary of weekly employee(Per Week):");
amount=s.nextFloat();
System.out.println("Enter the total no of week");
weeks=s.nextInt();
Employee W=new WeeklyEmployee(amount,weeks);break;
case 2:
System.out.println("Enter the salary of hourly employee(Per hour):");
amount=s.nextFloat();
System.out.println("Enter the total no of hours");
hours=s.nextInt();
Employee H=new HourlyEmployee(amount,hours);break;
default:System.out.println("Error invalid Choice");
}
System.out.println("Do you wish to continue?(Y/N)");
ch=s.next();
}while (ch== 'y'||ch== 'Y');
}
}
But When i use s.next().ChatAt(0); the code compiles successfully.Could somebody explain why this is happening?Is Char taking input as String?Or if it is a string why its showing an Error when i edit the while condition to while(ch=="y"||ch=="Y"); ?

ch is a char. s.next() returns a String. You can't assign a String to a char. You can assign the first character of the String to a char, which is what you do in ch = s.next().charAt(0);.
It's a good thing you are not trying while(ch=="y"||ch=="Y"), since that would fail even if you changed ch to be a String (which would allow it to pass compilation, but wouldn't give the expected result), since you can't compare Strings in Java with == (you should use equals instead).

s.next() returns the next String object. But s.next().charAt(0) returns the first character of the next String object. Hence its expecting character and throwing error

the method next() of the Scanner object returns a String. So in order for your assignment to work, you need to extract the first character from this string using the charAt() method.
And since ch is a character not String, while(ch == "y" || ch == "Y") won't work.
Use while(ch == 'y' || ch == 'Y') instead.
(single quotes = character, double quotes = string)

This because ch is char and your idea is input single letter Y or N to stop or continue your program. But, you use method next() of Scanner that return a String. That's main reason why you get this
*javac "AbstractDemo.java" (in directory: /home/user/Desktop)
AbstractDemo.java:52: error: incompatible types
ch=s.next();
^
required: char
found: String
1 error
Compilation failed.*
When you try to use s.next().ChatAt(0). It mean that you try to get first character from input.
-> this is just imcompatible types error when you try to assign String to Char without converting it.

When you use s.next(), it is read as a string. That's why you get an error with ch=s.next()
However, s.next().charAt(0) will return a char value which can be used by your variable.
Likewise, when you compare char ch to 'y', it compares two chars, but "y" reads as a string and would cause a type mismatch.

Related

Bad operand types for binary operator '||' error

I've been trying to create a program where if the user types in candy or C into the Scanner then the program will execute some code although I'm having difficulty comparing the two variables.
import java.util.Scanner;
public class StringOrChar
{
public static void main(String[] args)
{
System.out.println("Guess a word or character");
Scanner keyboard = new Scanner(System.in);
String input;
input = keyboard.nextLine();
char c = input.charAt(0);
if (input.equalsIgnoreCase("candy") || c = "C")
{
System.out.println("You guessed correctly.");
}
else
{
System.out.println("Try again...");
}
}
}
Upon running the program I receive the error " bad operand types for binary operator '||' " although I'm clueless as to how to go about fixing it. I'm aware that I could use
input.equals("C")
but I would like to know how to use the charAt() method.
If your intent is to allow the user to type "candy" or "C", your code won't get the job done even after you fix the compiler errors. It's checking the first character for C, which means that it will match any user input beginning with C, including Charlie, Caddywumpus, etc. If that's not what you want, then you have to compare the entire string to "C" and forget charAt(0):
if (input.equalsIgnoreCase("candy") || input.equalsIgnoreCase("C")) {
On the other hand, if you really do want to allow any input beginning with C, you need to make that clear in your question.
Few mistakes, need to correct. Though equalsIgnoreCase is sufficient to match candy or Candy or CANDY, ** anything uppercase/lowercase in word candy
1.) c = "C" is assignment not comparison.
2.) c is char here, so need to compare char with char, not char with String. so write c == 'C'
Code should go as below.
Code
public static void main(String[] args) {
System.out.println("Guess a word or character");
Scanner keyboard = new Scanner(System.in);
String input;
input = keyboard.nextLine();
char c = input.charAt(0);
if (input.equalsIgnoreCase("candy") || c == 'C') {
System.out.println("You guessed correctly.");
} else {
System.out.println("Try again...");
}
}
Ouput
1.) User Types C
Guess a word or character
C
You guessed correctly.
2.) User Types c
Guess a word or character
c
Try again...
3.) User types candy or Candy
Guess a word or character
candy
You guessed correctly.
You just won't require any other check
if (input.equalsIgnoreCase("candy") || c == 'C' )
Edit : handling only character input

Converting Strings to Uppercase with charAt

I'm writing a program that asks the user to enter their last name in lower case and asks them if they want it outputted as all caps or with just the first letter capitalised. The problem I'm having is using charAt with toUpperCase.
import java.util.Scanner;
//This imports the scanner class
public class ChangeCase {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
//This allows me to use the term scan to indicate when to scan
String lastName;
//sets the variable lastName to a string
int Option;
System.out.println("Please enter your last name");
//Prints out a line
lastName = scan.nextLine();
//scans the next line of input and assigns it to the lastName variable
System.out.println("Please select an option:"+'\n'+"1. Make all leters Capitalised"+'\n'+ "2. Make the First letter Capitalised");
Option = scan.nextInt();
if (Option == 1){
System.out.println(lastName.toUpperCase());
}
if (Option == 2){
System.out.println(lastName.charAt(0).toUpperCase());
}
}
}
I get an error saying "Cannot invoke toUpperCase() on the primitive type char"
You can't apply String.toUpperChase on a char like your error is saying. In the case where you want to make the first letter uppercase you can do something like:
String lastName = "hill";
String newLastName = lastName.substring(0, 1).toUpperCase() + lastName.substring(1);
System.out.println(newLastName);
A sample run of this:
run:
Hill
BUILD SUCCESSFUL (total time: 0 seconds)
In the case where you want all the letters uppercase, it's as simple as
newLastName = lastName.toUpperCase();
System.out.println(newLastName);
A sample run of this:
run:
HILL
BUILD SUCCESSFUL (total time: 0 seconds)
I used to try this in C programming in college. Should work here as well.
(char)(lastName.charAt(i) - 32)
Try the above in System.out.println
The code when we deduct 32 from character it reduces ascii value by 32 and hence gets upper case letter. Just refer an ascii table to understand what I am trying to tell by deduction of 32 places in the table.
As your error is telling you, you can't invoke String.toUpperCase() on a primitive char type.
System.out.println(lastName.charAt(0).toUpperCase());
But, you can invoke Character.toUpperCase(char) like
System.out.println(Character.toUpperCase(lastName.charAt(0)));
Or, call String.toUpperCase() and then take the first character. Like,
System.out.println(lastName.toUpperCase().charAt(0));

User Input not working with keyboard.nextLine() and String (Java)

I recently started learning java during my spare time. So to practice, I'm making a program that takes a temperature (Celsius or Fahrenheit) and converts it to the opposite. I've already imported the keyboard scanner.
int temp;
String opposite, type;
double product;
System.out.print("Please enter a temperature: ");
temp = keyboard.nextInt();
System.out.println("Was that in Celsius or Fahrenheit?");
System.out.print("(Enter 'C' for Celsius and 'F' for Fahrenheit) ");
type = keyboard.nextLine();
if (type == "C") // Only irrelevant temp conversion code left so I'm leaving it out
I'm new to the String and nextLine stuff and the program just skips over the user input section where you enter either C or F. Would someone explain what I can do to fix this?
Thanks!
For you code Change nextLine(); to next(); and it will work.
System.out.println("Was that in Celsius or Fahrenheit?");
System.out.print("(Enter 'C' for Celsius and 'F' for Fahrenheit) ");
type = keyboard.next();
to get an idea for you to what happened was this:
nextLine(): Advances this scanner past the current line and returns the input that was skipped.
next(): Finds and returns the next complete token from this scanner.
Also like the many of the answers says use equals() instead of using ==
The == checks only the references to the object are equal. .equal() compares string.
Read more Here
Never use Scanner#nextLine after Scanner#nextInt. Whenever you hit enter button after Scanner#nextInt than it will skip the Scanner#nextLine command. So,
Change from
int temp = keyboard.nextInt();
to
int temp = Integer.parseInt(keyboard.nextLine());
.nextInt() does not read the end of line character "\n".
You need to put a keyboard.nextLine() after the .nextInt() and then it will work.
Also, use type.equals("C") instead of if (type == "C"), the later one is comparing the reference of the value.
Call
keyboard.nextLine();
After
temp = keyboard.nextInt();
Because nextInt() doesn't consume the \n character.
Also, compare Strings with .equals(); not ==
if(type.equals("C"));
Use Scanner Class:
int temp;
java.util.Scanner s = new java.util.Scanner(System.in);
String opposite, type;
double product;
System.out.print("Please enter a temperature: ");
temp = s.nextInt();
System.out.println("Was that in Celsius or Fahrenheit?");
System.out.print("(Enter 'C' for Celsius and 'F' for Fahrenheit) ");
type = s.nextLine();
if (type.equals("C")){
do something
}
else{
do something
}
For More Input references:
Scanner
BufferedReader
String
Here is a wonderful comparison on how to compare strings in java.
You could use keyboard.next() instead of nextLine()
and as
user1770155
mentioned to compare two strings you should use .equals()
and what I would do since you're comparing to an upper letter "C" is
type = keyboard.next().toUpperCase();
if (type.equals("C"))

How to convert user inputted char to its numerical position in Java? [duplicate]

This question already has answers here:
How to map character to numeric position in java?
(7 answers)
Closed 5 years ago.
So I'm stuck on this problem in my Java intro class. I'm a complete newbie at this stuff, so any help is appreciated. I have to design and create a program that accepts a user inputted letter (which should be either a-z or A-Z) and determine what position it holds in the alphabet. (so a would equal 0) I keep having issues with string to char and char to int conversions. Any tips or leads on how to design this program would be much appreciated. I've been working on this program literally all day and haven't had made any discernible progress.
Just subtract the char constant 'a' from your input char.
Try the following code:
char c = 'b';
System.out.println(c - 'a' + 1);
The output will be 2.
In order to get a user inputted anything use a Scanner. In this case the following code will prompt the user for a character then assign that to a variable called 'c'.
import java.util.*;
// assuming that the rest of this code is inside of the main method or wherever
// you want to put it.
System.out.print("Enter the letter: ");
Scanner input = new Scanner(System.in);
char c = Character.valueOf(input.next());
Then using this code use whatever method you like to convert to alphabetical position. Hope that helps!
I think it was answered already but putting it all together:
/**
* Gets the numerical position of the given character.
*/
private static final int convertToPosition(final char c) {
return c - 'A' + 1;
}
public static void main(String[] args) throws Exception {
System.out.print("Enter the letter: ");
Scanner input = new Scanner(System.in);
if (input.hasNext()) { // if there is an input
String inStr = input.next().toUpperCase();
if (inStr.length() != 1) {
System.out.println("Unknown letter");
return;
}
char c = inStr.charAt(0);
int pos = convertToPosition(c);
System.out.println("Position: " + pos);
} else {
System.out.println("no input");
}
}

Creating a sub menu using String/char?

public static String getSubMenu(String submenu){
Scanner keyboard = new Scanner(System.in);
String chosen="", A="A",B="B", a="a", b="b";
do{
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
}while(chosen.compareTo(A));
return chosen;
}
//This function below is fine.
public static void Menu(){
String unem="";
do{
System.out.println("Sub Menu");
System.out.println("Select an Option\n\n");
System.out.println("a.Sort by name\n" +
"b.Sort by time\n" +
"c.Exit sub-menu\n\n");
System.out.print("Input the number for the selected option: ");
unem= getSubMenu(unem);
if("a".equals(unem)|| "A".equals(unem)){
}
if("b".equals(unem)|| "B".equals(unem)){
}
}while ("a".equals(unem) ||"b".equals(unem) || "A".equals(unem) || "B".equals(unem));
}
}
Hi, I'm trying to make a sub menu. As you can see in the function Menu, when getSubMenu is called the user has to input a selected option in the function getSubMenu. I looked through my textbook and online and it doesn't seem you can use char within arguments such as
char a="a";
if(a != b);
If you can use characters instead of strings in the functions above please tell.
But moving on. What I am trying to do now is to get getSubMenu to return a String containing either 'A' || 'a' || 'b' || 'B' || 'c' || 'C' and then loop when the user does not put any of these as an input. I've tried attempting to use compareTo but I receive a Type mismatch: cannot convert from int to boolean error how can I improve on this. What syntax can I use so that this can work.
Thanks for everyone who will help and contribute to this.
EDITED: NEW WORKING FUNCTION
public static String getSubMenu(String submenu){
Scanner keyboard = new Scanner(System.in);
boolean looped = true;
String chosen="";
do{
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
if("a".equals(option)|| "A".equals(option) || "b".equals(option)|| "B".equals(option) || "c".equals(option)|| "C".equals(option)){
looped = false;
}
else
System.out.println("Wrong input");
}while(looped);
return option;
It may of not been what I was aiming for but it still did it job.
while(chosen.compareTo(A)) is where you should get an error . The method compareTo(String) returns an int which you cannot use in while(boolean expression) , it requires a boolean expression which shall evaluate to true or false. I am pasting a code for reference , improvise on it :
public static String getSubMenu(String submenu) {
Scanner keyboard = new Scanner(System.in);
List<String> list = Arrays.asList(new String[]{"A","B","C"});
do {
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
} while (chosen!=null && list.contains(chosen.toUpperCase()));
return chosen;
}
compareTo() compares 2 objects and returns an int that represents which object was greater. Since it is not a boolean your do while loop fails to compile. If you're looking for a specific input from the user, use this snippet.
do
{
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
}
while (!chosen.trim().equalsIgnoreCase("a"));
You'll need to trim() the string to remove characters like whitespaces and you can use equalsIgnoreCase() to match 'A' and 'a'.

Categories

Resources