Is it possible to increment a string or character in Java? - java

My output should look like:
1 star(*)
3 stars(***)
4 stars(****)
For example i have code:
char array[] = new char[3];
char x = '*';
For (int i= 0; i < array.length; i++)
{
array[i]='*'
x = x+2;
system.out.println(array[i]);
}

No it's not possible in char[] array, you should do it like,
String array[] = new String[3];
String x = "*";
for (int i= 0; i < array.length; i++)
{
array[i] = "";
array[i] = array[i] + x;
system.out.println(array[i]);
x = x + "*";
}
This will print the output as,
*
**
***

Your array is a char array, so each element contains a single char. Therefore your output will be :
*
*
*
To get the output you want, you'll need a String array (or no array at all - you can used a nested loop instead).
In addition, x = x+2; doesn't do what you think it does. It assigns a new character to x. If the initial value of x is '*', it will change it to the char whose numeric value is higher by two compared to the numeric value of '*'.

Just to provide an alternative to the already existing answers, it is also possible to just work with char. The trick then is to use System.out.print() rather than System.out.println(). An example:
int n = 3; //the number of lines you want to print
char x = '*';
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(x);
}
System.out.print("\n");
}
Note: this is just an alternative to the already proposed solutions

For that you need to change array to String type and concat * on it in each level.
Code
String array[] = new String[3];
char x = '*';
array[0]=""+x;
for (int i= 0; i < array.length; i++)
{
System.out.println(array[i]);
if(i!=array.length-1)
array[i+1]='*'+array[i];
}
And you also have so much compilation error in your code like For,Array,system.
Also check DEMO

Considering your out put it can be derived from following
String s="*";
StringBuffer sb =new StringBuffer();
for(int i=1;i<=4;i++)
{
System.out.println(sb.append(s));
}
Output will be
*
**
Tc

Related

Bring 2d array contents into 1d array Java

I am trying to recreate the Thue Morse sequence in Java console and need to bring the contents of a 1 dimensional array into a 2 dimensional one. I tried using 2 for loops, with one nested, but receive the Ljava.lang.String;#42d3bd8b as a result
int x = Integer.parseInt(args[0]);
String[][] array = new String [x][x];
String thue = "0";
String morse = "1";
//
for (int i = 1; i <= array.length; i++) {
String t = thue; // save away values
String m = morse;
thue += m;
morse += t;
}
String[] split = (thue.split("(?!^)"));
for (var y = 0; y<split.length; y++){
if (split[y] == "0"){
split[y] = "+";
}
else split[y] = "-";
}
int index = 0;
for (var i = 0; i < array.length; i++){
for (var j = 0; j < array[i].length;j++){
array[i][j] = (split[index]);
index++;
}
}
System.out.println(Arrays.toString(array));
}
}
There are 2 corrections to be made
1)in this code
if (split[y] == "0"){
split[y] = "+";
}
Strings cannot be compared as primitives. Replace equals operator with equals method as such
if (split[y].equals("0")){
split[y] = "+";
}
2)Arrays toString method can be used to convert only 1D arrays to string format.
You have to use the deepToString for your purpose
System.out.println(Arrays.deepToString(array));
I found out how to fix it, I converted array into a integer array and then later on when setting split[index] equal to the indicies of array, I just added and Intger.parseInt around the split[index]

I have to capitalize the first letter of a String in Java.(I cant use the method in string class to do so). but i keep getting out of bounds error

