Why these backspace are not printing - java

I am trying to get factorial of given integer with the below code, but the final \b is not printing. Why?
import java.util.*;
class Example {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("INPUT AN INTEGER");
int num = input.nextInt();
System.out.print(num + "!=");
for(int i = num; i > 0; i = i - 1){
System.out.print(i + "*");
}
System.out.print("\b");
}
}

As indicated, the functionality of various output terminals varies wildly. There are full fledged VT100 terminals, Windows command line prompts, views within IDE's etc. So backspace is likely not supported by every one of them.
However, you should not generate text unless it is required. Do not backtrace or - in this case - backspace after the fact. That's an error prone process, and you use more memory resources by first creating the string in the first place. The latter is not a problem for a single *, but in general you try and avoid spurious memory use.
The following code should work:
for (int i = num; i > 0; i--){
if (i != num) {
print("*");
}
System.out.print(i);
}
Also notice the use of i-- instead of i = i - 1.
When you're ready to advance, you may want to have a look at String.format() and the StringBuilder class and create the full string before printing it out.
In principle you can of course use a substring to remove the final * character if you first create a string. Or you could remove it from the StringBuilder instance if you use that.
I would still prefer not appending it in the first place and use above code or a slight modification of it to build the entire string.

Related

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.

How can I put multiple parts of a string into a list?

So the goal is to look for patterns like "zip" and "zap" in the string, starting with 'z' and ending with 'p'. Then, for all such strings, delete the middle letter.
What I had in mind was that I use a for loop to check each letter of the string and once it reaches a 'z', it gets the indexOf('p') and puts that and everything in the middle into an ArrayList, while deleting itself from the original string so that indexOf('p') can be found.
How can I do that?
This is my code so far:
package Homework;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class ZipZap {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List < String > list = new ArrayList < String > ();
System.out.print("Write a sentence with no spaces:");
String sen = in .next();
int len = sen.length();
int p1 = sen.indexOf('p');
String word = null;
String idk = null;
for (int i = 0; i < len; i++) {
if (sen.charAt(i) == 'z') {
word = sen.substring(i, p1 + 1);
list.add(word);
idk = sen.replace(word, "");
i = 0;
}
}
}
}
use this , here i am using "\bz.p\b" pattern for finding any word that contains starting char with z and end with p anything can be in between
String s ="Write a sentence with no zip and zap spaces:";
s=s.replaceAll("\\bz.p\\b", "zp");
System.out.println(s);
output:
Write a sentence with no zp and zp spaces:
or it can be
s.replaceAll("z\\w+p", "zp");
here you can check you string
https://regex101.com/r/aKaNTJ/2
I think you’re saying that input zipzapityzoop, for example, should be changed to zpzpityzp with i, a and oo going into list. Please correct me if I misunderstood your intention.
You are on the way and seem to understand the basics. The issues I see are minor, but of course you want to fix them:
As #RicharsSchwartz mentions, to find all strings like zip, zap and zoop, you need to find p after every z you find. When you have found z at index i, you may use sen.indexOf('p', i + 1) to find a p after the z (the second argument causes the search to begin at that index).
Every time you have found a z, you are setting i back to 0, this starting over from the beginning of the string. No need to do that, and this way your program will never stop.
sen.substring(i, p1+1) takes out all of zip when I understood you only wanted i. You need to adjust the arguments to substring().
Your use of sen.replace(word, "") will replace all occurences of word. So once you fix your program to take out a from zap, zappa will become zpp (not zppa), and azap will be zp. There is no easy way to remove just one specific occurrence of a substring from a String. I think the solution is to use the StringBuilder class. It has a delete method that will remove the part between two specified indices, which is what you need.
Finally you are assigning the changed string to a different variable idk, but then you continue to search sen. This is like assigning zpzapityzoop, zipzpityzoop and zipzapityzp to idk in turn, but never zpzpityzp. However, if you use a StringBuilder as I just suggested, just use the same StringBuilder all the way through and you will be fine.

How do I check see a newline character with my scanner if I'm using a delimiter?

