JAVA display in sets of 13 - java

I am sure this is a pretty easy question, but I am pretty rusty on my programming. I need to write code that will show all numbers between 14859 - 26551 in sets of 13.
So far I just have the normal for loop to show all the numbers, no sure how to get sets of 13.
for(i=14859; i < 26551; i++){
System.out.println(i);
}

Assuming you want to display your numbers as Jukka said in comments:
for(i=14859; i < 26551; i++){
if((i-14858)%13==0)
System.out.println(); // or anything delimiting your sets
System.out.println(i);
}
Or if you want to display only one number every 13:
for(i=14859; i < 26551; i+=13){
System.out.println(i);
}
You can't just type i+13 as you said you tried in comments: 3rd argument in a for loop is an assignment, so you have to assign something to a variable.

for(int i=14859; i < 26551; i++)
System.out.print(((i % 13 != 0) ? ", " + i : "\n"));

Related

How to print a specific number of values per line using Arrays.toString?

I print my array like this:
public void something () {
String out = (java.util.Arrays.toString(array)+(...));
showMessageDialog(null, out);
Main calls on another method in a class containing this method.
I want to have a line break for every 8 values of my array. I know I could do it like this if I printed every value in a for loop:
if (printed == 8) {
System.out.print("\n");
printed = 0;
But how to do so when using Arrays.toString()?
Thanks for any help!
As stated Arrays.toString wont be the right choice for you, but you can create the string using Java streams in more or less compact manner.
String result = java.util.stream.IntStream
.range(0, array.length)
.mapToObj( i -> array[i] + ( ( (i + 1) %8 ) == 0 ? "\n":", " ) )
.collect( Collectors.joining("") );
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + (i % 7 == 0 && i > 0 ? "\n" : ""));
}
You could use java.lang.Instrumentation to change the method's behavior at runtime via a debugging agent. See for example: https://github.com/turn/RedefineClassAgent
It is possible, but not worth it.
You can wrie a class extending Array. Then you need to override toString() method and implement it as you wish. But to use your implementation of toString(), all arrays need to be objects of your new class. Then every System.out.println() will use your implementation.
It is possible, but totally not worth it. It is a great waste of your and CPU time.

Is this Python code equivalent of Java code?

I'm fairly new to Python so please bear with me.
This is the Java code:
public static int countDeafRats(final String town) {
String t = town.replaceAll(" ","");
int count = 0;
for (int i = 0 ; i < t.length() ; i+=2)
if (t.charAt(i) == 'O') count++;
return count;
}
This is my attempt to translate it to Python:
def count_deaf_rats(town):
count = 0
increment = 0
newTown = town.replace(" ", "")
while increment <= len(newTown):
if newTown[increment]=='O':
count +=1
increment +=2
return count
I didn't use for loop in Python since I don't how to increment by 2, so as the title says, would this be an acceptable translation?
Edit, sample input: ~O~O~O~OP~O~OO~
It appears that you are trying to find the number of zeroes in the string that occur at indices incremented by 2. You can use regex and list comprehensions in Python:
import re
new_town = re.sub("\s+", '', town)
count = sum(i == "0" for i in new_town[::2])
I don't know too much Java, but I believe this is a more direct translation of your code into python:
def countDeafRats(town):
count = 0
new_town = town.replace(' ','')
#format for range: start, end (exclusive), increment
for i in range(0, len(new_town), 2):
if new_town[i] == '0':
count += 1
return count
I agree with #Ajax1234 's answer, but I thought you might like an example that looks closer to your code, with the use of a for loop that demonstrates use of an increment of 2. Hope this helps!
Okay I will recommend that you must follow the answer provided by #Ajax1234 but since you mentioned that you are fairly new(probably not familiar much about regex) to python so I would suggest for the current instance you should stick to your code which you are trying to convert to. It is fairly correct just you need to make some amendments to your code(although very small related to indentation). Your amended code would look something like:
def count_deaf_rats(town):
count = 0
increment = 0
newTown = town.replace(" ", "")
while increment <= len(newTown):
if newTown[increment]=='O':
count +=1
increment +=2
return count
#print count_deaf_rats("~O~O~O~OP~O~OO~")
This yields the same result as your corresponding java code. Also since while loops are not considered much handy(but at some instances much useful also) in python therefore I will insist to use for loop as:
#Same as above
for increment in range(0,len(newTown),2):
if newTown[increment] == 'O':
count +=1
return count
Read more about range function here

