scanner that may scan both integer and character - java

i was trying to do some practice for my school. Please help me because i wanted to get both integers and string in a single scanner. Is it possible?
Scanner pal = new Scanner (System.in);
System.out.print("Enter Temperature you want to convert: ");
temp = pal.nextInt();
System.out.print("Convert to?: ");
convert_to = pal.next();

If I understood your requirement properly - you want to parse an input like '12 C'. To do this we can read the input and then parse it based on each word. So in this case the first index will contain the degree and the second index will contain the unit.
Scanner pal = new Scanner (System.in);
System.out.print("Enter Temperature you want to convert: ");
String values[] = pal.nextLine().split(" ");
int temp = Integer.parseInt(values[0]);
char unit = values[1].charAt(0);
You can then use this for the convert question, thereby we are using just one Scanner object to read all the input.
System.out.print("Convert to?: ");
String convertTo = pal.next();

Related

How to input characters using Classes and Objects

I'm making a java program that has to store data using classes and objects, My question is how do input characters like a name ( billy ) into my code.
Here is the class i did.
class bank
{
int AccountID;
int HolderName;
double AccountBalance;
}
And i'm assigning here
angel.AccountID = 7532;
angel.HolderName = 753; // angel
angel.AccountBalance = angelbalance;
I know that i can input integers using the following code
System.out.println("Set Balance for Angel: ");
int angelbalance = sc.nextInt();
My question is how do i input text/characters in a way (scanner) does with integer
Sorry for the bad explanation.
Do you mean getting the name input using the Scanner object? Because you've imported java.util.Scanner, you can do:
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
This will read the next line.
You can use (JOptionPane.showInputDialog) and it is easy to use if you want input from user
String name= JOptionPane.showInputDialog("Enter your name: "));
You need to either call the Scanner.nextLine() method or the Scanner.next() method to store String input such as a name like "Billy". Here is an example below:
//You can use the Scanner.next() method or the Scanner.nextLine() method to store Strings
Scanner scan = new Scanner(System.in);
System.out.println("Enter a name: ");
String billy = scan.next();
System.out.println("You entered: " + billy);
And here is your output:
Enter a name:
Billy
You entered: Billy
I'd check out the Scanner documentation here: https://docs.oracle.com/javase/8/docs/api/java/util/class-use/Scanner.html

How can I use IndexOf with Scanner?

I'm a beginner in Java, so I apologize if this seems too easy for you to reply, still I hope I can get a little help from here.
I wanted to get an input from the user with Scanner, writing a sentence.
Then the user would pick a word from that sentence.
And then with string.indexof(""), the program should count from which number the word starts in that sentence.
But the result is always -1. And I don't understand why.
String a,b;
Scanner sc= new Scanner(System.in);
System.out.println("Please write a sentence");
y=sc.next();
Scanner sc2 = new Scanner(System.in);
System.out.println("Please pick a word from that sentence");
System.out.println("The word starts from=" + (y.indexOf(a=sc2.next())));
But the result is always -1. And I don't understand why.
The only scenario in which -1 will be returned is if there is no such occurrence of the specified String.
Scanner#next() only returns what comes before a space, meaning anything after space is ignored. It seems that you'll need to use the Scanner#nextLine to store the whole sentence rather than Scanner#next().
e.g.
y = sc.nextLine();
{
String a,b;
Scanner sc= new Scanner(System.in);
System.out.println("Please write a sentence");
String y=sc.nextLine();
Scanner sc2 = new Scanner(System.in);
System.out.println("Please pick a word from that sentence");
System.out.println("The word starts from=" + (y.indexOf(a=sc2.nextLine())));
}

How to use the Scanner class properly?

I'm doing an assignment for class. For some reason the program completely skips the part where the variable name is supposed to be typed in by the user. I can't think of any reason why it's behaving this way, since the rest of my code that is after the cardType part (which asks for things such as String and int types work fine and in order.
System.out.println("Enter the card information for wallet #" +
(n+1) + ":\n---\n");
System.out.println("Enter your name:");
String name = scan.nextLine();
name = capitalOf(name);
System.out.println("Enter card type");
String cardType = scan.nextLine();
cardType = capitalOf(cardType);
You probably need to consume the end of the last line you read prior to trying to get the user name :
scan.nextLine(); // add this
System.out.println("Enter the card information for wallet #" +
(n+1) + ":\n---\n");
System.out.println("Enter your name:");
String name = scan.nextLine();
name = capitalOf(name);
System.out.println("Enter card type");
String cardType = scan.nextLine();
cardType = capitalOf(cardType);
It is behaving this way because I am quite sure you used the same scanner object to scan for integers/double values before you used it to scan for name.
Having said that does not mean you have to create multiple scanner objects. (You should never do that).
One simple way to over come this problem is by scanning for strings even if you are expecting integers/doubles and cast it back.
Scanner scn = new Scanner(System.in);
int numbers = scn.nextInt(); //If you do this, and it skips the next input
scn.nextLine(); //do this to prevent skipping
//I prefer this way
int numbers = Integer.toString(scn.nextLine());
String str = scn.nextLine(); //No more problems

Unclosed Character Character Literal Error

My code is below. Not sure how to eliminate this problem. I tried using next.Line(), but that did not work.
String demoEmpName;
int demoIdNum;
double demoPayRate;
int demoHoursWorked;
Scanner keyboard = new Scanner(System.in);
System.out.print("What is your name?");
demoEmpName = keyboard.nextString();
System.out.println("What is your ID number?");
demoIdNum = keyboard.nextInt();
System.out.println("What is your hourly pay rate?");
demoPayRate = keyboard.nextDouble();
System.out.println("How many hours did you work?");
demoHoursWorked = keyboard.nextInt();
Payroll pyrll = new Payroll(demoEmpName, demoIdNum, demoPayRate, demoHoursWorked);
Change keyboard.nextString() to keyboard.next().
There is no nextString() method in Scanner class.
Oh, and in case all this code you posted is not enclosed in some method, that would be another problem.
There is no existence of nextString() method in the Scanner class.If the employee's name consists of just a single word,you should use:-
demoEmpName=keyboard.next();
If the name consists of more than one words,use demoEmpName=keyboard.nextLine();

How do I make Java register a string input with spaces?

Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}

Categories

Resources