Program to display character only displays '?' in java - java

Wrote a program to display all that character. But the output only display the ? character. I am a total newbie, please help.
public class charSheet {
public static void main(String args[]){
char c;
for(int i = 0; i < 65536; i++){
c = (char) i;
System.out.println(i + "---" + c);
}
}
}
Output(only a part):
57987---?
57988---?
57989---?
57990---?
57991---?
57992---?

Try printing it till 100, it does prints some characters, you probably are using command prompt which does not supports much characters, try using some IDE such as Eclipse, i think you will get better results.

Range of characters are from 0 - 255.
Everything after that is therefore irrelevant.

Related

Does System.out.println move the cursor to the next line after printing in some cases?

import java.util.Scanner;
public class CanYouReadThis {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String input = scn.next();
int i = 0;
while ( input.length() > i && input.charAt(i) < 'a' )
{
System.out.println(input.charAt(i));
i++;
while(input.length() > i && input.charAt(i)> 'Z' )
{
System.out.print(input.charAt(i));
i++;
}
}
}
}
Input : IAmACompetitiveProgrammer
Excepted Ouput :
I
Am
A
Competitive
Programmer
My Output :
I
A
mA
C
ompetitiveP
rogrammer
import java.util.Scanner;
public class CanYouReadThis {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String input = scn.next();
int i = 0;
while ( input.length() > i && input.charAt(i) < 'a' )
{
System.out.print(input.charAt(i)); // removed ln
i++;
while(input.length() > i && input.charAt(i)> 'Z' )
{
System.out.print(input.charAt(i));
i++;
}
System.out.println(); // Added this line
}
}
}
I made these changes to my code and it works fine . But isn't the logic of both programs the same. What am i missing here ? Please help me out .
Println renders and outputs its argument followed by whatever is configured as the JVM's end-of-line character sequence1.
The normal behavior and expected behavior2 of a console program when it gets that sequence is to move to the start of the next line.
In the light of this, two versions of your program are clearly different. The first version outputs a line separator after the first character, and not the last one. The second version outputs a line separator after the last character of each word but not the first one.
The output you are getting reflects that difference.
"Shouldn't it just print on the new line and leave the cursor there?"
Well, that depends on the console program's implementation. But on platforms where "\n" is the line separator, the default behavior of a console program should be to go to the start of the next line. Whether that is correct in terms of the historical meaning of the ASCII NL characters as implemented by 1960's era teleprinters, etc is moot.
The fact that Linux and Windows console programs interpret these things is also a historical anomaly. But you can get yourself into problems if you hard-wire "\n" or "\r\n" into your output. That is why println is provided, and why Formatter.format (etc) support %n as meaning line separator.
1 - On Windows it is "\r\n", and on Linux it is "\n".
2 - However, the actual behavior depends on the implementation of the console. That is outside of Java's control.

I want to know what is system.out.println() doing in this code

I don't know why there are system.out.println in the end of these code. what is this and why is it here?
This code is a code from my friend, he told me to understand this code and I don't understand why there are system.out.println after this code.
public class Nestedlooplab2 {
public static void main(String[] args) {
for (byte i = 1; i <= 5; i++) {
for (byte j = 1; j <= i; j++) {
System.out.print(".");
}
for (byte k=1; k<=(5-i);k++) {
System.out.print("*");
} System.out.println();}
}
}
First, let's take a look at the output of your code:
.****
..***
...**
....*
.....
As a String, this is the same as:
.****\n..***\n...**\n....*\n.....\n
Using System.out in Java writes to the standard output-stream of characters by default. When you write to this stream, you can use various methods, including System.out.print and System.out.println. Calling print will output the exact String that you provide to it, whereas calling println will output the String you provide to it, followed by a new line (the line separator for your system). If you call System.out.println() (println with no parameter), you will output the String you provided ("") as well as move the output to the next line. Essentially, this means removing calls to System.out.println() in your code will result in the following output:
.****..***...**....*.....
This output will look exactly the same as a String. As you can see, there are no newline characters (\n) within your output when you only call System.out.print and don't call System.out.println.
Finally, let's take a look at your code in the context of making it easier to read and understand. I'm using the Java 11+ feature String.repeat to massively simplify the operation of repeating a String here:
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(".".repeat(i)+"*".repeat(5-i));
}
}
Output:
.****
..***
...**
....*
.....
This is equivalent to the original output. However, it's much clearer to read and understand what is going on. Supposing that you don't have access to those features, you can do the following instead:
for (int i = 1; i <= 5; i++) {
for(int rpts = 0; rpts < i; rpts++) {
System.out.print('.');
}
for(int rpts = i; rpts < 5; rpts++) {
System.out.print('*');
}
System.out.println();
}
This snippet of code also has the same output. Its content is not much different from your code snippet, as your code snippet does have the right idea. However, it is more consistently formatted, which makes it easier for yourself and others to read the code. Do note how the repeats are labelled with a name rpts, and (in both examples) the iteration variables are ints. Java programmers usually use ints to iterate because the space you save from using bytes to iterate is negligible enough to ignore for most applications, and integers cover most ranges of values you might want to iterate over.
Welcome to stack overflow!
By itself a System.out.println() will just print a newline character, e.g. \n. If you were to add a parameter to this statement it would print your parameter along with a newline.
Here are the JavaDocs for println
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
The code you linked would print a certain amount of . characters and certain amount of * characters without any line breaks. The final System.out.println(); would then print a newline character and the loop would start over again.
Output:
.****
..***
...**
....*
.....
The output of your code is:
.****
..***
...**
....*
.....
Without the System.out.println();, the output would be:
.****..***...**....*.....
The System.out.println(); prints a new line character to the screen for each interaction of the loop.

