Making a specific pattern in Java - java

How do I make this pattern using a input from the user?
input=3
(1st line)+
(2nd line)--
(third line)+++
I have tried using the for loops but just couldn't figure out how to get it to work.

First, we can judge the parity of a value by taking the remainder of 2
get the input value;
loop i = 1 & i <= input value:
when i is odd output char is "+"
when i is even output char is "-"
loop j = 0 & j < i
print i times output char
codeļ¼š
int inputVal = 3;
for (int i = 1; i <= inputVal; i++) {
String outputTag = i % 2 == 0 ? "-" : "+";
for (int j = 0; j < i; j++) {
System.out.print(outputTag);
}
System.out.println();
}

Scanner inp = new Scanner(System.in);
System.out.println("Enter Input");
int input = inp.nextInt();
for (int i = 0; i < input; i++) {
String symbol = i%2 == 0 ? '-' : '+';
for (int j = 0; j < i; j++) {
System.out.print(symbol);
}
System.out.print("line" + (i+1) + "\t");
}

Related

Reversing the order of displayed numbers in a nested loop

I've been doing some solo exercises to prepare for starting college next year and this one is stumping. The output is current
1
12
123
1234
and I want to get it to
1
21
321
4321
Here's the code I've been playing with for a while.
Scanner stdIn = new Scanner (System.in);
int n;
do
{
System.out.println("Please enter the value number: ");
n = stdIn.nextInt();
}
while ( n < 1 || n > 9);
for (int i = 1; i <= n; i++)
{
for (int k = i; k < n ; k++)
{
System.out.print(" ");
}
for (int j = 1; j <= i; j++)
{
System.out.print(j);
}
System.out.println();
}
stdIn.close();
One simple way is to make the second for loop start from i, and go down to 1:
for (int j = i; j >= 1; j--)
{
System.out.print(j);
}
Alternatively, print i - j + 1:
for (int j = 1; j <= i; j++)
{
System.out.print(i - j + 1);
}
Also, you should not close the Scanner, which is "connected to" System.in You didn't open System.in, so don't close it.
You can convert the numbers to String and print its reverse:
Scanner stdIn = new Scanner (System.in);
int n;
String str;
do
{
System.out.println("Please enter the value number: ");
n = stdIn.nextInt();
}
while ( n < 1 || n > 9);
for (int i = 1; i <= n; i++)
{
str = "";
for (int k = i; k < n ; k++)
{
System.out.print(" ");
}
for (int j = 1; j <= i; j++)
{
str = str + j;
}
System.out.println(new StringBuffer(str).reverse().toString());
}
stdIn.close();

String,which repeats ,but not starts from the beginning in Java (diamond pattern

This is the work that i done so far:I have to print diamond pattern which always starts with uppercase from string, which repeats,but not always starts from the beginning.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.next();
userInput = Character.toUpperCase(userInput.charAt(0)) + userInput.substring(1);
int i;
int j;
if (userInput.length() % 2 != 0) {
for(i = 1; i < userInput.length(); i += 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.println("");
}
for(i = userInput.length(); i > 0; i -= 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.print("\n");
}
} else {
for(i = 2; i < userInput.length(); i += 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.println("");
}
for(i = userInput.length(); i > 0; i -= 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.print("\n");
}
}
}
For example my input is "Peter".
So my output is:
P
Pet
Peter
Pet
P
but it must be:
P
Ete
Rpete
Rpe
T
I dont know what to change to make this work
Here's a shorter version of your code:
public static void main(String[] args) {
String userInput = "Peter";
int length = userInput.length();
int m, j, i, n = 0;
for (m = length % 2 > 0 ? 1 : 2; m < length * 2; m += 2) {
i = m < length ? m : length * 2 - m;
for (j = 0; j < length - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
char c = userInput.charAt(n++ % length);
c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
System.out.print(c);
}
System.out.println("");
}
}
You need some few changes:
Declare int n=0; after int j;
Always print userInput.charAt(n++ % userInput.length()) instead of charAt(j)
In order to get only the first character in line in uppercase:
char c = userInput.charAt(n++ % userInput.length());
c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
System.out.print(c);
Check the modulo operator.
With these changes, you'll get this output:
P
Ete
Rpete
Rpe
T
Given the fact that the input itself gets printed in a cylic manner, we can make use out of it. My proposal would be to concatenate the input string and print out the substrings which are determined by the structure of the diamond pattern.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.next();
String concatenated = userInput;
// build up the index array
int i, cumSum = 0;
ArrayList<Integer> helperIndex = new ArrayList<>();
for(i = 1; i < userInput.length(); i += 2) {
helperIndex.add(i);
cumSum += i;
}
for(i = userInput.length(); i > 0; i -= 2) {
helperIndex.add(i);
cumSum += i;
}
int numOfWordRepitition = cumSum / userInput.length() ;
for (i = 0; i < numOfWordRepitition; i++){
concatenated += userInput;
}
// print out diamond
String substr;
int prev = helperIndex.get(0);
int next = helperIndex.get(0);
substr = concatenated.substring(0 , helperIndex.get(0));
System.out.println(Character.toUpperCase(substr.charAt(0)) + substr.substring(1));
for(i = 1; i < userInput.length(); i++){
next += helperIndex.get(i);
substr = concatenated.substring(prev , next);
substr = Character.toUpperCase(substr.charAt(0)) + substr.substring(1);
System.out.println(substr);
prev = next;
}
}

initialize only some elements of array in java

