I have been struggling to figure this out for the past 3 hours and i am frustrated as hell. If anyone can help me with this, I would greatly appreciate it. The program has to generate 10 random integers, then it has to print out the line of integers and group together the consecutive ones
Example:
4 3 3 4 0 0 1 3 0 4 4 5 2 2 5 4 5 1 2 2
After Grouping:
4 (3 3) 4 (0 0) 1 3 0 (4 4) 5 (2 )2 5 4 5 1 (2 2)
Heres is my code
package week6assignments;
import java.util.Random;
public class Question2REal
{
public static void main(String[] args) {
Random rand = new Random();
int[] rolls = new int[20];
int input;
int x = 1;
boolean found = false;
for (int i = 0; i < rolls.length; i++) {
input = rand.nextInt(6);
rolls[i] = input;
}
System.out.println("Raw data output after 20 dice rolls");
for (int i = 0; i < rolls.length; i++) {
System.out.print(rolls[i] + " ");
}
System.out.println("");
System.out.println("Data after grouping runs together");
for (int i = 0; i < rolls.length; i++) {
++x;
if (x > 19) {
x = 19;
}
if (rolls[i] == rolls[x] && found == false) {
System.out.print("(");
found = true;
if (rolls[i] == rolls[x] && found == true) {
System.out.print(rolls[i]);
}
}
if (rolls[i] > rolls[x] || rolls[i] < rolls[x] && found == true) {
found = false;
}
System.out.print(rolls[i]);
}
}
}
I know this program is way off what its supposed to do, but ive tried 100's of things I can think of and cant figure out or find an example online. :(
I am really confused with what you were trying to do there in your code (like you said, its way off) so forget about everything you already have in that last for-loop.
First, you are trying to figure out if the current number is the same as the next one to group them together. So something like this.
if (rolls[i] == rolls[i+1]) {
System.out.print("(" + rolls[i]);
}
Now, in your question and example, it wasn't clear if in the situation where if there are more than 2 same number, what was the intended action. So I assumed you would include it in the group.
In that case, you make a while loop (inside the if and after the print) that checks if all the following numbers are the same.
i++;
while (rolls[i] == rolls[i+1]) {
System.out.print(" " + rolls[i]);
i++;
}
Finally, we've always been printing the last number and not the current number so if the next one is no longer the same as the current, it will exit the while loop and we have to print the current number with a close bracket. So something like this...
System.out.print(" " + rolls[i] + ") ");
Now let's take care of else condition. Simple, just print the number and move on...
} else {
System.out.print(rolls[i] + " ");
}
Of course, this isn't perfect, there are still a few edge cases that you need to work on. What if the while loop loops through the last item? Now we have an ArrayIndexOutOfBound. So here's a little tweak...
while ((i+1) < rolls.length && rolls[i] == rolls[i+1])
But then what about the first if during the last for-loop iteration? Probably need the same fix...
if ((i+1) < rolls.length && rolls[i] == rolls[i+1])
I've basically done all the work and thinking for you. If you understood what I explained, you should be able to put these pieces together rather easily.
Homework is ready. ;)
import java.util.Random;
public class Homework {
public static void main(String[] args) {
Random rand = new Random();
Integer last = null;
boolean equals = false;
for (int i = 0; i < 20; i++) {
int newInteger = rand.nextInt(6);
if(Integer.valueOf(newInteger).equals(last)) {
if(!equals) System.out.print("( ");
equals = true;
System.out.print(last+" ");
} else {
if(last != null) System.out.print(last+" ");
if(equals) System.out.print(") ");
equals = false;
}
last = newInteger;
}
System.out.print(last);
if(equals) System.out.print(" )");
}
}
Related
I am currently lost as to what I should to do make this work. The assignment has already been turned in, but I am trying to be a good student and figure out why it wouldn't work. Here is the problem I was given:
A run is a sequence of adjacent repeated values. Write a Java class with one main method that generates a
sequence of 20 random die tosses in an ArrayList and that prints the die values, marking the runs by including
them in parentheses, like this:
1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 3 1
Pseudocode:
Hint: Use the following pseudocode:
Set a boolean variable inRun to false.
For each valid index i in the ArrayList
If inRun
If values[i] is different from the preceding value
Print ).
inRun = false.
If not inRun
If values[i] is the same as the following value
Print (.
inRun = true.
Print values[i].
If inRun, print ).
I know there are a bunch of questions like this, but I swear I have seen them all. I could not find one similar enough that used an ArrayList versus an Array.
Here is my code:
package run;
import java.util.ArrayList;
import java.util.Random;
public class DiceRoller {
public static void main(String[] args)
{
boolean inRun = false;
int roll;
ArrayList randomNumList = new ArrayList();
Random randNum = new Random();
for(int i = 0; i < 20; i++)
{
roll = randNum.nextInt(6);
randomNumList.add(roll);
}
//Gets the size of the ArrayList.
int sizeOfArray = randomNumList.size();
for (int i = 0; i <= sizeOfArray; i++)
{
if (inRun == true)
{
if (randomNumList.indexOf(i) == randomNumList.lastIndexOf(i)) //PROBLEM AREA//
{
System.out.print(")");
}
inRun = false;
}
if (inRun == false)
{
if(randomNumList.indexOf(i) == randomNumList.indexOf(i))//PROBLEM AREA//
{
System.out.print("(");
inRun = true;
}
}
}
System.out.println(randomNumList);
}
I can not for the life of me and the internet figure out why I could not get the correct output. I first tried to do if(randomNumList[] == randomNumList[i-1] and if(randomNumList[i] == randomNumList[i+1](i)). This was all I could find online, but gave me the error that it would not work with an ArrayList it needed an Array. So the way it is in the code if how I got it up till now. Output looks something like this:
(((((()()()()()()()()()()()()()()()([4, 0, 0, 1, 3, 5, 3, 4, 0, 5, 1, 5, 3, 4, 2, 3, 4, 2, 3, 5]
Please help!!
Let's start from the basics. First of all you should output each element of the list one by one inside the for loop:
for (int i = 0; i < sizeOfArray; i++) {
System.out.print(randomNumList.get(i) + 1);
}
This will print each dice roll. The +1 is because dices has numbers from 1 to 6, not from 0 to 5.
Now let's improve our code by considering the parenthesis cases:
Print a ( before the dice roll print if a certain condition is verified
Print a ) after the dice roll print if another certain condition is verified
Something like this:
for (int i = 0; i < sizeOfArray; i++) {
// Print '(' if ...
System.out.print(randomNumList.get(i) + 1);
// Print ')' if ...
}
What you need to test is the "next element", the i+1 one. If it is the same as the current one and you are not in a run, you should print ( before anything else. Alternatively, if you actually are in a run BUT the next one breaks it, you should print a )
for (int i = 0; i < sizeOfArray; i++) {
boolean isNextTheSame = (i+1 < sizeOfArray) && randomNumList.get(i+1) == randomNumList.get(i);
if (!inRun && isNextTheSame) {
System.out.print("(");
inRun = true;
}
System.out.print(randomNumList.get(i) + 1);
if (inRun && !isNextTheSame) {
System.out.print(")");
inRun = false;
}
}
In your pseudocode it tests the previous element in order to verify the second condition, and not the next one. But the results are the same
First, your display is totally buggy because you're doing a first loop displaying only the parenthesis then a sysout of the array list.
Then, your algorithm is not good
An ArrayList can be accessed like an array (just use .get(index)), this is not a problem
You should study in details the functions of ArrayList, I think you have not understand what lastIndexOf and indexOf are doing
I sugest you to doing this : by traducting in Java the hint given
Please note : if object in ArrayList are Integer, you have to use equals instead of ==
boolean inRun = false;
for (int i = 0; i < sizeOfArray; i++) {
// If inRun If values[i] is different from the preceding value Print
// ).
if (inRun && randomNumList.get(i) != randomNumList.get(i - 1)) {
System.out.print(") ");
inRun = false;
} else
// If not inRun If values[i] is the same as the following value
// Print (
if (!inRun && i < sizeOfArray - 1 && randomNumList.get(i) == randomNumList.get(i + 1))
{
System.out.print("( ");
inRun = true;
}
System.out.print(randomNumList.get(i) + " ");
}
if (inRun) {
System.out.print(") ");
}
I am writing a program that outputs how many times each integer is found in an array of integers. I have accomplished this, however, i have duplicate output strings.
This is the output:
>run:
>Please enter integers from 0 to 100:
1
2
3
4
4
5
0
// 1 occurs 1 time //
2 occurs 1 time //
3 occurs 1 time //
4 occurs 2 times //
4 occurs 2 times //
5 occurs 1 time //
BUILD SUCCESSFUL (total time: 14 seconds)
So as you can see, "4 occurs 2 times" prints twice since it is found twice in the array.
I just need some direction on how to eliminate the duplicates. Anything would be greatly appreciated.
import java.util.*;
public class WorkSpace3 {
public static void main(String[] args) {
int i = 0;
int count = 0;
int key = 0;
System.out.print("Please enter integers from 0 to 100: ");
int[] myList = new int[100];
Scanner s = new Scanner(System.in);
for (i = 0; i < myList.length; i++)
{
myList[i] = s.nextInt();
if (myList[i] == 0)
break;
}
while (key < myList.length && myList[key] != 0) {
for (i = 0; i < myList.length; i++)
{
{ if (myList[i] == myList[key])
{ count++; } }
}
if (count == 1)
System.out.println(myList[key] + " occurs " + count + " time ");
if (count > 1)
System.out.println(myList[key] + " occurs " + count + " times ");
key++;
count = 0;
}
}
}
A simple approach that is available to you is to mark the elements that you have counted with zeros. This approach is not universal; it is valid only because you use zero to mark the end of the input sequence by end-user.
You would have to slightly modify your code to use this approach: rather than looking for zero in the while loop, set up a variable to mark the length of the sequence. Set it to myList.length at the beginning, and then reset to i at the break. Now you can walk the list up to this max count, do the counting, and then set zeros into elements that you have already counted.
See the set element:
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Making a set element from array You remove the duplicates.
try this using Map
Map<Integer,Integer> counts=new HashMap<Integer,Integer>();
for (i = 0; i < myList.length; i++) {
if(counts.contains(myList[i]){
counts.put(myList[i],++counts.get(myList[i]);
}else{
counts.put(myList[i],1);
}
I'm creating a java project called magicsquare and I've searched online on how to do it. Now, I'm trying to understand how the 2nd loop works, I know that it prints and align the magic square, but I don't know the details. I already know the first one. I would really appreciate if someone explains to me the 2nd loop. Thanks!
import java.util.*;
public class Magicsquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int N;
System.out.print("Enter a number to create a Magic Square: ");
N=input.nextInt();
if (N % 2 == 0){
System.out.print("N must be an Odd number!");
}
else{
int[][] magic = new int[N][N];
int row = N-1;
int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
if (magic[r][c] < 10) System.out.print(" "); // for alignment
if (magic[r][c] < 100) System.out.print(" "); // for alignment
System.out.print(magic[r][c] + " ");
}
System.out.println();
}
}main (null);
}catch (Exception e){
System.out.print("Invalid Input!");
}
}
}
Well, first the obvious. The part about < 10 and < 100: if a number is between 0 and 9, it's only going to print out one digit. If it's between 10 and 99, it's going to print out two. And if it's between 100 and 999, it'll print out using three digits. (It seems as if this code is written to assume it will only encounter numbers between 0 and 999. Generally speaking, it's best to ensure that somehow rather than just hope.)
So, with the if statements and their extra spaces, a "5" will print out as " 5" (note the two leading spaces for a total of three characters). 25 will print out as " 25" (again, three characters) and 125 as "125" (three digits again). Since all of the numbers print out using three characters, everything will line up neatly in columns.
What confuses me is that you're iterating over c first, then r. This seems to say that you're printing out the first column on a single row on the screen, then the second column as a second row, and the third column as a third row. I.e. the whole thing has been rotated on a diagonal. But maybe that's just a naming issue.
Using a simple Java array called int score[], I wish to store in the array
the int 1 or 0.
The ints are supplied from a simple math question and an if statement, that allows a 1 to be added to the array if a correct answer is given, or a 0 if the answer is incorrect.
There are only 5 math questions to try, with 1 point/ 0 point (or int 1/0) for each correct answer, so its a fixed array of size[4].
I am using a for loop, but the durn thing keeps filling the array with 1's if i use <= score.Length() method.
I just wish to add an int 1 or 0 to score[4] without overwriting the previous element, each time the user answers a question.
if( playerTotal < computerTotal || playerTotal > computerTotal) {
System.out.printf("\n" + "Sorry, thats incorrect...try again__");
for(int i = 0; i <= score.length ;++i ) {
score[i] = 0 ;
System.out.print( " | ");
System.out.print( score[i]);
}
} else {
System.out.print( playerTotal + " is correct, very well done!");
// in.close();
for(int i = 0; i <= score.length ; i++ ) {
score[i] = 1 ;
System.out.print( " | ");
System.out.print( score[i]);
}
}
I hope to use the stored ints to move the math game (yayy!) onto the next level after 5 correct points are achieved.
You dont need a for loop if you want to set one element.
remove to for loop and write
if( playerTotal < computerTotal || playerTotal > computerTotal ) {
score[4]=0;}
else{score[4]=1;}
score[4] = ( (playerTotal < computerTotal) || (playerTotal > computerTotal)) ? 0 : 1;
As mentioned in the comments a few times, the error in your code is the loop overwriting the other values.
I do not know how you interact with the user, but I've provided an example on how you may solve this task. The do-while will ask for an answer until it is correct.
Scanner scanner = new Scanner(System.in);
String[] questions = {"What is 2-1?", "What is 2+1?", "What is 10-5?"};
int[] correctAnswer = {1,3,5};
//keep track of correct/incorrect answer with a boolean value
boolean[] score = new boolean[correctAnswer.length];
for(int i = 0; i < questions.length; i++) {
System.out.println(questions[i]);
do {
int input = scanner.nextInt();
score[i] = input == correctAnswer[i];
if(score[i])
System.out.println("Correct!");
else
System.out.println("Wrong, please try again..");
} while(!score[i]);
}
//do something with the score data
int sum = 0;
for(boolean b : score)
if(b) sum++;
System.out.println("You got " + sum + " points!");
Write a program that reads a list of 10 values from the user. Put the values in an array. The program should read the array and then calculate and display the average of the even input values and the average of the odd input values. This should be done using objects, methods, and a tester class.
I cannot figure out why I am receiving the error:
bad operand types for binary operator.
I do not know what to change. I know something is wrong with my mod (%).
Here is what I have so far for my Average class:
public class Average
{
private int[] numbers = new int[10];
double aveEven, aveOdd,sumEven=0,sumOdd=0;
int oddCounter=0, evenCounter=0;
public Average(int[] n)
{
numbers = n;
if (numbers % 2 == 0)/something is wrong here/
{
evenCounter++;
sumEven+=n;
}
else
{
oddCounter++;
sumOdd+=n;
}
}
public void aveEven()
{
for (int i = 0; i < numbers.length; i++)
{
aveEven = sumEven/evenCounter;
System.out.println("The even average is: " + aveEven);
}
}
public void aveOdd()
{
for(int i = l; i < numbers.length; i++)
{
aveOdd = sumOdd/oddCounter;
System.out.println("The odd average is: " + aveOdd);
}
}
}
For the AverageTester class I have the following:
import java.util.Scanner;
public class AverageTester
{public static void main(String[] args)
{
int[] integer = new int[10];
Scanner input = new Scanner(System.in);
for(int i=0 ; i < 10 ; i++)
{
System.out.print("Please enter a number : ");
integer[i] = input.nextInt();
}
Average example = new Average(integer);
example.aveOdd();
}
}
Also, If you see anything else that could be wrong, please let me know.
Thank you.
numbers is an array, so numbers % 2 is invalid. You should loop over the array and use the % operator on the elements of the array. The += operator should also be applied on a element of the array (i.e. numbers[i]) and not the entire array.
numbers = n;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evenCounter++;
sumEven+=numbers[i];
} else {
oddCounter++;
sumOdd+=numbers[i];
}
}
As for aveEven and aveOdd, since you already compute the sums in the constructor (or at least it seems like that's what you intended to do), you don't need a loop in these methods.
EDIT :
I originally assumed you intended to calculate the average of the numbers in even positions in the array and the average of the numbers in odd positions. After reading the question again, I think the odd/even refers to the numbers themselves, so I changed the code accordingly.
Numbers is an array and comparing an array to an int doesn't work, you could do something like this (depending on your logic):
for(int number : numbers){
if(number % 2 == 0){
evenCounter++;
sumEven += n;
}else{
oddCounter++;
sumOdd += n;
}
}
Few Mistakes
1.) if (numbers % 2 == 0), numbers is an array, use index here and loop. like this if (numbers[i] % 2 == 0).
2.) sumEven += n;, again n is an array here, need to use index.
3.) for (int i = l ; i < numbers.length ; i++) {, you have used l instead of 1.