here is the code. I keep getting the error: String index out of range:5, I don't know what I'm doing wrong so any help will be appreciated. Also, I'm not allowed to use any Scanner class methods other than length.
import java.util.*;
public class capitalLetter
{
public static void main(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a non capitalized word");
String word = sc.next();
int length = word.length();
char ch[] = new char[length];
for(int i = 0;i<length-1;i++){
ch[length] = word.charAt(length);
}
ch[0]+=32;
for(int i = 0;i<length-1;i++){
System.out.print(ch[length]);
}
}
}
Firstly, within the for loop you need to use the loop variable i, rather than length. Also, i should go to the last element of the array.
This
for(int i = 0; i < length-1; i++){
ch[length] = word.charAt(length);
}
should be
for(int i = 0; i < length; i++){
ch[i] = word.charAt(i);
}
Secondly, you're adding 32 when you should be subtracting.
Putting this together you get:
String word = "hello";
int length = word.length();
char ch[] = new char[length];
for(int i = 0; i < length; i++) {
ch[i] = word.charAt(i);
}
ch[0] -= 32;
for(int i = 0; i < length; i++) {
System.out.print(ch[i]);
}
Output:
Hello
In both of your loops, you are indexing by length instead of by i.
e.g this line
ch[length] = word.charAt(length);
should be like this
ch[i] = word.charAt(i);

Trying to get a loop to work through alternate arrays

I'm trying to print out a string by alternating its letter cases. I want YourString to come out as YoUrStRiNg. I've tried three things but I can't get the loop to work the way I need it to. Here's what I have so far:
//one attempt
String s = "yourString";
String x = "";
for (int i = 0; i < s.length(); i += 2) {
for (int j = 1; j < s.length(); j += 2) {
x += Character.toUpperCase(s.charAt(i));
x += Character.toLowerCase(s.charAt(j));
}
}
System.out.println(x);
//the desired result but not the ideal solution
String[] sArray = {"Your", "String"};
String f = "";
for (String n : sArray) {
f += n;
}
char[] c = f.toUpperCase().toCharArray();
char[] d = f.toLowerCase().toCharArray();
System.out.print(c[0]);
System.out.print(d[1]);
System.out.print(c[2]);
System.out.print(d[3]);
System.out.print(c[4]);
System.out.print(d[5]);
System.out.print(c[6]);
System.out.print(d[7]);
System.out.print(c[8]);
System.out.print(d[9]);
System.out.println();
//third attempt with loop but the first loop keeps starting from zero
String t = "";
for (int i = 0; i < c.length; i += 2) {
for (int j = 1; j < d.length; j += 2) {
t += Character.toUpperCase(c[i]);
t += Character.toLowerCase(d[j]);
}
System.out.print(t);
}
What am I doing wrong?
Actually, there's no need to iterate more than once through the elements of the String. As you need to change the case of the character alternatively, you can just count the position of your iteration, by using the operator %. So, for example, given c as the current String character, the operation would be like this:
System.out.print(i % 2 == 0, (char)Character.toUpperCase(c) : (char)Character.toLowerCase(c));
However, you can actually take advantages from Java Stream and lambda expression, so to realize a very elegant solution for that.
I am going to show you my proposal solution. The only issue is that you cannot actually have a proper cycle variable, as the variable you access inside the lamba expression must be final or effective final, so I used a sort of trick for it.
That is just to give you an idea, you can actually personalize, make it reusable, and improve it as you wish:
public class MyStringTest {
public static void main(String args[]) {
String s = "yourString";
initializeCycleVariable();
s.chars().forEach(c ->
{System.out.print( MyStringTest.getAndIncrement() %2 == 0 ?
(char)Character.toUpperCase(c) :
(char)Character.toLowerCase(c));
});
}
private static int i = 0;
public initializeCycleVariable() { i = 0; }
public static int getAndIncrement() { return i++; }
}
And here is the output:
YoUrStRiNg
You should iterate over the string char by char. You could do upper case for the even indexes, and lower case for the odd ones. Sorry for not providing more detail, but it is clear that this is an assignment.
Try this one out,
String s = "yourString", x = "";
for(int i = 0; i < str.length(); i++){
if(i % 2 == 0)
x += Character.toUpperCase(s.charAt(i));
else
x += Character.toLowerCase(s.charAt(i));
}
System.out.println(x);

How to compare two arrays of different sizes?

