what is wrong in this code?
import java.io.IOException;
import java.util.*;
public class char_digit {
public static void main(String[] args) throws IOException {
int count=0;
while (true){
char t=(char) System.in.read();
if (t=='0'){
break;
}
count++;
}
System.out.println(count);
}
}
run:
a
b
c
d
e
f
0
12
You're counting the newlines as well as the other characters. Try something like if (t == '\n') continue; before the current if.
nothing is wrong. The carriage return also counts as a char (or 2 depending on your OS)
The problem is that you're counting whitespace characters as well, which are inserted when you hit the Enter button into the console. One quick fix is to use Character.isWhitespace check as follows:
if (t=='0'){
break;
} else if (!Character.isWhitespace(t)) {
count++;
}
Depending on what you want to do, though, a java.util.Scanner may serve your purpose better. Using System.in.read directly is highly atypical, and especially if you're reading char, where a Reader is more suitable.
Related questions
Java I/O streams; what are the differences?
What is the difference between a stream and a reader in Java?
Related
This question already has answers here:
How to read a single char from the console in Java (as the user types it)?
(7 answers)
Closed 2 years ago.
I was Trying to find a way to check the user input while typing so if they typed a special character ("#") the execution will terminate immediately without pressing Enter (using Java Scanner) , I tried this code but it needs to press enter each time .I couldn't find a way to do that
I'd appreciate any help.
import java.util.Scanner;
public class test{
public static void main(String[] args) {
Scanner scan =new Scanner(System.in);
while (true) {
String input =scan.next();
if (input.equals("#")) {
break;
}
System.out.println("yes");
}
}
}
you may read byte by byte and stop read when entering the special character.
For example:
char key;
do{
key = scanner.nextByte() // be careful with encoding. utf-8 may use 2 bytes per symbol
//do stuff
}while(key != '#')
Try reading the input char by char. Something like this:
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
if(c == '#')
{
// terminate execution
}
you can try this. System.in.read() will read the entered character. If the entered character is # you can terminate the execution. If the user has entered the enter key you can use the whitespace() method to break out of the loop.
char arr[] = new char[100];
for(int i=0;i<100;i++) {
arr[i] = (char)System.in.read();
if (arr[i].equals("#")) {
System.exit(1);
}
if(arr[i].isWhitespace()){
break;
}
}
I am trying to write one java program. This program take a string from the user as an input and display the output by removing the special characters in it. And display the each strings in new line
Let's say I have this string Abc#xyz,2016!horrible_just?kidding after reading this string my program should display the output by removing the special characters like
Abc
xyz
2016
horrible
just
kidding
Now I know there are already API available like Matcher and Patterns API in java to do this. But I don't want to use the API since I am a beginner to java so I am just trying to crack the code bit by bit.
This is what I have tried so far. What I have done here is I am taking the string from the user and stored the special characters in an array and doing the comparison till it get the special character. And also storing the new character in StringBuilder class.
Here is my code
import java.util.*;
class StringTokens{
public void display(String string){
StringBuilder stringToken = new StringBuilder();
stringToken.setLength(0);
char[] str = {' ','!',',','?','.','_','#'};
for(int i=0;i<string.length();i++){
for(int j =0;j<str.length;j++){
if((int)string.charAt(i)!=(int)str[j]){
stringToken.append(str[j]);
}
else {
System.out.println(stringToken.toString());
stringToken.setLength(0);
}
}
}
}
public static void main(String[] args){
if(args.length!=1)
System.out.println("Enter only one line string");
else{
StringTokens st = new StringTokens();
st.display(args[0]);
}
}
}
When I run this code I am only getting the special characters, I am not getting the each strings in new line.
One easy way - use a set to hold all invalid characters:
Set<Character> invalidChars = new HashSet<>(Arrays.asList('$', ...));
Then your check boils down to:
if(invaidChars.contains(string.charAt(i)) {
... invalid char
} else {
valid char
}
But of course, that still means: you are re-inventing the wheel. And one does only re-invent the wheel, if one has very good reasons to. One valid reason would be: your assignment is to implement your own solution.
But otherwise: just read about replaceAll. That method does exactly what your current code; and my solution would be doing. But in a straight forward way; that every good java programmer will be able to understand!
So, to match your question: yes, you can implement this yourself. But the next step is to figure the "canonical" solution to the problem. When you learn Java, then you also have to focus on learning how to do things "like everybody else", with least amount of code to solve the problem. That is one of the core beauties of Java: for 99% of all problems, there is already a straight-forward, high-performance, everybody-will-understand solution out there; most often directly in the Java standard libraries themselves! And knowing Java means to know and understand those solutions.
Every C coder can put down 150 lines of low-level array iterating code in Java, too. The true virtue is to know the ways of doing the same thing with 5 or 10 lines!
I can't comment because I don't have the reputation required. Currently you are appending str[j] which represents special character. Instead you should be appending string.charAt(i). Hope that helps.
stringToken.append(str[j]);
should be
stringToken.append(string.charAt(i));
Here is corrected version of your code, but there are better solutions for this problem.
public class StringTokens {
static String specialChars = new String(new char[]{' ', '!', ',', '?', '.', '_', '#'});
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Enter only one line string");
} else {
display(args[0]);
}
}
public static void display(String string) {
StringBuilder stringToken = new StringBuilder();
stringToken.setLength(0);
for(char c : string.toCharArray()) {
if(!specialChars.contains(String.valueOf(c))) {
stringToken.append(c);
} else {
stringToken.append('\n');
}
}
System.out.println(stringToken);
}
}
public static void main(String[] args) {
String a=",!?#_."; //Add other special characters too
String test="Abc#xyz,2016!horrible_just?kidding"; //Make this as user input
for(char c : test.toCharArray()){
if(a.contains(c+""))
{
System.out.println(); //to avoid printing the special character and to print newline
}
else{
System.out.print(c);
}
}
}
you can run a simple loop and check ascii value of each character. If its something other than A-Z and a-z print newline skip the character and move on. Time complexity will be O(n) + no extra classes used.
String str = "Abc#xyz,2016!horrible_just?kidding";
char charArray[] = str.toCharArray();
boolean flag=true;;
for (int i = 0; i < charArray.length; i++) {
int temp2 = (int) charArray[i];
if (temp2 >= (int) 'A' && temp2 <= (int) 'Z') {
System.out.print(charArray[i]);
flag=true;
} else if (temp2 >= (int) 'a' && temp2 <= (int) 'z') {
System.out.print(charArray[i]);
flag=true;
} else {
if(flag){
System.out.println("");
flag=false;
}
}
}
The second do while loop in this code:
do {
ignore = (char) System.in.read();
} while(ignore != '\n');
I cannot comprehend what it actually does. All I understand is that when I take it out and run the program and guess an incorrect letter, program will print out 3 lines of the text "Guess letter now". Why does it do that 3 times without that code in place. What does that code even do? So I am confused and just cannot work it out.
public class GuessChar {
public static void main(String args[])
throws java.io.IOException {
char ch ,ignore, answer = 'k';
do {
System.out.println("Guess the letter now");
ch = (char) System.in.read();
do {
ignore = (char) System.in.read();
} while(ignore != '\n');
if(ch == answer) System.out.println("WELL DONE");
} while(ch != answer);
}
}
First look at the most confusing part:
char ignore;
do {
ignore = (char) System.in.read(); // (1)
} while (ignore != '\n'); // (2)
The do loop is entered unconditionally, so the line marked (1) is always executed. What it does is reading a single character from the standard input stream and assign the 16 least significant bits (thanks to the typecast) to the variable ignore. It is confusing letters in Java are actually of type int but as long as you are only dealing with simple-enough letters (eg symbols from the ASCII character set) they are the same.
The line marked (2) checks whether the just-read character is different from the newline character \n. If so, it will re-enter the loop and break it otherwise.
In combination, this discards any input up to and including the next newline character (ie the end of the current line).
Before that loop, you are also reading in a single character and store it away in the variable ch.
char ch = (char) System.in.read();
After the loop has discarded any remaining characters on the line, you test whether ch (that is, the first character that was on the line) is equal to answer and, if so, exit or otherwise start anew.
In conclusion, the program reads, line-by-line, input from the user (prompting for each line) until the user enters something that starts with the letter k.
Now we have clarified what the program does, let's see how we can improve it. It turns out that reading one character at a time is very inefficient and there are already methods in the standard library that will do a better job. Using them and more expressive variable names, the intent of the program becomes much clearer.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GuessChar {
public static void main(String[] args) throws IOException {
char expected = 'k';
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Guess the letter now.");
while (true) {
String line = stdin.readLine();
if (line == null) { // end of input
System.out.println("Giving up, eh?");
break;
} else if (line.isEmpty()) {
System.out.println("Sorry, that was no input at all.");
} else if (line.charAt(0) == expected) {
System.out.println("Well done!");
break;
} else {
System.out.println("Sorry, please try again.");
}
}
}
}
'\n' is a character for "new line", meaning it waits for a user to press "Enter". So second loop will exit as soon as user press Enter, and will check for correct answer afterwards. If answer is wrong, all start from the beginning.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
im creating a program called "Book" for school and im having alot of trouble. IM suppost to find out how many times the character "a" comes up in a txt file. The txt file reads the following "go to the bathroom
he said
and he was right
I needed to go to the bathroom" . Here is my code but it doesnt seem to work at all and i am stuck.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Book
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner text = new Scanner (new File("data.txt"));
String word = null;
int count = 0;
while(text.hasNextLine())
{
word = text.nextLine();
for (int i = 0; i < word.length(); i++)
{
if (word.substring(i) == "a")
{
count++;
}
}
}
System.out.print(count);
}
}
The substring with one parameter returns a substring that starts at the given index. Also, you do not generally compare strings in Java using ==.
You need single quotes around a to make it a character constant, and charAt to get the specific character of the string, like this:
if (word.charAt(i) == 'a')
I think you are looking the charAt() function. substring() returns a String, but you really want a Character. Note: Characters are denoted with single quotes '
if (word.charAt(i) == 'a')
word.substring(i) returns a String, when used in an equality check with ==, the String objects in the operand are compared based on their location in memory, rather than their values.
Additionally, word.substring(i) will return the entire string beginning at i, not the character at i. To return just the character, you'll need to also specify the end index. (see the docs)
This will probably work if you replace
if (word.substring(i) == "a")
with
if (word.substring(i, i+1).equals("a"))
You are reading your text file line by line but
You can use FileInputStream to read char from file.
Here is an example given.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
File file = new File("data.txt");
if (!file.exists()) {
System.out.println(args[0] + " does not exist.");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
char current;
int count = 0;
while (fis.available() > 0) {
current = (char) fis.read();
if (current == 'a') {
count++;
}
}
System.out.println(count);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here you can iterate each char of file instead of line.
Hope this will help you.
sorry if its a stupid question, but I a beginner using StreamTokenizer, I am trying to solve this exercise this, please help me, I dont know what its wrong in my program that never reach my solve method, it also never finishes, I already ask in timus forum, but I know that here is faster to receive an answers
import java.io.*;
public class Prueba {
static int index = 0;
static double[] l = new double[131072];
public static void main(String args[]) throws IOException {
StreamTokenizer str = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
while (((str.nextToken() != StreamTokenizer.TT_EOF))) {
if (str.ttype == StreamTokenizer.TT_NUMBER) {
l[index++] = str.nval;
//System.out.println(str.nval);
// System.out.println(l[0]);
// System.out.println(l[1]);
}
}
solve();
}
public static void solve() {
double res;
for (int i = index - 1; i >= 0; i--) {
res = Math.sqrt(l[i]);
System.out.println(String.format("%.4f\n", res));
}
}
}
You are reading from the standard input, and your code loops until it gets a TT_EOF. To feed a TT_EOF into your program, you need to press Ctrl-D if you're using Unix, or Ctrl-Z followed by Enter if you're using Windows.
You are waiting on System.in, it is blocking on read, ergo, you will never get to EOF so you while loop will continue to wait for input.
As it is, you either need to pipe a file from command line, or enter text on console followed by EOF character. Pressing Ctrl+Z generates EOF in Windows, and pressing Ctrl+D generates EOF in Unix/Linux.
EDIT: If your input is single line you can check for TT_EOL instead of TT_EOF.
You must call eolIsSignificant(true) before entering the loop. This will make sure end-of-line is treated as separate token