How to pass Keyboard Input (int) in Java to String? - java

I have a text file having names separated by tab. I need to print the name at the given input number. like i have
abc def ghi jkl mno
when the user enters 2, it should print "def". What i did is
import java.io.*;
import java.util.*;
public class NamesTab {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char ch;
System.out.println("Enter the Number: ");
ch=(char) br.read();
System.out.println(ch);
BufferedReader s = new BufferedReader(new FileReader("Ass1.txt"));
String c=s.readLine();
String[] tokens = c.split("\t");
System.out.println(tokens[1]);
}}
but i could not pass the "ch" to "tokens[ch]". please help me.

You can use ch-'0' for single-digit numbers.
System.out.println(tokens[ch-'0']);

You're attempting to provide a character in a space which should be an Integer. I understand that this "should" work in java, but just to be safe, cast ch to an int when you're getting the index of the String array containing the characters you want.
System.out.println(tokens[(int)ch]);

Can we assume that ch always refers to a number between 0 to 9? If so, ch - '0' should do the trick.

Related

BlueJ string issue

I'm trying to create a program in BlueJ that allows the reader to type any word, then print out: that word, the length of the word, and whether or not the word contains "ing". I've figured out how to print the word and its length, but I can't figure out how to include whether "ing" is in the word.
Here is my code:
import java.util.*;
public class One
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = "";
System.out.println("Type in a word");
str = sc.nextLine();
//System.out.println(str);
System.out.println(str.length());
}
}
How can I tell whether "ing" is included in the word?
You can do that using the contains() method on your resulting string:
if (str.contains("ing")) System.out.println("Contains ING");
If you need to match either lowercase or uppercase, you can just convert str to upper case and check that instead:
if (str.toUpperCase().contains("ING")

Reverse a string with spaces.going through for loop

In this exercise I am to reverse a string. I was able to make it work, though it will not work with spaces. For example Hello there will output olleH only. I tried doing something like what is commented out but couldn't get it to work.
import java.util.Scanner;
class reverseString{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scan.next();
int length = input.length();
String reverse = "";
for(int i = length - 1; i >= 0; i--){
/*if(input.charAt(i) == ' '){
reverse += " ";
}
*/
reverse += input.charAt(i);
}
System.out.print(reverse);
}
}
Can someone please help with this, thank you.
Your reverse method is correct, you are calling Scanner.next() which reads one word (next time, print the input). For the behavior you've described, change
String input = scan.next();
to
String input = scan.nextLine();
You can also initialize the Scanner this way:
Scanner sc = new Scanner(System.in).useDelimiter("\\n");
So that it delimits input using a new line character.
With this approach you can use sc.next() to get the whole line in a String.
Update
As the documentation says:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
An example taking from the same page:
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
All this is made using the useDelimiter method.
In this case as you want/need to read the whole line, then your useDelimiter must have a pattern that allows read the whole line, that's why you can use \n, so you can do:
Scanner sc = new Scanner(System.in).useDelimiter("\\n");

How to read comma separated integer inputs in java

import java.io.*;
import java.util.*;
class usingDelimiters
{
public static void main(String args[])
{
Scanner dis=new Scanner(System.in);
int a,b,c;
a=dis.nextInt();
b=dis.nextInt();
c=dis.nextInt();
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}
}
This program is working fine when my input is 1 2 3 (separated by space)
But, how to modify my program when my input is 1,2,3 (separated by commas)
You can use a delimiter for non-numerical items, which will mark any non-digit as delimiter.
Such as:
dis.useDelimiter("\\D");
The useDelimiter method takes a Pattern or the String representation of a Pattern.
Full example:
Scanner dis=new Scanner(System.in);
dis.useDelimiter("\\D");
int a,b,c;
a=dis.nextInt();
b=dis.nextInt();
c=dis.nextInt();
System.out.println(a + " " + b + " " + c);
dis.close();
Inputs (either or)
1,2,3
1 2 3
Output
1 2 3
Note
Don't forget to close your Scanner!
See the API for Patterns for additional fun delimiting your input.
you can use the nextLine method to read a String and use the method split to separate by comma like this:
public static void main(String args[])
{
Scanner dis=new Scanner(System.in);
int a,b,c;
String line;
String[] lineVector;
line = dis.nextLine(); //read 1,2,3
//separate all values by comma
lineVector = line.split(",");
//parsing the values to Integer
a=Integer.parseInt(lineVector[0]);
b=Integer.parseInt(lineVector[1]);
c=Integer.parseInt(lineVector[2]);
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}
This method will be work with 3 values separated by comma only.
If you need change the quantity of values may you use an loop to get the values from the vector.

How to take a scanner object and make it a String

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.

Convert string user input to array

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.

Categories

Resources