Space Replacement for Float/Int/Double

I am working on a class assignment this morning and I want to try and solve a problem I have noticed in all of my team mates programs so far; the fact that spaces in an int/float/double cause Java to freak out.
To solve this issue I had a very crazy idea but it does work under certain circumstances. However the problem is that is does not always work and I cannot figure out why. Here is my "main" method:
import java.util.Scanner; //needed for scanner class
public class Test2
{
public static void main(String[] args)
{
BugChecking bc = new BugChecking();
String i;
double i2 = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (i2 <= 0.0)
{
i = in.nextLine();
i = bc.deleteSpaces(i);
//cast back to float
i2 = Double.parseDouble(i);
if (i2 <= 0.0)
{
System.out.println("Please enter a number greater than 0.");
}
}
in.close();
System.out.println(i2);
}
}
So here is the class, note that I am working with floats but I made it so that it can be used for any type so long as it can be cast to a string:
public class BugChecking
{
BugChecking()
{
}
public String deleteSpaces(String s)
{
//convert string into a char array
char[] cArray = s.toCharArray();
//now use for loop to find and remove spaces
for (i3 = 0; i3 < cArray.length; i3++)
{
if ((Character.isWhitespace(cArray[i3])) && (i3 != cArray.length)) //If current element contains a space remove it via overwrite
{
for (i4 = i3; i4 < cArray.length-1;i4++)
{
//move array elements over by one element
storage1 = cArray[i4+1];
cArray[i4] = storage1;
}
}
}
s = new String(cArray);
return s;
}
int i3; //for iteration
int i4; //for iteration
char storage1; //for storage
}
Now, the goal is to remove spaces from the array in order to fix the problem stated at the beginning of the post and from what I can tell this code should achieve that and it does, but only when the first character of an input is the space.
For example, if I input " 2.0332" the output is "2.0332".
However if I input "2.03 445 " the output is "2.03" and the rest gets lost somewhere.
This second example is what I am trying to figure out how to fix.
EDIT:
David's suggestion below was able to fix the problem. Bypassed sending an int. Send it directly as a string then convert (I always heard this described as casting) to desired variable type. Corrected code put in place above in the Main method.
A little side note, if you plan on using this even though replace is much easier, be sure to add an && check to the if statement in deleteSpaces to make sure that the if statement only executes if you are not on the final array element of cArray. If you pass the last element value via i3 to the next for loop which sets i4 to the value of i3 it will trigger an OutOfBounds error I think since it will only check up to the last element - 1.
If you'd like to get rid of all white spaces inbetween a String use replaceAll(String regex,String replacement) or replace(char oldChar, char newChar):
String sBefore = "2.03 445 ";
String sAfter = sBefore.replaceAll("\\s+", "");//replace white space and tabs
//String sAfter = sBefore.replace(' ', '');//replace white space only
double i = 0;
try {
i = Double.parseDouble(sAfter);//parse to integer
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println(i);//2.03445
UPDATE:
Looking at your code snippet the problem might be that you read it directly as a float/int/double (thus entering a whitespace stops the nextFloat()) rather read the input as a String using nextLine(), delete the white spaces then attempt to convert it to the appropriate format.
This seems to work fine for me:
public static void main(String[] args) {
//bugChecking bc = new bugChecking();
float i = 0.0f;
String tmp = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (true) {
tmp = in.nextLine();//read line
tmp = tmp.replaceAll("\\s+", "");//get rid of spaces
if (tmp.isEmpty()) {//wrong input
System.err.println("Please enter a number greater than 0.");
} else {//correct input
try{//attempt to convert sring to float
i = new Float(tmp);
}catch(NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
System.out.println(i);
break;//got correct input halt loop
}
}
in.close();
}
EDIT:
as a side note please start all class names with a capital letter i.e bugChecking class should be BugChecking the same applies for test2 class it should be Test2
String objects have methods on them that allow you to do this kind of thing. The one you want in particular is String.replace. This pretty much does what you're trying to do for you.
String input = " 2.03 445 ";
input = input.replace(" ", ""); // "2.03445"
You could also use regular expressions to replace more than just spaces. For example, to get rid of everything that isn't a digit or a period:
String input = "123,232 . 03 445 ";
input = input.replaceAll("[^\\d.]", ""); // "123232.03445"
This will replace any non-digit, non-period character so that you're left with only those characters in the input. See the javadocs for Pattern to learn a bit about regular expressions, or search for one of the many tutorials available online.
Edit: One other remark, String.trim will remove all whitespace from the beginning and end of your string to turn " 2.0332" into "2.0332":
String input = " 2.0332 ";
input = input.trim(); // "2.0332"
Edit 2: With your update, I see the problem now. Scanner.nextFloat is what's breaking on the space. If you change your code to use Scanner.nextLine like so:
while (i <= 0) {
String input = in.nextLine();
input = input.replaceAll("[^\\d.]", "");
float i = Float.parseFloat(input);
if (i <= 0.0f) {
System.out.println("Please enter a number greater than 0.");
}
System.out.println(i);
}
That code will properly accept you entering things like "123,232 . 03 445". Use any of the solutions in place of my replaceAll and it will work.
Scanner.nextFloat will split your input automatically based on whitespace. Scanner can take a delimiter when you construct it (for example, new Scanner(System.in, ",./ ") will delimit on ,, ., /, and )" The default constructor, new Scanner(System.in), automatically delimits based on whitespace.
I guess you're using the first argument from you main method. If you main method looks somehow like this:
public static void main(String[] args){
System.out.println(deleteSpaces(args[0]);
}
Your problem is, that spaces separate the arguments that get handed to your main method. So running you class like this:
java MyNumberConverter 22.2 33
The first argument arg[0] is "22.2" and the second arg[1] "33"
But like other have suggested, String.replace is a better way of doing this anyway.

java System.out.println() strange behavior long string

Can somebody explain me why this code does not print the numbers?
String text = new String("SomeString");
for (int i=0; i<1500; i++) {
text = text.concat(i+"");
}
System.out.println(text);
Result
SomeString
If I lower the number of runs to 1000 it works, why?!
And also if I add not only a number but also a character, it works.
Ok New Update:
Thanks for the code examples. I tried them all but what I found out is, that the console
actually display the numbers but only in fontcolor white. But the first part of the String
SomeString is black.
I use jdk1.7.0_06 !
This is eclipse bug. Fixed width console fixes the output.
String.concat() accepts a String parameter.
If you add "a number and a character" you are adding a string because the + operator understands you are chaining String and numeric data.
Anyway code runs fine to me, numbers appended till 1499 as expected.
There are a couple things you could try. I'll give you an example of both.
First, in Java you can simply add strings together. Primitives such as int should be automatically converted:
String text = new String("SomeString");
for (int i = 0; i < 1500; i++) {
text += i;
}
System.out.println(text);
Second, if the first method still isn't working for you then you can try to explicitly convert your int to a String like so:
String text = new String("SomeString");
for (int i = 0; i < 1500; i++) {
text += Integer.toString(i);
}
System.out.println(text);
To do the same more efficiently
StringBuilder text = new StringBuilder("SomeString");
for (int i = 0; i < 1500; i++) {
text.append(i);
}
System.out.println(text);
Both examples work for me on Java 6 update 32 and Java 7 update 3.
Woah, this is weird. I got the same result. At first glance, it looks like a bug in the JVM, but I tried running the program from the command-line and it works fine. It must be a bug in the Eclipse console. I found that changing the console to have a fixed width solves the display issue.
I also found that if you replace i + "" with i + "," it displays fine. It seems there's something Eclipse console doesn't like about having a long continuous stretch of pure numbers.
String text = "SomeString";
for (int i = 0; i < 15000; i++) {
// text = text.concat(i + ""); // Doesn't display correctly
// text += i; // Doesn't display correctly
text = text.concat(i + ","); // Displays correctly
// text += i + ","; // Displays correctly
}
System.out.println(text);
This bug is somewhat worrying to me. Good find!
UPDATE: I tried just printing a long line of "xxxxxx" and found that up to 32000 characters are displayed correctly. When the line goes to 32001 it's not displayed. When I put "12345" + "xxxxxxxxx...", I was still able to display 32000 "x" characters which means the line length is longer than 32000, so it's nothing to do with total line length. It seems that it's to do with the length of parts of String objects.

How is this program coming along?

Instructions:
Write a program that will read a line of text that ends
with a period, which serves as a sentinel value. Display all the
letters that occur in the text, one per line and in alphabetical
order, along with the number of times each letter occurs in the text.
Use an array of base type int of length 26 so that the element at
index 0 contains the number of as. and index 1 contain number of bs etc.
package alphabetize;
import java.util.*;
public class Alphabetize
{
private static void number(String s)
{
int[] array = new int[26];
s = s.toUpperCase();
System.out.println(s);
for (int i = 0; i < s.length(); ++i)
{
if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
{
++array[s.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println("|" + (char) ('A' + i) + "|" + array[i] + "|");
}
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String aString = ".";
while (true)
{
System.out.println("Please enter sentence with a period to end");
aString = keyboard.nextLine();
if (".".equals(aString))
{
System.exit(0);
}
number(aString);
}
}
}
Still having problem with the period thing.. it does not seem to work the way i did it.
Considering this is a homework and instructions are very specific, you should read the text character by character instead of using built-in functions
If your text file was something like
abcabca.
The output should be something a appears three times, b appears two times etc etc.
So your algo should be something like
Read next character
If char is period goto 5
If char is space goto 1.
If char is between a <-> z. update the counter in arr[0..25] and goto 1
output arr[0..25] one per line
Was it mandated that this assignment is done in Java? The whole idea of a "sentinal character" rather than just using a line terminator is pretty bizarre.
Anyway, you can achieve the behaviour you want by setting the delimiter of Scanner:
keyboard.useDelimiter("\\.");
As for the looping, a big hint is this:
int[] counts;
counts[chars[0] - 'a'] = counts[chars[0] - 'a'] + 1;
or simply
counts[chars[0] - 'a']++;
I'll leave it up to you to include that in a loop.
Edit
If you are looking for character-at-a-time input, I would suggest you use an InputStreamReader instead of Scanner for your input. Here's a basic skeleton of what that looks like:
Reader reader = new InputStreamReader(System.in);
while (true) {
int nextInput = reader.read();
if (nextInput == -1) {
System.out.println("End of input reached without sentinal character");
break;
}
char nextChar = (char) nextInput;
//deal with next character
}
Still, read() will typically block until either the end of input is reached (CTRL-D or CTRL-Z from most consoles) or a new line is sent. Thus the sentinal character is of limited use since you still have to do something after typing ".".
You have to check whether period is there at the end or not. So the last character should be '.'.
Then take the length of string before last '.'.
For the counting part create an array like u are doing :
int [] name = new int[26]
where each index starting from 0, 25 corresponds to 'a' till 'z'.
Now you put the string characters in a loop and have to check what that character is like :
if its a 'a' : increase the value at index 0 by 1.
if its a 'd' : increase the value at index 3 by 1.
like wise.
later you display the whole array with a, z along with indexes from 0 till 25.
Suggestion: If its not required to use an array, and you can use any other data-structure you can implement the same in a HashMap very easily. by keeping 'a', 'z' as the keys and count as the corresponding values. and then retrieving and showing the values will also be easier.
You need an int array (e.g., int[] counts = new int[26];) After you read the input line, examine it character by character in a loop. If the character is a not period, then increment the appropriate element of the counts array. (If the character is a, then increment counts[0]; if it is b, increment counts[1]; etc. Hint: you can subtract a from the character to get the appropriate index.) When you find a period, exit the loop and print the results (probably using a second loop).

Categories

Resources