I'm trying to make an undirected graph with some of the nodes (not all, unlike my example) being connected to one another. So my input format will look like
3
1:2,3
2:1,3
3:1,2
Meaning there's three nodes in all, and 1 is connected to 2 and 3, 2 is connected to 1 and 3 and so on.
However, I cannot understand how to take the input in a meaningful way. Here's what I've got so far.
public Graph createGraph() {
Scanner scan = new Scanner(System.in).useDelimiter("[:|,|\\n]");
int graphSize = scan.nextInt();
System.out.println(graphSize);
for (int i = 0; i < graphSize; i++) {
while (!scan.hasNext("\\n")) {
System.out.println("Scanned: " + scan.nextInt());
}
}
return new Graph(graphSize);
}
Can my
while (!scan.hasNext("\\n"))
see the newline character when I'm using a delimiter on it?
In my opinion, you shouldn't be using those delimiters if they are meaningful tokens. In the second line for example, the first integer doesn't have the same meaning as the others, so the : is meaningful and should be scanned, even if only to be discarded later. , however doesn't change the meaning of the tokens that are separated by it, so it's safe to use as a delimiter : you can grab integers as long as they are delimited by ,, they still have the same meaning.
So in conclusion, I would use , as a delimiter and check manually for \nand : so I can adapt my code behaviour when I encounter them.
yup, scanner can definitely detect new line. infact you dont even have to explicitly specify it. just use
scan.hasNextLine()
which essentially keeps going as long as there are lines in your input
Edit
Why dont you read everything first and then use your for loop?
Alright I figured it out. It's not the prettiest code I've ever written, but it gets the job done.
public Graph createGraph() {
Scanner scan = new Scanner(System.in);
number = scan.nextLine();
graphSize = Integer.valueOf(number);
System.out.println(graphSize);
for (int i = 0; i < graphSize; i++) {
number = scan.nextLine();
Scanner reader = new Scanner(number).useDelimiter(",|:");
while (reader.hasNextByte()) {
System.out.println("Scanned: " + reader.nextInt());
}
}
return new Graph(graphSize);
}

Arrays - square-free word

This is what the program should do:
The word, zatabracabrac, is not square free, since it has subword, abrac twice start-
ing at position 4 of the word.
We are not allowed to use strings, breaks or other complex stuff. I get the square and square not part but am unable to find its place. I think I went wrong some place like I can't figure it out.
public static void main(String[] args) {
// part (a) of the main
Scanner keyboard = new Scanner(System.in);
System.out.println("***************************");
System.out.println(" Part (a)");
System.out.println("***************************");
do{
System.out.println("Enter a word and then press enter:");
String str=keyboard.next();
char[] word = str.toCharArray();
isSquareFree(word);
System.out.println("Do you want to test another word? Press y for yes, or another key for no");
}while(keyboard.next().charAt(0)=='y');
public static void isSquareFree(char[] word){
int z = 0;
for(int i=0; i<word.length; i++){
for(int j=0; j<word.length-1;j++){
if (word[j] == word[j+1]){
z = 1;
j = word.length;
}
else{
z = 2;
}
}
}
if (z == 1){
System.out.println();
System.out.println("Not Square Free");
}
else{
System.out.println();
System.out.println("Square Free");
}
}
}
Downvotes on the question: this is not where you solve your homework... we all went through having homeworks and solved them (well, most of us), and that's partly why we're capable of helping you.
You're checking whether the word contains two consecutive characters which are the same.
That's not what you want, try another solution.
Here's why it does what I said above:
The outer for loop doesn't have an effect on the inner one, since i is not used inside
Index j and j+1 in the same iteration as a character and the next one
Other notes:
j = word.length is the same as break here, try using that, it stops your loop like the end condition was satisfied; read more: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
For easier testing, you might want to use another main function containing only calls like isSquareFree("zatabracabrac".toCharArray());, even multiple ones to see multiple test results at once
This will greatly reduce the change-compile-run-check cycle's length.
You can use a debugger in an IDE (Eclipse or IntelliJ) to see what your program does.
Without debugging you can use println/print/printf calls to see how many iterations you have and what your values during those iterations.
Hints on solution:
As I see you're essentially looking for consecutive k-length subword duplicates
You phrased it right in the comment, the arbitrary length is giving it another level
At each position i try to look for a subword with length k which has a corresponding match starting at i + k (this helps the consecutive constraint)
k can be anything between a letter and half of the string (more than that is overkill since it cannot repeat twice)
I didn't code it, but it would be my first try
In your examples:
borborygmus
^=>
i
borborygmus
^=>
i+k
With k = 3 there is a match
zatabracabrac
^===>
i
zatabracabrac
^===>
i+k
With k = 5 there is a match

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.

Categories

Resources