So I want to skip the first and last elements of the array to initialize. What am I doing wrong?
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Columns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Here is my output:
Input Rows:
3
Input Columns:
3
Entered Values:
0 0 0
0 0 0
0 0 0
You need to change the if condition inside the loop like following:
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((i == 0 && j==0) || (i == m -1 && j == n -1)) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
In this line:
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
You are testing for the equality of values within your array. You should be comparing whether the indices you are looking at are the beginning or end of the array.
That is to say, you want to compare whether (in pseudo code):
i==0 and j==0, OR i==max index in its dimension and j==max index in its dimension
I have deliberately omitted the literal answer, because this looks a tiny bit like homework.
You compare the value of arr[i][j] with the value of arr[0][0]. You should instead compare i==0 && j==0 || i==m -1 && j==n -1
As your array was empty, and as you start the loop, arr[i][j] was equal to arr[0][0], skipping the first element. but for the next loop, arr[i][j] was still empty, and as you compare it to a non-initialised value, it's always true, skipping in each step
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Coloumns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i==0 && j==0 || i==m-1 && j==n-1) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
You don't need to check whether the array items are equal, you just want to check whether the row and column are equal to the last and first.

How to make an array inside a loop and then be able to call it after the loop in Java?

I wrote a code here to do the following:
Prompt the user for how many numbers are going to be entered. We called this value userRequest.
So, userRequest times we do the following:
read a String. This String will have the form: a mixture of digits and letters.
return the integers of the String and the letters separated.
but in the returning code, I scanned the string character by character, so it printed each input separately. But, my question is how can I print the numbers together as one integer and the letters together as on string. (I think it needs arrays, but I couldn't call an array when it inside a loop)
import java.util.*;
public class Program8{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int userRequest;
int returnNum;
System.out.print("How many numbers do you wish to enter? ");
while (!scan.hasNextInt()){
System.err.print("Please try again, with digits only: ");
scan.next();
}//while
userRequest = scan.nextInt();
int sortingNum = 1;
String str;
char ch;
str = scan.nextLine();
for (int i = 0; i < userRequest; i++){
System.out.print("* Please enter a string #" + sortingNum + ": ");
str = scan.nextLine();
System.out.println("- String #" + sortingNum++ + " = " + str);
for (int j = 0; j < str.length(); j++){
ch = str.charAt(j);
if ((ch + 0) >= 48 && (ch + 0) <= 57){
int digit = ((ch + 0) - 48);
System.out.println(digit);
}
}
System.out.println();
for (int k = 0; k < str.length(); k++){
if (str.toLowerCase().charAt(k) >= 'a' && str.toLowerCase().charAt(k) <= 'z')
System.out.println(str.charAt(k));
}
}//for
}//main
}//Program8
For the number:
Add the logic to multiply a variable by 10 and add the digits extracted.
For the string:
Add the logic to append the characters to a stringbuilder object.
Code:
int finalNumber = 0;
for (int j = 0; j < str.length(); j++){
ch = str.charAt(j);
if ((ch + 0) >= 48 && (ch + 0) <= 57){
int digit = ((ch + 0) - 48);
finalNumber = finalNumber*10 + digit;
//System.out.println(digit);
}
}
System.out.println(finalNumber);
System.out.println();
StringBuilder finalString = new StringBuilder();
for (int k = 0; k < str.length(); k++){
if (str.toLowerCase().charAt(k) >= 'a' && str.toLowerCase().charAt(k) <= 'z') {
//System.out.println(str.charAt(k));
finalString.append(str.charAt(k));
}
}
System.out.println(finalString.toString());

Getting each letter in a String only once

I'm writing a Java program for Horspool's algorithm, and am having a bit of trouble. I'm trying to create an array of chars that will hold each letter in a string, but I don't want duplicates of the letters. Right now this is my code:
public static void main(String[] args)
{
Scanner scanIn = new Scanner (System.in);
int count = 0;
int count2 = 0;
int inc = 0;
//The text to search for the phrase in
String t = "";
//The phrase/pattern to search for
String p = "";
System.out.println(" ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Harspool's Algorithm: ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" ");
System.out.println("Please enter the full text: ");
t = scanIn.nextLine();
System.out.println("Please enter the pattern to search for: ");
p = scanIn.nextLine();
char[] text = new char[t.length()];
char[] pattern = new char[p.length()];
char[] alphabet = new char[t.length()];
for (int i = 0; i < alphabet.length; i++)
{
alphabet[i] = ' ';
}
for (int i = 0; i < text.length; i++)
{
text[i] = t.charAt(i);
}
for (int i = 0; i < pattern.length; i++)
{
pattern[i] = p.charAt(i);
}
while (inc < text.length)
{
for (int j = 0; j < text.length; j++)
{
if (text[inc] != alphabet[j])
{
count++;
}
if (count == p.length() - 1 && count2 < text.length)
{
alphabet[count2] = text[inc];
count2++;
count = 0;
inc++;
}
}
}
for (int i = 0; i < alphabet.length; i++)
{
System.out.print(alphabet[i]);
}
}
I believe the problem is in the while loop, but I can't figure out what exactly is going wrong. Right now, it will print out the entire string passed in, when it should be printing each letter only once. Could someone please help?
Instead of counting the occurrences of each character, Use Set<Character>. A set contains unique elements and so you will not have duplicates that way.
You can also convert a Set to an array by doing mySet.toArray(new String[mySet.size()]); or just mySet.toArray(new String[0]);
Your code is not easy to read. You might consider using the following algorithm instead.
int ccount[256];
int ii;
for(ii=0;ii<256;ii++) ccount[ii]=0;
for (ii = 0; ii < text.length; ii++)
{
ccount[t.charAt(i)%256]++;
}
for (ii = 0; ii<256; ii++) {
if(ccount[ii]>0) System.out.printf("%c", ii);
}
EDIT - made sure ccount was initialized, and captured characters outside of range 0-255 with % operator.

Categories

Resources