I am trying to write a program that asks the user for a letter (R,G,B) and then after five output the result. There cannot be 2 letters in a row. I get indexoutofbounds when I enter the third letter and the double letter check does not work.
package absolutejava;
import java.util.Scanner;
import java.util.*;
public class RGB {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int count = 0;
boolean isColor = false;
String finalString = "";
int i = 0;
int j = 1;
String temp = "";
for (count = 0; count < 5;) {
System.out.println("Enter a color. Use R for red, G for green, and B for blue.");
temp = kb.nextLine();
if ((temp.equals("R") || temp.equals("G") || temp.equals("B"))) {
isColor = true;
temp += temp;
} else {
isColor = false;
System.out.println("Invald Color, please choose again");
}
if (isColor == true && j < 6 && i < 5) {
count++;
if (temp.length() > 2 && temp.length() <= 5 && finalString.substring(i, j).equals(temp.substring(i - 1, j - 1))) {
System.out.println("Two colors cannot be next to each other ");
isColor = false;
count--;
} else if (temp.length() == 5) {
finalString = finalString + temp.substring(i);
//debugging line
System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length());
i++;
j++;
} else {
finalString = finalString + temp.substring(i, j);
//debugging line
System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length());
i++;
j++;
}
}
}
System.out.println(finalString);
}
}
The following line is definitely wrong:
temp += temp;
You're replacing temp with the current input every iteration, so this will have no effect. Even if that wasn't the case, you'd just be adding the same string to itself - e.g. "A" would become "AA."
I assume you meant
finalString += temp;
or something to that effect.
In general, it seems like you're mixing up temp and final in a few places.
One more thing: don't explicitly compare to true and false, it's unnecessary and is generally considered poor style.
Related
I am trying to write a program that allows generate random numbers inside a infinite loop. If the user press 'c' it will get out of loop. But the loop only starts when I press c, it should start before and it should stop when I press 'c'.
import java.util.Random;
import java.util.Scanner;
public class main{
public static void main (String[] args) {
Random rand = new Random();
int[] randNumber = new int[100];
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0);
do {
for (int i = 0; i <= 99; i++) {
randNumber[i] = rand.nextInt(100);
}
for (int i = 0; i < 99; i++) {
if (randNumber[i] < randNumber[i + 1]) {
System.out.println("Number " + randNumber[i] + " smaller than " + randNumber[i + 1]);
} else if (randNumber[i] > randNumber[i + 1]) {
System.out.println("Number " + randNumber[i] + " greater than " + randNumber[i + 1]);
} else if (randNumber[i] == randNumber[i + 1]) {
System.out.println("Number " + randNumber[i] + " equal to " + randNumber[i + 1]);
} else {
System.out.println("Wrong!");
}
}
} while (c == 'c');
}
}
Also I would like to how can I do this program only using while loop instead of do-while loop. When I was doing with only while I started with while(1) then break the loop with if statements from input, but that didn't work neither. Inside still there is two for loops.
Many thanks
Regarding first query move the lines of codes where you are taking input inside the do-while loop, in this way after each iteration it will ask for a input and if you enter 'c', it will continue else it will break free.
Regarding second query, if you use while(1) and check for user input for 'c' using if statements and breaking out if user inputs 'c', it should work.
You need to ask for user input inside of your loop; otherwise, c never changes.
Random rand = new Random();
int[] randNumber = new int[100];
Scanner scanner = new Scanner(System.in);
// Just set it to 'c' as default so it enters the loop at least once. IMO this is better than an infinite loop with breakout or having another default value for c and checking it, or using a do while loop
char c = 'c';
while (c == 'c') {
for (int i = 0; i <= 99; i++) {
randNumber[i] = rand.nextInt(100);
}
for (int i = 0; i < 99; i++) {
if (randNumber[i] < randNumber[i + 1]) {
System.out.println("Number " + randNumber[i] + " smaller than " + randNumber[i + 1]);
} else if (randNumber[i] > randNumber[i + 1]) {
System.out.println("Number " + randNumber[i] + " greater than " + randNumber[i + 1]);
} else if (randNumber[i] == randNumber[i + 1]) {
System.out.println("Number " + randNumber[i] + " equal to " + randNumber[i + 1]);
} else {
System.out.println("Wrong!");
}
}
// Ask for the next input
char c = scanner.next().charAt(0);
}
Hi I want to put my prints in a for-loop. how to do it? So something like
if index = 0,1,2 print.
if index = 2,3,4 print.
if index = 4,5,6 print.
Code:
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.println("\n\nThis starts to look like calculations:");
System.out.print("\n" + objectList.get(0));
System.out.print(" "+ objectList.get(1));
System.out.print(" " + objectList.get(2) + " =");
System.out.print("\n\n" + objectList.get(2));
System.out.print(" " + objectList.get(3));
System.out.print(" " + objectList.get(4)+ " =");
System.out.print("\n\n" + objectList.get(4));
System.out.print(" " + objectList.get(5));
System.out.print(" " + objectList.get(6) + " =");
output:
This starts to look like calculations:
1 + 3432.123 =
3432.123 * 4535 =
4535 - 24.4 =
private String buildOperation(int pos){
String output;
if(pos == 0) {
output = "+";
}else if(pos == 1){
output = "*";
}else {
output = "-";
}
return output;
}
List<Object> objectList = new ArrayList(res);
for(int i = 0; i < objectList.size()-1; i++){
System.out.println(objectList.get(i) + buildOperation(i) + objectList.get(i+1) + "=");
}
Additionaly I'll use a HashMap with the operations to avoid all if/else conditions
Map<Integer,String> operations = new HashMap{}
operations.put(0,"+");
operations.put(1,"*");
operations.put(2,"-");
System.out.println(objectList.get(i) + operations.get(i) + objectList.get(i+1) + "=");
}
Final solution now the String size does not matter anymore.
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.print("\n\nThis starts to look like calculations:");
int maxi= objectList.size();
maxi = maxi -2;
System.out.println("\n\nmaxi = " + maxi);
for (int i = 0; i < maxi; i+=2) {
System.out.println("");
System.out.println(i);
System.out.print("\n\n" + objectList.get(i));
System.out.print(" " + objectList.get(i + 1));
System.out.print(" " + objectList.get(i + 2)+ " =");
I want to count the occurrence of every number that appears in the array. I've seen other answers, but I do not understand why my method does not work. I have an Array with random numbers:
int[] fält = new int[20]
This is what I did:
public static String statistik(int[] fält) {
String poäng[] = new String[20];
String output = "";
//Clear out the array:
for (int i = 0; i < poäng.length; i++) {
poäng[i] = "";
}
//Add a star for each time a number appears
for (int i = 0; i < fält.length; i++) {
for (int t = 0; t < fält.length; t++) {
if (fält[t] == i) {
poäng[i] += "*";
}
}
}
//Print it out
for (int i = 0; i < fält.length; i++) {
output += (i + 1) + ": " + poäng[i] + "\n";
}
JOptionPane.showMessageDialog(null, output);
return "";
}
Not all numbers get a star and it all ends up weird. Why?
You are checking if (fält[t] == i) please change it to if (fält[t] == fält[i])
This line :
output += (i + 1) + ": " + poäng[i] + "\n";
this will start to print "1 :" BUT you count from 0 that's why the output seems weird.
public static String statistik(int[] fält) {
String poäng[] = new String[fält.length];
String output = "";
//Clear out the array:
for (int i = 0; i < poäng.length; i++) {
poäng[i] = "";
}
//Add a star for each time a number appears
for (int i = 0; i < fält.length; i++) {
for (int t = 0; t < fält.length; t++) {
if (fält[t] == i) {
poäng[i] += "*";
}
}
}
//Print it out
for (int i = 0; i < fält.length; i++) {
output += i + ": " + poäng[i] + "\n";
}
System.out.println(output);
return "";
}
1)Hi, #Habbo, it is because the flat[] array only consists 0's
2) only in first iteration i value will be 0 and then it never be zero again.
if (fält[t] == i) {
poäng[i] += "*";
}
4)so poäng[i] inside this "i" will only zero and never increases
5) that is why you are having weird result
you should change the output message
from output += (i + 1) + ": " + poäng[i] + "\n";
to output += i + ": " + poäng[i] + "\n";
at all i think you could optimize your code
by sort it first this will cost 2 Loops
then loop upon the sorted array like this
int temp= fält[0];
output = temp + ": *";
for (int i = 1; i < fält.length; i++) {
if(fält[i] >temp){
temp = fält[i];
output +="\n"+ temp + ": *";
}
else{
output +="*";
}
}
you will have only 3 Loops In your Code not 4
for(int counter = 0; counter < args.length; counter++){
System.out.println("Displaying per words: " + args[counter]);
splitWords = args[counter].toCharArray();
for(int counter2 = 0; counter2 < splitWords.length; counter2++){
System.out.println("Word spliced: " + splitWords[counter2]);
System.out.println("The number equivalent of " + splitWords[counter2] + " is "
+ (int) splitWords[counter2]);
occurenceCount[(int)splitWords[counter2]]++;
System.out.println("The letter " + splitWords[counter2] +
" was shown " + occurenceCount[(int)splitWords[counter2]] + " times.");
}
}
My function doesn't detect counter2 as a variable since it was inside the nested for loop. So how do I get out of this dilemma?
I'm trying to use the argument inputs (string respectively) and post the number of occurrences using an ascii table as reference and, as you see, there's just one obstacle from stopping me from accomplishing that.
Any ideas?
Your primary problem is that you have missed one important fact - your counts are not complete until after your loop has completed.
You therefore need to print out your counts in a separate loop after your first loop is complete.
public void test() {
String[] args = {"Hello"};
int[] occurenceCount = new int[256];
for (int word = 0; word < args.length; word++) {
System.out.println("Displaying per words: " + args[word]);
char[] splitWords = args[word].toCharArray();
for (int character = 0; character < splitWords.length; character++) {
System.out.println("Word spliced: " + splitWords[character]);
System.out.println("The number equivalent of " + splitWords[character] + " is "
+ (int) splitWords[character]);
occurenceCount[(int) splitWords[character]]++;
System.out.println("Word spliced: " + splitWords[character]);
}
}
// Scond loop to print the results.
for (int character = 0; character < occurenceCount.length; character++) {
int count = occurenceCount[character];
if (count > 0) {
System.out.println("The letter " + ((char) character)
+ " was shown " + count + " times.");
}
}
}
I have a task:
"Send integers n [1 .. 10] from command line. Enter n rows to the Console, find the shortest and the longest line. Print the results and line length."
My idea is: Create array of strings and copy every line from BufferedReader to the array data[i]. Sample of my code:
String[] data = new String[n];
int j=0;
for (int i = 1; i <= n; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, enter " + i + " string: ");
String line = in.readLine();
for (int j=0; j<=data.length;j++){
data[j] = line;
j++;
} ///:~
System.out.println("Your " + i + " string : " + data[j] + "String len: " + line.length());
} ///:~
But I could not find the way how to fill elements of array data[i] with new line from console.
Can you please give me a small hint?
To fill data, just replace the inner for-loop with a simple assignment using index i-1:
for (int i = 1; i <= n; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, enter " + i + " string: ");
String line = in.readLine();
data[i-1] = line;
System.out.println("Your " + i + " string : " + data[i-1] + "\nString len: " + line.length());
}
I left the loop from 1 to n instead of 0 to n-1 because you're printing i.
But if you only want the shortest and longest lines, there's no need to store all the lines, you only need to check the length of the current line against the length of the shortest and longest lines and change them appropriately.
the easyst way is
data[i-1] = in.readLine();
Thank you all for all your Help :)
Here is my example:
package taskstring;
import java.io.*;
public class TaskString {
public static void main(String[] args) throws java.lang.Exception {
int n = Integer.parseInt(args[0]);
if (n <= 0) {
System.out.println("Wrong! please send more numbers to java");
return;
}
System.out.println("Enjoy! You are going to send " + n + " string(s) to java");
int maxLen = 0;
int minLen = 0;
for (int i = 1; i <= n; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, enter " + i + " string: ");
String line = in.readLine();
System.out.println("Your " + i + " string : " + "String len: " + line.length());
if (maxLen < line.length()) {
System.out.println("New string is bigger");
maxLen = line.length();
} else {
System.out.println("New string is smaller");
}
if (minLen > line.length() || minLen == 0) {
System.out.println("New string is smaller" + " minLen=" + minLen);
minLen = line.length();
} else {
System.out.println("New string is bigger");
}
//return;
} ///:~
System.out.println("Max row: " + maxLen + "\nMin row: " + minLen);
} ///:~
}