How to write text with parameter and variable - java

Have an assignment I cant figure out. The assignment is:
With a given method:
static void writeTexts(String text, int amount);
Print out the text in the parameter text as many times as given by the variable amount. Every print of text on separate line.
Print an empty line for every third time text is printed.
Write a main method with one or more calls of writeTexts with appropriate test data (don't know what this means) to check that the method works in all cases.
I'm a beginner and find this very difficult, have been reading and watching tutorials, also searched and found a similar question, but can`t seem to grasp this. Any help is appreciated.
The error I get when running my code is:
cannot find symbol.
What I got so far:
public class Task {
static void writeTexts(String text, int amount) {
amount = 0;
text = "hallo";
while (amount< 3) {
System.out.println(text);
amount++;
}
}
public static void main(String[] args) {
writeTexts(text);
}
}

static void writeTexts(String text, int amount) {
for(int i = 0; i < amount; i++){
//Check if the line is the a multiple of 3
//then print an empty line
//I use i + 1 because I start at 0 which is a multiple of 3
//but we are not interested by the that
if( (i + 1) % 3 == 0 ){
System.out.println("");
}
//Print the text
System.out.println(text);
}
Now for calls of writeTexts with appropriate test data that essentially means call the function with so the appropriate parameters e.g: writeText("Halo 3", 3).
I would strongly recommend you to read some more on function to get better grasp of how they work.

You are overwriting amount with 0 and you are overwriting text with "hallo" which is incorrect because you will be printing "hallo" instead of text and you lose track of how many time you need to print.
amount = 0;
text = "hallo";
Your loop will always only iterate 3 times. Instead you should iterate amount times. To do this, you will also need a counter i
int i = 0;
while (i < amount) {
You are not printing an empty line every third time text is printed. You should add this:
i++;
if (amount % 3 == 0) { // If amount is divisible by 3
System.out.println();
}

Related

How to alter and display only one column (via user input) on 2D array Java

I am creating a game board. I need it to reveal a the selected column after a user input, while the rest of the columns still print as "X". This game holds values I have set in each column, but does not print them on the screen. When the user selects a column, I need it to print showing the value that column is holding while the rest of the columns still print "X" so they do not reveal what they have. I am new to this, thank you for your help.
This is the function where I think the problem is. If you look, you will see that I have the if statement "if (isCovered) - then I want it to print the covered version. Then the "else" - which is where I want it to print just the one that was guessed as its actual value. I have tried multiple ways of achieving this with no luck. Is there are way to make it like (!isCovered)? But that doesn't work, because it states it needs to be an array and the function "!" does not work. Right now it just seems like it never prints the "else" statement at all. I have functions that take the user input and compare them to "isCovered" and they work correctly, because the piece moves on the board as it should. I just cannot get it to print the actual value instead of an "X". Thank you for any help and if further information would be helpful, please let me know. It is due today unfortunately I only had a few days to work on it and have been working constantly on it.
public static void PrintRevealBoard(int[][] myArray,Boolean[][] isCovered)
{
int i, j;
for (i = 0; i<myArray.length ; i++ ) { // array.length = max rows
System.out.print((i+1) + " ");
for(j = 0; j <myArray[0].length; j++) { // array[0].length = max
cols
if(isCovered[i][j]){
System.out.print(GetRollColorCovered(myArray[i][j]) + " ");
} else {
System.out.print(GetRollColor(myArray[i][j]) + " ");
}
}
your main module is kinda messy. And I don't know how GetRollColor(dice) works. Anyway as I understand you have a two dimensional array and you want to show only a specific value. Seems like u want to show the entire input column.
use this to update isRevealed() after the input of inputCol.
public static Boolean[][] updateRevealed(Boolean[][] isRevealed, int inputCol){
for(int i=0;i<isRevealed[inputCol].length;i++)
isRevealed[inputCol][i] = true;
return isRevealed;
}
update like this,
isRevealed = updateRevealed(isRevealed,inputCol);
your printRevealBoard is almost correct. Just remove the first line. It doesn't make sense and you don't want it as I see
int isRevealed = inputCol;
I don't know how your array looks like. But because of the first for loop u will definitely get an
index out of bounds exception
loop runs until I becomes myarray.length. and in the next loop you access index I of myArray. Exception will be thrown if I=myArray.length. u gotta fix it. If any problem occurs lemme know.
thankyou
edit:
try this for printRevealBoard
public static void printRevealBoard(char[][] myarray , Boolean[] []isRevealed){
for(int i=0;i<myarray.length;i++){
for(int j=0;j<myarray[0].length;j++){
if (isRevealed[i][j]) System.out.print(myArray[i][j] + " ");
else System.out.print("* ");
}
System.out.println();
}
}

Why are 2 for loops needed in this program?

Why does this program need 2 for loops to function? Is there a way to write this without the 2 for loops?
Its purpose is to assign integer values 1-25 to an array with a length of 25. It then prints the array as five separate lines each containing five array elements separated by commas.
Its output is this:
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20
21,22,23,24,25
public class ArrayNums
{
static int[] arrayList = new int[25];
public static void main(String[] args)
{
for(int i=0; i<25; i++)
arrayList[i] = i + 1;
printArray();
}
public static void printArray()
{
int i;
for(i=1; i<=25; i++){
if (i % 5 != 0)
System.out.print(arrayList[i-1]+",");
else
System.out.println(arrayList[i-1]);
}
}
}
Of course, the main function would go like this :
public static void main(String[] args)
{
for(int i=0; i<25; i++){
arrayList[i] = i + 1;
if ((i+1) % 5 != 0)
System.out.print(arrayList[i]+",");
else
System.out.println(arrayList[i]);
}
}
Though, it's considered better practice to have one function doing only one thing at a time. It makes it much easier to understand, hence your first version I would rather advice to use.
Keep it separate because this enables Separation of Concerns and better usage and maintenance of the program. As #cricket_007 stated, it's better to "have buildArray() as a separate function from printArray()".
In this scenario, the output could be achieved using a single loop and you could print i instead of the arrayList contents, but I doubt you really have a critical need to print 1 to 25 on 5 lines - assume the build and print functions would change in practice. Consider a few scenarios:
Scenario 1
Let's say the program was later required to also output to a CSV file and return a JSON object (not at the same time but by different function calls). If you're building and printing in the same loop, now you need to put the building part into three different functions.
Scenario 2
Let's say you need to change the contents of the array from numbers to letters or inputted data or the ability for the program to do any of those three. Making this change within the loop makes it harder to see potential conflicts or errors.
Scenario 3
Both Scenario 1 and Scenario 2 happen.
I think this will help you.`You could easily add the printarray() method inside the first method.
public static void main(String[] args) {
for(int i=1;i<=25;i++){
arrayList[i-1]=i;
if(i%5==0){
System.out.println(i);
}else{
System.out.print(i+",");
}
}
}

How do you change each part of an array?

So here is the code I have right now.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
int set[] = new int[5];
set[0] = (int)(Math.random()*6)+1;
set[1] = (int)(Math.random()*6)+1;
set[2] = (int)(Math.random()*6)+1;
set[3] = (int)(Math.random()*6)+1;
set[4] = (int)(Math.random()*6)+1;
System.out.println("Your current dice: " + set[0] + " " + set[1] + " " + set[2] + " " + set[3] + " " +set[4] );
System.out.println("Select a die to re-roll (-1 to keep remaining dice):");
int ask = keyboard.nextInt();
After this if the user types in let's say 1 then set[1] should change to the number zero and so it becomes x0xxx and if the user also wants the 3rd number to change then it should be x0x0x.
The x's are just the generated random numbers by the way.
How do I keep doing this? It has to be a total of utmost 5 times.
Here are the basic steps you should follow to accomplish what you want/need.
Read user input (using Scanner or something else).
Validate if the user input is a valid index for the array (this is, the input is a number with a value between 0 and 5). You can store this in a variable int x.
Change the value of the element of the array inside the index user entered to 0 (or the value you want/need). This would traduce into something like set[x] = ... (change the ... by the proper value).
The way you do one thing many times is in a loop. The key is in learning which kind of loop to use.
For things that get applied to every element, use a for-each loop. For things that need done until some condition use a while loop. For things that need done until some condition becomes false, use a do-until loop.
The thing you do is the same, that goes into the block of the loop. The thing you are "working on" changes, that is a variable which the loop will set each time it "goes through" the loop's block.
In your case
for (Die die : dice) {
die.roll();
}
where class Die looks like
public class Die {
private int value;
public Die() {
roll();
}
public void roll() {
value = (int)(Math.random()*6)+1;
}
public int getValue() {
return value;
}
}
Then, since you need "order" (first, second, third, etc...) use a data structure that can contain Objects (like your Die)
List<Die> dice = new ArrayList<>();
Arrays are nice, and you do need to know how to use them; however, there are far better ways of solving most problems by not using them.
When you really can't get around using them, use a for loop to walk each array index.

10 ×10 multiplication table, but only shows those entries which are greater than a value entered by the user

I have a 10x10 multiplication table. I need to code in so that when a user inputs a certain number, 50 for example, the numbers >50 are replaced by a character and the rest remain the same.
I know how to do this using strings but I have no clue how to do this in this situation. Any help will be appreciated.
public class task4{
public static void main(String args[]){
int Multiples = 10;
System.out.format(" Table");
for(int z = 1; z<=Multiples;z++ ) {
System.out.format("%5d",z);
}
System.out.println();
System.out.println("-------------------------------------------------------------------------------------------------------");
for(int i = 1 ;i<=Multiples;i++) {
System.out.format("%5d |",i);
for(int j=1;j<=Multiples;j++) {
System.out.format("%5d",i*j);
}
System.out.println();
}
}
}
That seems to be simple enough problem, basically you have table drawing code, your for loops, so we function that off into a nice little method public void drawTable(){} which we call to draw the table initially, but we also provide an overloaded version which takes a number public void drawTable(int maxDispNum){} and this method is the same except if i*j >maxDispNum we print a character instead. then in main we can simply while(true){ read val; drawTable(val);}
alternativley if you want to maintain a permanent record of what's been removed stored the table in an array, 10*10 in your case and use some marker, -1 works here to indicate removed, and simply check for that in your draw method,

Trying to Make an Average Finder, Not Using ReadLine(), using Only Console

New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;

Categories