Adding values to array without overwriting - java

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!");

Related

Finding consecutive numbers in an array

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(" )");
}
}

Counting integers in an array; How to eliminate duplicate output strings

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);
}

Loop Counting in Java

What I have is a program that prints out 4000+ random digits in the range of 1 to 99999. After printing, it shows the range, and a couple of other things, and then asks user for 5 numbers to be input and tells how many times it had to run the loop, but I'm getting an exception in main upon print, it's coming from the main for loop. Screenshot is attached. Desired should look something like:
(Randomly generated numbers):
25
192
33
(User Enters) Please enter number: 33
(System Response) It took 3 times to find the number.
If the number is not listed, as it is over 4000 integers, it will say, not found.
Here is code and screenshot:
Screenshot
Exception in Main java.lang.ArrayIndexOutOfBoundsException:0
Thank You!
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] input = new int[0];
int[] arrayone = new int[4096];
int loop = 0;
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
for(int in = 0; in<input.length; in++) {
if (arrayone[i] == input[in]) {
loop++;
}
}
}
for (int i = 0; i < 5; i++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[0] = s.nextInt();
if (min <= input[0] && input[0] <= max) {
System.out.println("It took " + loop + " time(s) to find the number " + input);
}
}
}
The problem with your input array is that you initialize it with a size of 0, so when you try to access the first location [0], you run out of the bounds since your array has a size of 0. In your answer you were also trying to determine the loops before asking the question. While doing this you were also trying go past the bounds of your input array with a size 0. What you should do is initialize your array of numbers first then for each guess loop through and determine if it's within the bounds of your max and min. Also note that just because the numbers are within the max and min doesn't guarantee the number is contained in the array because the numbers are not going to be sequential from max to min. You should check where you end up after your for-loop check for the input.
public static void main(String random[])
{
Scanner s = new Scanner(System.in);
int input = new int[5];
int[] arrayone = new int[4096];
int loop = 0;
//don't do anything here except fill the array with values
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
}
//ask the user for 5 inputs
for (int index = 0; index < input.length; index++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[index] = s.nextInt();
//check to see if the number is valid
if (min <= input[index] && input[index] <= max) {
//loop through the arrayone to determine where it is
for(int i = 0; i < arrayone.length; i++) {
//if it is not in the current index at i increment the loop count
if (arrayone[i] != input[index]) {
loop++;
}
//we have found where it is and should break out of the loop
else {
break;
}
}
//check if we found it based on how much we incremented
if(i != arrayone.length)
{
//output how long it took to find the number
System.out.println("It took " + loop + " time(s) to find the number " + input[index]);
}
else
{
System.out.println(input[index] + " not found!");
}
//now reinitialize the loop to 0 for the next guess
loop = 0;
}
}
//always remember to close your scanners
s.close();
}
}
int[] input = new int[0];
This creates an array with size of 0, so when you try save value it throws an exception because you are exceeding array size.
Solution: set valid size of array or use list.
The ArrayList is (simplifying) resizeable version of array. Use it like this:
List<Integer> input = new ArrayList<>();
input.add(5); //Adds 5 to list
input.get(0); //Read object of index 0
for(int value : list) { //Loop: for each element in list ...
System.out.println(value);
}
//Checks whether list contains 5
System.out.println(list.contains(5));
Also, do you actually need input to be an array? Because right now it looks like you don't need it at all.

How to print 10 numbers per line in java

I have a simple but hard problem and wanted to get your help on this.
This is the code:
int i = 0;
while (i < 100) {
i++;
System.out.print(i);
}
This is the real issue that I'm having, how do I control the println to display how many numbers per line that I want so I don't just see 100 numbers in a row straight?
Btw please if at all possible, don't give me the answer but help me to answer it myself instead.
while loops? Why not use for loops? They are much better in this kind of situation i.e. when you want to repeat something a known number of times.
You can use a nested for loop to make this happen:
int counter = 0;
for (int i = 0 ; i < 10 ; i++) {
for (int j = 0; j < 10 ; j++) {
System.out.print (counter);
System.out.print (" "); // I think it is best to have spaces between the numbers
counter++;
}
//after printing 10 numbers, go to a new line
System.out.println ();
}
You could do something like:
for(int number = 0; number <= 100; number++) {
if(number % 10 == 0 && number > 0)
System.out.println(number);
else
System.out.print(number + " ");
}
This would create 10 rows of 10 numbers.
Try this one
if (i%10==1){
System.out.println("");
}

I don't understand what to use to check all values in an array?

import java.util.Scanner;
public class Project10C {
public static void main ( String [] args ) {
Scanner reader = new Scanner(System.in);
int [] finalarray = new int [5];
int [] test = new int [1000];
int x = 1000;
int temp1;
for ( int i = 0; i <= 4;i++){
System.out.println ( "Input a number between 1 and 25 inclusive: " );
temp1 = reader.nextInt();
test[i] = temp1;
if ( i > 0 ){
if ( temp1 == test[i] ) {
System.out.print ("Sorry that number has already been entered.");
break;
}
else {
finalarray[i]= temp1;
Did not include brackets in this question. Point of this code is check if numbers inputted have already been entered. I'm having difficulty trying checking if the number they input is equal to values in an already existing array. In this:
if (temp1 == test[i] ){
From my own knowledge this will only check the current array going through this if statement every time. Should I be using another for statement? If so what would I put for the second parameter of the for statement?
There are many ways to do this. The easiest way is probably using another loop inside the main loop, as follow:
for ( int i = 0; i <= 4;i++){
System.out.println ( "Input a number between 1 and 25 inclusive: " );
temp1 = reader.nextInt();
boolean repeated = false;
for(int j = 0; j < i; j++) {
if(finalarray[j] == temp1) {
// the number is already entered.
repeated = true;
break;
}
}
if(repeated)
break;
// number is not entered before
finalarray[i] = temp1;
}
Actually when you're reading i-th number, you have to check every number from 0 to (i - 1) in the array to not be equal with entered number.
However, if there are a lot of numbers, using a data structure like Set is preferable. Just add every number to the set and then you can easily check if a new number is previously entered:
Set<Integer> numbers = new TreeSet<Integer>();
for(int i = 0; i < n; i++) {
temp1 = reader.nextInt();
if(numbers.contains(temp1)) {
// already entered
break;
}
// number is not entered before
// add it to our array
finalarray[i] = temp1;
// also put it in the set for future checks
numbers.add(temp1);
}
You need another for-loop to compare previous elements of final-array with the entered input as recommended in my solution. Also, the loop would iterate always from 0 to i---the key thing!
The solution goes as :-
for ( int i = 0; i <= 4;i++){
System.out.println ( "Input a number between 1 and 25 inclusive: " );
temp1 = reader.nextInt();
for( int j=0;j<i;j++){
if(temp1==finalarray[j]){
System.out.println("Sorry that number has already been entered.");
break;
}
else
finalarray[i]= temp1;
}
}
Do you have to use a primitive array, or can you use an ArrayList? If you can use an ArrayList:
List<int> myArrayList = new ArrayList();
for (int i = 0; i <= 4; i++){
System.out.println ( "Input a number between 1 and 25 inclusive: " );
temp1 = reader.nextInt();
/* The array list already has the input number. */
if (myArrayList.contains(temp1)) {
System.out.print ("Sorry that number has already been entered.");
break;
/* The array list does not contain the input number. */
} else
myArrayList.add(temp1);
}
Also, are you only trying to allow 4 digit numbers to be input?

Categories

Resources