I have attempted to complete the following exercise however the output isn't as expected.
You should print a number of pluses equal to the number entered by the user, followed by a list of numbers, so that in total exactly 20 characters are printed. The numbers printed should be the last digit of the current position in the list. Example: +++++678901234567890 if the number entered by the user was 5.
Here's my code:
package interact;
import java.util.Scanner;
public class Interact {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
{int value,k
for (int i=0; i<num1; i++) {
System.out.print("+");}
for (int j=0; j<20-num1; j++) {
if (num1>9) {k=num1-10;}
else k=num1+1;
System.out.print(k);
}
}
The output if 6 is entered is ++++++77777777777777. The numbers aren't incrementing - why not?
You aren't incrementing k or num1, so k becomes whatever number the user enters + 1, and keeps printing that out. You need to update k. First set k=num1. Then change your loop to:
if (k>9) {k=0;}
else k++;
System.out.print(k);
Since, your num1 remains same throughout the below loop.
for (int j=0; j<20-num1; j++) {
if (num1>9) {k=num1-10;}
else k=num1+1;
System.out.print(k);
}
But if you do like this it'll work
k=num1+1;
for (int j=0; j<20-num1; j++) {
if (k>9) {k=0;}
System.out.print(k);
k++;
}
This should fix it for you :)
i can answer any questions you got on the modification :)
good luck :)
int value, k;
for (int i = 0; i < num1; i++) {
System.out.print("+");
}
k=num1;
for (int j = 0; j < 20 - num1; j++) {
if (k >= 9) {
k = 0;
}
else
k++;
System.out.print(k);
}
Related
I need to print a square pattern where the number increases as per the row, for example consider variable 'i' which represents row value, if you initialize i=1 and increase the value till 'n' which is user input using while loop, the first row will print 1, second row will print 2 and so on till it reaches the value 'n'. Additionally I created variable for column and named it 'j' whose value also increases till it reaches n.
The output that I'm getting though is:
enter image description here
The code that I have written is: (java)
enter image description here
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int i =1;
while(i<=n){
int j = 1;
while(j<=n){
System.out.println(i);
j=j+1;
}
System.out.println();
i=i+1;
}
Why is the output for the above code:
enter image description here instead of
1111
2222
3333
4444
Please help me out.
Problem
The doc states the following and you know it
Prints an integer and then terminates the line
Fix
Use print instead
while (i <= n) {
int j = 1;
while (j <= n) {
System.out.print(i);
++j;
}
System.out.println();
++i;
}
Improvements
Could be a little bit nicer with for loops
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
System.out.print(i);
}
System.out.println();
}
Using String.repeat
for (int i = 1; i <= n; ++i) {
System.out.println(Integer.toString(i).repeat(n));
}
I'm writing a java code currently for class and I'm trying to figure out how to implement a run length encoding on a user input. The main problem I'm having it with comparing the first letter with the next and that letter with the next and so on to see if they're the same letter. Currently I have:
System.out.print("Enter a string: ");
String s1 = reader.nextLine();
int sum = 0;
char ast = '*';
//System.out.println("Run length encoded version of string: ");
for (int counter = 0; s1.charAt(counter) <= s1.length()-1; counter++) {
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
if (sum >= 4) {
System.out.print(ast + s1.charAt(counter) + sum);
}
else {
System.out.print(s1.charAt(counter));
}
}
I know where the big problem comes from in this and why it doesn't work but, namely from the
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
segment as it just goes infinitely. Is there a proper way to do this? The professor mentioned it can be done without loops and while I can see it being possible I can't see it being short. Any help would be appreciated, thanks!
String str="ayyusaab";
char[] ch=str.toCharArray();
for(int i=0;i<ch.length-1;i++){
for(int j=i+1;j<ch.length-1;j++){
if(ch[i]==ch[j]) {
System.out.println(ch[i]+" at Index "+i +"with j at "+j);
}
}
}
I'm completely new to coding and my teacher is terrible at explaining things. I have no idea what's going on in the class, and I really need help with this!
I've made lots of pyramid patterns before, but this is one I can't figure out.
I know how to get user input too, but I just need help understanding why this won't work. He briefly explained how to code this problem to us, but it doesn't work no matter how many times I change and try it.
I have to create a pyramid using the number of lines the user inputs. So if the user entered 5, this is what it should look like:
*
**
***
****
*****
So the number of spaces on the first line is four, the second one has three spaces, and so on until you get to zero.
This is the code (which gives a completely inaccurate output):
System.out.print("\f");
System.out.println("Enter a valid number between 1 and 20.");
int num = 0;
int counter = 1;
num = keyNum.nextInt();
for (int i = 1; i == num; i++)
{
for (int j = 1; j == (num -= counter); j++)
{
System.out.print(" ");
}
for (int k = 1; k == counter; k++)
{
System.out.print("*");
}
System.out.println("");
counter++;
}
Please help! I feel so stupid.
I doubt your teacher will accept this. But it is just a one liner for fun
int num = 20;
IntStream.range(0, num).forEach(i -> System.out.println(String.format("%" + num + "s", new String(new char[i+1]).replace("\0", "x"))));
It's mostly right, but you are starting the loops from 1, but they really should be starting from 0, and the condition in the for loops shouldn't have == which just makes it run once.
for (int i = 0; i < num; i++) {
for (int j = 0; j <= (num - counter); j++) {
System.out.print(" ");
}
for (int k = 0; k < counter; k++) {
System.out.print("*");
}
System.out.println("");
counter++;
}
it's pretty close mostly the for loop is wrong.
for(initialization;condition;increment)
the for loop only executes when the condition is true. In your case the conditions don't really make sense. Try changing it. also your counter and i are the same thing :)
Interesting coding exercise. You got it almost right anyway as others pointed out.
There are hundred ways to solve the problem.
Here is just a variation that saves a loop...
int lines=5;
for (int i=0; i<lines; i++) {
for (int k=0; k<lines; k++) {
System.out.print( (k < lines - i - 1) ? " " : "*");
}
System.out.println();
}
Another solution using a single (explicit) loop:
for (int i = 1; i <= num; i++) {
int expectedSpaces = num - i;
String spaces = repeat(" ", expectedSpaces);
String asterisks = repeat("*", i);
System.out.println(spaces + asterisks);
}
}
private static final String repeat(String toBeRepeated, int length) {
return new String(new char[length]).replace("\0", toBeRepeated);
}
As mentioned elsewhere, loop variables such as i usually start at 0 since such variables can be used as an array/List index. However, in this case there is no related array or List so sarting at 1 simplifies the logic.
I worked on something similar, this is what I did, you could give it a try. It takes a user input and displays spaces and "#"...
int size = n;
for (int i = 0; i <= size-1; i++){
for(int j = size -1; j > i; j-){
System.out.print(" ");
}
for(int j = 0; j <= i; j++){
System.out.print("#");
}
System.out.println();
}
The output would be:
#
##
###
####
#####
######
So I have most of my code written, but there's one part of the assignment that I don't understand.
Write a program that will accept a number (n) from the user to represent the size of a board (nxn). If the user does not enter a number greater than 1, prompt the user over and over until he/she gives valid input.
Once valid input is obtained, print a board with every other column filled with 1s along with the last row filled with 1s. Zeros everywhere else. Your board will have an equal number of rows and columns based on the users input.
I have it to do the pattern with the 0's and 1's but I don't understand how I can get the last row to have all 1's. Here is my code posted below
import java.util.Scanner;
public class question1 {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Please input a value for the board greater than 1.");
n= input.nextInt();
while(n<1)
{
System.out.println("Error, please enter a value greater than 1");
n=input.nextInt();
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(j%2==0)
{
System.out.print(0);
}
else
{
System.out.print(1);
}
if(i==n)
{
System.out.print(1);
}
}
System.out.println(' ');
}
}
}
Change your loops to:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == n - 1) {
System.out.print(1);
} else {
System.out.print(j % 2);
}
}
System.out.println();
}
if(i==n)
{
System.out.print(1);
}
you should just change to (i == n-1)
So the task is to make the system output a triangle with spaces that increment in between x's like this(dashes added in place of space for readability):
xx
x-x
x--x
x---x
x----x
x-----x
x------x
x-------x
So, I've done this before and it seems easy enough, but the issue I'm having is getting the initial amount of spaces correct. I would like an example of how to do this and why it works as plainly stated as possible, thank you. Here's the code I have so far, along with the output:
Scanner in = new Scanner(System.in);
System.out.println("How many columns");
col = in.nextInt();
for (int i = 0; i < col; i++)
{
System.out.print("#");
for(int j = 0; j < (i+ 1); j++)
{
System.out.print(" ");
}
System.out.print("#");
System.out.println();
}
Output(when cols = 4):
x-x
x--x
x---x
x----x
All help is truly appreciated :)
public static void main(String[]args){
System.out.println("How many columns?");
int columns = new Scanner(System.in).nextInt();
for(int i=0; i<=columns; i++){
String toPrint = "x";
for(int cols=0; cols<i; cols++){
toPrint+=" ";
}
System.out.println(toPrint+"x");
}
}
change condition for j like below. also you have declared variable as col and used it like cols. so make corrections first.
Scanner in = new Scanner;
System.out.println("How many columns");
col = in.nextInt();
for (int i = 0; i < col; i++)
{
System.out.print("#");
for(int j = 0; j < i; j++)
{
System.out.print(" ");
}
System.out.print("#");
System.out.println();
}
I think The problem is with the r value set initially. There is no need of new variable r to be set.
If i is less than j, the loop doesn't get executed first time, and the loop executes 1 step more than each previous iteration of outer for loop