So my task is to read a file line by line and store the integers into an array. Then to add the integers in spots 1-5, 2-6, 3-7 etc. and store those into a new array.
In array 1 there is 4 more values than array 2. I need to compare these Arrays and see if array1 is 0.999 bigger than array2.
If it is indeed larger, I need to print out the LOCATION of the number in the array 1.
Right now my problem is my code is outputting that every number is larger than the corresponding number in array 2.
Code:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Asgn7
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner file = new Scanner(new File("asgn7data.txt"));
double[] array = new double[file.nextInt()];
double[] newArray = new double[array.length - 4];
double tempVal = 0;
int j = 0;
int count = 0;
while(file.hasNext())
{
for(int i = 0; i < array.length ; i++)
{
array[i] = file.nextInt();
}
for(j = 0; j < array.length - 4; j++)
{
for(int k = 0; k < 5; k++)
{
newArray[j] += array[j+k] / 5;
}
}
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
}
}
The values which should be compared are from 3-13.
Judging by the picture, you are not placing the values in the correct index in the second array, or you are not matching the correct ones.
If you want it to look exactly like in the picture, the second array should be declared:
double[] newArray = new double[array.length - 2];
And the loop to fill it should be changed to:
for(j = 2; j < array.length - 2; j++)
{
for(int k = -2; k <= 2; k++)
{
newArray[j] += array[j+k] / 5;
}
}
This will put the averages in the third, fourth, fifth... elements in newArray. And now you can compare them directly:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i] + 0.999))
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
If you want to save the two unused spaces, as you originally did, rather than responding exactly to the picture, then you should calculate the values as you originally did. But remember to compare each element to the one two places before it and stop 2 places before the end.
Instead of
for(int i = 2; i < array.length; i++)
use
for(int i = 2; i < array.length - 2; i++)
To print the location, your construct with the count and tempVal is unnecessary. You just need to print i+1. Also note that you have a ; after your if. This means it's an empty if, and the block after it is always performed. Never have a ; after an if, for, while etc.
Not clear with what you are asking for in your question but without questioning what's the logic, by just looking at your code:
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
if you relocate the system.out line as follows, I think you will get what you expect as follows:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
System.out.println(tempVal);
// count++;
// tempVal = count;
}
}
}
PS: Please note that I have also changed the boundary for the loop to stop iteration on 13th member of the array, instead of 15.
Are you sure you're parsing the numbers correctly?
See Java: Reading integers from a file into an array
Why don't you print them out after parsing for verification?
btw, this will overflow the index of the 2nd array (since it is created using new double[array.length - 4]):
for(int i = 2; i < array.length; i++)
so does your code run?

duplicate characters in a loop

I need to write a small program that takes in a string like Hello World and prints out HHHEEELLLOOO WWWOOORRRLLLDDD, but instead of just hello world it would take in any string using the scanner function and produce the same result. I am new to java and cannot figure out how to create this program at all.
They key to learning how to program is to break up the problem into smaller pieces.
Write a program, using Scanner, to echo back the input and exit.
Modify that program so that you loop over the input and print each character.
Modify that program to print each character twice.
Modify that program to print each character n number of times.
I would do it like this at the first thought, but there may be an easier solution saving all the concatenations.
String produceString(String source, int numberPerLetter) {
String result = "";
for (int i = 0; i < source.length(); i++) {
char c = source.charAt(i);
for (int j = 0; j < numberPerLetter; j++) {
result += c;
}
}
return result;
}
Get the string from whichever source you want, e.g. scanner. Then iterate over each character in the string and print it as many times as you want.
int charRepeats = 3;
String input = "Whatever"; // Get from whichever source you want.
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
for (int j = 0; j < charRepeats; j++) {
System.out.print(c);
}
}
int No_of_Repeats = 2;
Scanner sc = new Scanner(System.in);
String user_input=sc.next();
for (int i = 0; i < user_input.length(); i++) {
char c = input.charAt(i);
for (int j = 0; j < No_of_Repeats; j++) {
result+=c;
}
}
return result;

Categories