Displaying multiple lines from while loop in one output box

My assignment asks to print all values from 1-10 using while loops in one output dialog box, with each number appearing on a separate line. So far I have:
int i=1;
while (i <= 10)
{
System.out.println(i);
i++;
}
and it displays 1-10 on separate lines but that's in the command prompt window. I need it to be displayed on one output box. How would I do that?
Forgot to mention, I know how to display the output in a dialog box, however it displays it one by one in separate boxes rather than in just one. How would I make it display in only one and not 10 different boxes?
What you are looking for can be found in the Java Docs. The classes, as well as how to use them can be found here:
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
Be sure to import this:
import javax.swing.JOptionPane
When you're just printing to the console, all you have to do is change System.out.println to System.out.print:
int i = 1;
while (i <= 10)
{
System.out.print(i);
i++;
}
An alternative way to do it is this:
String s = "";
int i = 1;
while (i <= 10) {
s += i;
i++;
}
System.out.println(s);

Why is printing "B" dramatically slower than printing "#"?

I generated two matrices of 1000 x 1000:
First Matrix: O and #.
Second Matrix: O and B.
Using the following code, the first matrix took 8.52 seconds to complete:
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("#");
}
}
System.out.println("");
}
With this code, the second matrix took 259.152 seconds to complete:
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B"); //only line changed
}
}
System.out.println("");
}
What is the reason behind the dramatically different run times?
As suggested in the comments, printing only System.out.print("#"); takes 7.8871 seconds, whereas System.out.print("B"); gives still printing....
As others who pointed out that it works for them normally, I tried Ideone.com for instance, and both pieces of code execute at the same speed.
Test Conditions:
I ran this test from Netbeans 7.2, with the output into its console
I used System.nanoTime() for measurements
Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B as a word character but # as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a # almost immediately and happily breaks there; whereas with the B, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).
But that's pure speculation.
I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8;
I used System.nanoTime() for measurements.
Eclipse:
I got the same time on both cases - around 1.564 seconds.
Netbeans:
Using "#": 1.536 seconds
Using "B": 44.164 seconds
So, it looks like Netbeans has bad performance on print to console.
After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println command), demonstrated by this code:
for (int i = 0; i < 1000; i++) {
long t1 = System.nanoTime();
System.out.print("BBB......BBB"); \\<-contain 1000 "B"
long t2 = System.nanoTime();
System.out.println(t2-t1);
System.out.println("");
}
The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.
And so on..
Summary:
Eclipse works perfectly with "B"
Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).
Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.
First Matrix: O and # = 6.03 seconds
Second Matrix: O and B = 50.97 seconds
Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B");
}
if(j%100==0){ //Adding a line break in second loop
System.out.println();
}
}
System.out.println("");
}
Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

Restart current iteration in 'for' loop java

I have a for loop that asks the user to input a number and then does something with it 10 times
I want a check built in that, if the user enters a non accepted input, the loop should restart its current iteration
For example if the user enters something wrong in round 3, round 3 should be restarted.
How do i do that? is there something like a REDO statement in java?
something like this ?
for(int i=0; i<10; i++){
if(input wrong){
i=i-1;
}
}
You have a couple of choices here.
Continue
The continue statement in Java tells a loop to go back to its starting point. If you're using a for loop, however, this will continue on to the next iteration which is probably not what you want, so this works better with a while loop implementation:
int successfulTries = 0;
while(successfulTries < 10)
{
String s = getUserInput();
if(isInvalid(s))
continue;
successfulTries++;
}
Decrement
This approach seems ugly to me, but if you want to accomplish your task using a for loop, you can instead just decrement the counter in your for loop (essentially, 'redo') when you detect bad input.
for(int i = 0; i < 10; i++)
{
String s = getUserInput();
if(isInvalid(s))
{
i--;
continue;
}
}
I recommend you use a while loop.
Prefer avoiding to reassign the i variable, this may lead to confusion.
for(int i=0; i<10; i++){
String command = null;
do{
command = takeCommandFromInput();
} while(isNotValid(command));
process(command);
}

Categories

Resources