import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
char[] course; //course code format: ABCDE##
String code;
//int num;
System.out.println("Input Course: ");
course = keyboard.next();
System.out.println(course);
code = String.copyValueOf(course, 0, 4);
System.out.println(code);
}
}
I don't know how I should let the user input the course when I'm using a character array instead of string. In short, how do I use the "scanner" on character arrays?
The instruction is the user will input a course code in the format: ABCDE##
Then, the program must split it into the course name and the course number. So, I had to use the copyValueOf method but it doesn't seem to work because from all the articles I read online, they used a char[] array but initialized the array with some value. So I was wondering how I could use the scanner on character arrays.
Why not just read a string from the scanner and then call String.toCharArray? It's not even clear why you need a char array here...
Why not just read a string directly with scanner.nextLine?
import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("Input Course: ");
String course = keyboard.nextLine();
System.out.println(course);
String code = course.substring(0, 5); //You put 4 but it left out the last letter in the course name. I changed it to 5 and it worked but I'm confused since the index always start with 0.
System.out.println(code);
String num = course.substring(5, 6);
System.out.println(num);
}
}
Related
For example, I entered a size of 3 Students. It skips index 0 in the console also in printing.
Please refer to this image, I have a sample size of 3 students and its output.
I don't have the slightest idea of why it skips index 0? Thanks for the help!
import java.util.Arrays;
import java.util.Scanner;
class string{
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
String [] arrName = new String[studentSize];
for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}
System.out.print(Arrays.toString(arrName));
//Closing Braces for Class and Main
}
}
The problem is with the console.nextInt(), this function only reads the int value.So In your code inside the loop console.nextLine() first time skip the getting input.just puting console.nextLine()afterconsole.nextInt()
you can solve the problem.
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
console.nextLine();
String [] arrName = new String[studentSize];
for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}
System.out.print(Arrays.toString(arrName));
//Closing Braces for Class and Main
}
The reason for this skip is due to the different behavior of the console.nextInt() and console.nextLine() as:
console.nextInt() reads the integer value entered, regardless of whether you hit the enter for new-line or not.
console.nextLine() reads the whole line, but as you previously hit thee enter when you give the size of Array.
3 was accepted as the size of the Array and when you hit enter it was accepted as the first value for you array which is a blank space or I can say it is referred as "".
Following are the two resolution for this:
Either put a console.nextLine() call after each console.nextInt() to consume rest of that line including newline
Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. you may convert to an integer using int studentSize = Integer.parseInt(console.nextLine()) method. (Surround it with try-catch)
I'm trying get 5 string inputs from the user and those inputs are going to be stored in an array. When I enter something like "Hello World" and hit a new line I can only enter 3 more words. So I want each user input to be a sentence and hitting enter should ask the user for another input on a new line.
Here is my code so far:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.next()+"\n";
String ask2 = user_input.next()+"\n";
String ask3 = user_input.next()+"\n";
String ask4 = user_input.next()+"\n";
String ask5 = user_input.next();
String[] cars = {ask1, ask2, ask3, ask4, ask5};
According to the documentation, Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
As the default delimiter used by Scanner is whitespace, calling next() will get you individual words from user input. When you want to capture multiple words that end with a newline, you should use Scanner.nextLine() instead.
Additionally, you can remove code duplication (which you always should do, keeping things DRY) by creating the array beforehand and allocating the user input entries within a loop:
final int numberOfCars = 5;
Scanner userInput = new Scanner(System.in);
String[] cars = new String[numberOfCars];
for (int i = 0; i < numberOfCars; i++) {
cars[i] = userInput.nextLine();
}
I recommend that you have a certain keyword or phrase that the user can type which stops the program. Here, I made a simple program that uses the java.util.Scanner object to receive keyboard input. Each value is stored in a java.util.ArrayList called "inputs." When the user is done entering input, he/she will type "stop" and the program will stop.
import java.util.*; //you need this for ArrayList and Scanner
public class Input{
public static void main(String[] args){
Scanner user_input = new Scanner(System.in); //create a scanner object
ArrayList<String> inputs = new ArrayList<String>(); //I used a java.util.ArrayList simply because it is more flexible than an array
String temp = ""; //create a temporary string which will represent the current input string
while(!((temp = user_input.next()).equals("stop"))){ //set temp equal to the new input each iteration
inputs.add(temp); //add the temp string to the arraylist
}
}
}
If you want to convert the ArrayList to a normal String[], use this code:
String[] inputArray = new String[inputs.size];
for(int i = 0; i < inputs.size(); i++){
inputArray[i] = inputs.get(i);
}
You can make this more generic by storing your question on an array and looping through a for loop prompting for input until you have question. This why when you have more questions you can add them to list without changing anything else on the code.
Then, to answer your original question regarding creating a String array, you could use following method String[] a = answers.toArray(new String[answers.size()]);
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
ArrayList<String> questions = new ArrayList<String>(5){{
add("What is your name?");
add("What is school you went to?");
add("Do you like dogs?");
add("What is pats name?");
add("Are you batman?");
}};
ArrayList<String> answers = new ArrayList<String>(questions.size()); // initialize answers with the same size as question array
String input = ""; // Stores user input here
Scanner scanner = new Scanner(System.in);
for(String question : questions){
System.out.println(question); // Here we adding a new line and the user type his answer on a new line
input = scanner.nextLine();
answers.add(input); // Store the answer on answers array
}
System.out.println("Thank you.");
String[] a = answers.toArray(new String[answers.size()]); // THis converts ArrayList to String[]
System.out.println("You entered: " + a.toString());
}
}
You want this instead:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.nextLine()+"\n";
String ask2 = user_input.nextLine()+"\n";
String ask3 = user_input.nextLine()+"\n";
String ask4 = user_input.nextLine()+"\n";
String ask5 = user_input.nextLine();
String[] cars = {ask1, ask2, ask3, ask4, ask5};
Can any one tell me that how to use Scanner Class of Java to find the frequency of a word in a sentence.
I am confused as to enter a line in java i have to use nextInt() function but to compare need it to convert in char so how to do so.
For example:-
I enter on terminal window(Giving Input)
This is my cat.
Now i have to find the FREGUENCY of word "this" in the above sentence. Please can you give me some idea.REMEMBER THE RESTRICTION IMPOSED ON IT IS I HAVE TO USE ONLY SCANNER CLASS OF JAVA LIBRARY
PROGRAMME USING STREAM READER IS AS FOLLOWS-
import java.io.*;
class FrequencyCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String: ");
String s=br.readLine();
System.out.println("Enter substring: ");
String sub=br.readLine();
int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
//i+sub.length() is used to reduce comparisions
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
}
alternative solution using pattern
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaApplication20 {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
System.out.print("Enter a word:\t");
String word = scanner.nextLine();
Pattern p = Pattern.compile(word);
Matcher m = p.matcher(sentence);
int count = 0;
while (m.find()){
count +=1;
}
System.out.println("in your sentence the frequency of \""+word+"\" is:\t" + count);
}
}
try out this.
public class JavaApplication20 {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
System.out.print("Enter a word:\t");
String word = scanner.nextLine();
int count = 0;
while (!sentence.equals("")){
if(sentence.contains(word)){ // check if the word is in the sentence; if yes cut the sentence at the index of the first appearance of the word plus word length
// then check the rest of the sentence for more appearances
sentence = sentence.substring(sentence.indexOf(word)+word.length());
count++;
}
else{
sentence = "";
}
}
System.out.println("in your sentence the frequency of \""+word+"\" is:\t" + count);
}
}
You can enter a String too using Scanner Class . Here is your code that i modified , and it working . `
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the String: ");
String s=in.nextLine();
System.out.println("Enter substring: ");
String sub=in.nextLine();
int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
//i+sub.length() is used to reduce comparisions
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
The nextLine() method of Scanner class let you input Strings.
Don't listen to #Uzochi. His answers may work, but they're way too complicated and may actually slow your program down.
For the Scanner class, there are multiple ways of reading in numbers or text:
nextInt() - scans in the next integer value
nextDouble() - scans in the next double value
nextLine() - scans in the next line of text
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html - scroll down to method summary, and in the middle of all of the methods, you will find all of the "next" methods.
Note that there is a small bug with Scanner (at least with the last time I used it). Say you're using a Scanner called scan. If you call
scan.nextInt();
scan.nextLine();
(which reads in an integer and then a line of text), your Scanner will skip the call to nextLine(). This is a small bug that can easily be fixed by adding another nextLine(). It will catch the second nextLine.
In response to #Uzochi, there is a much simpler solution to your algorithm. Your algorithm is actually faster than his, although there are some small things that could make your program run a tiny bit faster:
1) Use a while loop instead of a for loop. Your use of indexOf() makes the current index of the String s you're at skip forward a lot, so there's virtually no point in having a for loop. You can easily change it into a while loop. Your conditions would be to keep checking if indexOf() returns a non-negative value (-1 means there is no value), and you increment that index value by 1 (like the for loop does automatically).
2) Smaller thing - you don't need the line:
ind=-1;
Your current code will always modify ind before it hits that if statement, so there is virtually no reason to have this line in the program.
EDIT - #Uzochi may be using Java's built in libraries, but for a beginner like OP, you should be learning how to use for and while loops to efficiently write code.
I need help doing the following:
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
The below code is what I have so far but it is only returning user input and not removing numbers:
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1.replaceAll("[^0-9]","");
System.out.println(firstname1);
Updated Code. Thank you Hovercraft. I am now investigating how to retrieve all alpha characters as with the code below, I am only getting back the letters prior to the numeric values entered by the user:
import java.util.Scanner;
public class Assignment2_A {
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1 = firstname1.replaceAll("[^A-Z]","");
System.out.println(firstname1);
String input = yourScannerObject.nextLine ();
where "yourScannerObject" is the name you give your scanner.
What method did you use to scan? is it {scanner object name}.next() ?
if so you have got a string and all that you have to do is create some string, and save the input to it, e.g.:
String str="";
str = {scanner object name}.next();
before using anything in java, I would advise you to read the API :
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#next()
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
Here's an example:
String in;
Scanner scan = new Scanner("4r1e235153a6d 6321414t435hi4s 4524str43i5n5g");
System.out.println(in = (scan.nextLine().replaceAll("[0-9]", ""))); // use .next() for space or tab
Output:
read this string
The problem in your code is the regex "[^A-Z]" is set to remove all non-alphabet capital characters. This means you remove all lower case as well. You could say "[^a-zA-Z]", but then you're also removing special characters.
Ok so I'm trying to create a programmed where the user is asked to enter a word, this word is then stored as a variable, and then its displayed as an array.
This is what I have so far:
package coffeearray;
import java.util.Arrays;
import java.util.Scanner;
import java.lang.String;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String drink;
String coffee;
int [] a =new int[6];
Scanner in = new Scanner(System.in);
System.out.println("Please input the word coffee");
drink = in.next();
So basically I need some code so that the word stored is then displayed as variable. For example "Coffee" would then be displayed but each letter on its own line.
I've searched all over and can't seem to find out how to do this. Thanks in advance.
Given string str :
String str = "someString"; //this is the input from user trough scanner
char[] charArray = str.toCharArray();
Just iterate trough character array. I'm not going to show you this as this can easily be googled. Again if you're really stuck let me know, but you should really know this.
Update
Since you're new to Java. Here is the code per Jeff Hawthorne comment :
(for int i=0, i < charArray.getlength(); i++){
System.out.println(charArray[i]);
}
You can use String.split("")
Try this:
String word = "coffee"; //you get this from your scanner
if(word.length()>0)
String [] characterArray = Arrays.copyOfRange(word.split(""), 1, word.length()+1);
You can convert the String to a CharSequence:
CharSequence chars = inputString.subSequence(0, inputString.length()-1);
you can then iterate over the sequence, or get individual characters using the charAt() method.