I am attempting to generate an ADDITIONAL single random number and create another method that will have three parameters = the integer array, the size of the array, and the value it will be searching for in the array. It will search through the array and count how many times the value was found.It will then either print out how many times the value was found or that the value was not found. I am a bit lost and this is what I have so far which generates the random array and prints it/ asking the user if they want to restart. Thanks in advance
My code:
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public void createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] number = new int[20];
createNum(number);
printNum(number);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
I should not be telling you the whole code, since this looks like a homework question.
So here are the hints:
Creating an additional random number - Not so difficult, as you have RND_GEN
int rn = RND_GEN.nextInt(10)+1; //exactly as you have been doing it.
Creating a method that takes three parameters.... Here is the method header:
void search(int[] array, int size, int val)
Body of the method? You have various search algorithms out there. Some of the most popular ones are:
linear search
binary search
So just go on, research, learn and do it yourself.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to make a bubble sorting algorithm in Java however my code just keeps going when It's supposed to sort without returning anything. When the program is run it gets as far as printing the array before the sorting however after that nothing happens but the program doesnt stop it keeps running
package src;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class bubbleSort {
public static void main(String[] args) {
int length = getLength();
List<Integer> randomList = createList(length);
System.out.println("The list before sorting:\n" + randomList);
List<Integer> newList = sortList(randomList, length);
System.out.println("The list after sorting:\n" + newList);
}
public static int getLength() {
System.out.println("Please enter how long you want the array to be");
Scanner reader = new Scanner(System.in);
int length = Integer.parseInt(reader.nextLine());
return length;
}
public static List<Integer> createList(int length) {
Random rand = new Random();
List<Integer> randomList = new ArrayList<Integer>();
for(int x = 0 ; x < length ; x++){
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
randomList.add(randomnumber);
}
return randomList;
}
public static List<Integer> sortList(List<Integer> randomList, int length){
boolean sorted = false;
while(sorted == false){
sorted = true;
for(int x = 0 ; x < (length - 1) ; x++) {
if(randomList.get(x) > randomList.get(x + 1)) {
sorted = false;
int temp = randomList.get(x + 1);
randomList.set((x + 1), (x));
randomList.set((x + 1), temp);
}
}
}
return randomList;
}
}
Create a swap method to make it clearer (both for us and yourself):
private void swap(List<Integer> values, x, y) {
int temp = values.get(x);
values.set(x, values.get(y));
values.set(y, temp);
}
Other suggestions:
name your class BubbleSort rather than bubbleSort. Convention for class names is to start with uppercase.
don't pass the length as a second argument to your sort method. It's redundant and might become incorrect if someone sneakily adds an item to the list.
rename randomList to values or numbers or randomNumbers. No need to repeat the type in the variable name.
replace sorted == false with !sorted. This is the common and more readable notation
getLength and createList can be private
Consider using the main method to create an instance of your sorting class, with the list as a field. In that way the methods won't have to pass the list along to each other. Your code will be more readable and more object-oriented.
EDIT: you could take the separation even further and move all the static methods into a separate class called 'Application' or 'Main'. See edited code below:
Here's roughly how the code would look following my suggestions:
public class BubbleSort {
// a field
private List<Integer> numbers;
public BubbleSort(List<Integer> numbers) {
this.numbers = numbers;
}
public static List<Integer> sort() {
boolean sorted = false;
while(!sorted) {
sorted = true;
for(int x = 0; x < length - 1; x++) {
if(numbers.get(x) > numbers.get(x + 1)) {
sorted = false;
swap(x, x + 1);
}
}
}
return numbers;
}
private void swap(x, y) {
int temp = numbers.get(x);
numbers.set(x, numbers.get(y));
numbers.set(y, temp);
}
}
The Application class. It's purpose is to get the length from the user, create test data and set up and call a BubbleSort instance:
public class Application {
public static void main(String[] args) {
int length = getLength();
List<Integer> unsorted = createList(length);
System.out.println("The list before sorting:\n" + unsorted);
// creating an instance of the BubbleSort class
BubbleSort bubbleSort = new BubbleSort(unsorted );
List<Integer> sorted = bubbleSort.sort();
System.out.println("The list after sorting:\n" + sorted);
}
private static int getLength() {
System.out.println("Please enter how long you want the array to be");
Scanner reader = new Scanner(System.in);
return Integer.parseInt(reader.nextLine());
}
private static List<Integer> createList(int length) {
Random rand = new Random();
List<Integer> numbers = new ArrayList<Integer>();
for(int x = 0 ; x < length ; x++){
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
numbers.add(randomnumber);
}
return numbers;
}
BTW Good job splitting off those methods getLength and createList. That's the right idea.
you made a couple of mistakes
this:
randomList.set((x + 1), (x));
randomList.set((x + 1), temp);
should be:
randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);
full method:
public static List<Integer> sortList(List<Integer> randomList, int length){
boolean sorted = false;
while(sorted == false){
sorted = true;
for(int x = 0 ; x < (length - 1) ; x++) {
if(randomList.get(x) > randomList.get(x + 1)) {
sorted = false;
int temp = randomList.get(x + 1);
randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);
}
}
}
return randomList;
}
I am working on a problem for 5 hours, and I searched in a book and on the Internet, but I still cannot solve this problem, so please help me to check what's wrong with the program. And the pic is the requirement for this program.
//imports
import java.util.Scanner;
import java.util.Random;
public class Lab09 // Class Defintion
{
public static void main(String[] arugs)// Begin Main Method
{
// Local variables
final int SIZE = 20; // Size of the array
int integers[] = new int[SIZE]; // Reserve memory locations to store
// integers
int RanNum;
Random generator = new Random();
final char FLAG = 'N';
char prompt;
prompt = 'Y';
Scanner scan = new Scanner(System.in);
// while (prompt != FLAG);
// {
// Get letters from User
for (int index = 0; index < SIZE; index++) // For loop to store letters
{
System.out.print("Please enter the number #" + (index + 1) + ": ");
integers[index] = RanNum(1, 10);
}
// call the printStars method to print out the stars
// printArray(int intergers, SIZE);
} // End Main method
/***** Method 1 Section ******/
public static int RanNum(int index, int SIZE);
{
RanNum = generator.nextInt(10) + 1;
return RanNum;
} // End RanNum
/***** Method 2 Section ******/
public static void printArray(int integers, int SIZE) {
// Print the result
for (int index = SIZE - 1; index >= 0; index--) {
System.out.print(integers[index] + " ");
}
} // End print integers
} // End Lab09
As Tim Biegeleisen and Kayaman said, you should put everything in the question and not just an external image.
You have a lot of errors in your code. Below the code will compile and run but I recommend you to take a look and understand what it has been done.
Errors:
If you are declaring a method, make sure you use { at the end of the declaration. You have:
public static int RanNum(int index, int SIZE);
Should be:
public static int RanNum(int index, int SIZE){
// Code here
}
You also should declare outside your main method so they can be accessed across the program.
If you are passing arrays as arguments, in your method the parameter should be an array type too.
You have:
public static void printArray(int integers, int SIZE) {
// Code her
}
Should be
public static void printArray(int[] integers, int SIZE) {
// Code her
}
Here is the complete code:
package test;
import java.util.Random;
import he java.util.Scanner;
public class Test {
//Local variables
public static final int SIZE = 20; //Size of the array
static int integers[] = new int[SIZE]; //Reserve memory locations to store integers
static int randomNumber;
static Random generator = new Random();
static String prompt;
static final String p = "yes";
static boolean repeat = true;
static Scanner input = new Scanner(System.in);
Test() {
}
/***** Method 1 Section ******/
public static int RanNum (int low, int high) {
randomNumber = generator.nextInt(high-low) + low;
return randomNumber;
} //End RanNum
/***** Method 2 Section ******/
public static void printArray(int[] intArray, int SIZE) {
//Print the result
for (int i = 0; i < SIZE; i++) {
System.out.print (intArray[i] + " ");
}
} //End print integers
public static void main (String [] arugs) {
do {
for (int i = 0; i < SIZE; i++) {
integers[i] = RanNum(1, 10);
}
printArray(integers, SIZE);
System.out.println("Do you want to generate another set of random numbers? Yes/No");
prompt = input.nextLine();
} while(prompt.equals(p));
}
}
I'm creating a program that will generate 100 random numbers between 1 and 1000, add them to a list, and then sum up those numbers. Here's my code:
public class Iteration {
public static void main (String [] args){
private int RandomDataAnalyzer(int Rando) {
Random rand = new Random();
List<Integer> NumList = new ArrayList<Integer>();
for (int i=0;i<=100;i++){
Rando = rand.nextInt(1001);
NumList.add(Rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
Rando = rand.nextInt(100);
sum = sum + Rando;
}
return sum;
}
}
}
And here's my errors:
H:\Java\Iteration.java:12: error: illegal start of expression
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
Any help, please?
You can't define a method inside another method. Close your main method first, then start RandomDataAnalyzer:
public static void main(String[] args) {
// Contents of main.
}
public int RandomDataAnalyzer(int Rando) {
// Contents of RandomDataAnalyzer.
}
I'm going to assume that this isn't a homework problem and that you're learning Java on your own. If I'm wrong, shame on me for giving a working version. But my impression is that you'll learn from this:
public class gpaCalc
{
static Random rand;
static int rando;
public static void main(String[] args)
{
ArrayList<Integer> NumList = new ArrayList<>(); // use ArrayList
for (int i=0;i<=100;i++)
{
rand = new Random();
rando = rand.nextInt(1001);
NumList.add(rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
rando = NumList.get(i); // get is "opposite" of put--get the value put into the list earlier
sum = sum + rando;
}
System.out.println(sum);
}
}
There doesn't seem to be a need for a separate method called randomDataAnalyzer.
Welcome to StackOverflow.
Let's begin with the first issue: randomDataAnalyzer is being defined inside main method. Which is wrong, you should be actually defining it at the same level.
Taken into consideration, you should also add the static word before this function because this method is part of the class, and not of the elements. It's not necessary to create a new element of the class 'Iteration' for using a simple method.
Last, but not least, you are looping through the arraylist incorrectly. You are not even calling it. As you will see now:
import java.util.*;
public class Iteration
{
public static void main(String[] args)
{
ArrayList<int> numberList = new ArrayList<int>(); // we define the arraylist
for (int i = 0; i < 100; i++)
{
numberList.add(new Random().nextInt(1001)); // we add a random number to the list
}
// finally, after the 100 values were added..
System.out.println(randomDataAnalyzer(numberList)); // we show the output
}
public static int randomDataAnalyzer(ArrayList<int> list) // we will send this function an arraylist which will get the Σ.
{
int sum = 0;
for (int value : list) // this is how we loop through foreach value in the list
{
sum += value; // which means sum = sum + value.
}
return sum; // after looping and summing up, here'll be the result
}
}
I hope this was what you were looking for.
Here's a working version. Note the changes to your original:
Don't define methods inside methods: it is illegal syntax.
Rando, NumList: the naming conventions are to start classes, interfaces, enums (i.e. types) with a capital letter, and methods, fields, and variables with a lowercase case letter;
Removed the int Rando parameter alltogether: it's value was never used (it was only assigned to)
Use the values from numList rather than generating new numbers.
Added a method illustrating that the use of such a list is not needed in this case; the 'list' of 1000 numbers is still present, but only conceptually.
import java.util.*;
public class Iteration {
public static void main (String [] args) {
int sum = new Iteration().randomDataAnalyzer();
System.out.println(sum);
}
private int randomDataAnalyzer() {
Random rand = new Random();
List<Integer> numList = new ArrayList<Integer>();
for ( int i=0; i<100; i++ )
{
numList.add( 1 + rand.nextInt(1000) );
}
int sum = 0;
for ( int i=0; i<numList.size(); i++ )
{
sum = sum + numList.get(i);
}
return sum;
}
// Note that the above method has the same effect as this one:
private int moreEfficient() {
Random rand = new Random();
int sum = 0;
for ( int i=0; i < 100; i++)
sum += 1 + rand.nextInt(1000);
return sum;
}
}
import java.util.Random;
public class DotComTestDrive {
public static void main(String [] args) {
String stringOfWords[] = {"Do", "You", "Like", "Me"};
boolean correctOrder = true;
int numberOfResets = 0;
String correctString;
String realString[];
while (correctOrder == true) {
System.out.println();
for (int x = 0 ; x < 4 ; x++) {
int rand = (int) (Math.random() * 4);
System.out.print(stringOfWords[rand]);
System.out.print(" ");
numberOfResets++;
}
// Place If statement here to change correctOrder to false when the new string is "Do You Like Me "
}
System.out.println(numberOfResets);
}
}
My main goal for this is to try and get the new random four words that
it prints out into an String[] so I can then use an If statement to
see if the string matches the original. Then I will make the boolean
"correctOrder" be false, ending the loop.
I know it is simple and sorry if its not a great or clear question.
Just trying to learn the basics and anything helps, thanks!
What I would suggest is to use a list and shuffle it every time you loop.
Map<K,V> map = xxxx;
List<Map.Entry<K,V>> list = new ArrayList<Map.Entry<K,V>>(map.entrySet());
// each time you want a different order.
Collections.shuffle(list);
for(Map.Entry<K, V> entry: list) { /* ... */ }
Assuming that you want to put these Strings in realString, you should do as follows/
initialise this Array
assign one of its elements in your for loop.
For example:
String realString[] = new String[4];
while(correctOrder == true){
for(int x = 0; x < 4; x++){
int rand = (int) (Math.random()*4);
System.out.print(stringOfWords[rand]);
System.out.print(" ");
realString[x] = stringOfWords[rand];
}
}
Also, since I'm at it, I'd suggest you to change a few things in your code:
no need to specify == true: a boolean variable can be tested by itself.
the use of the Random class (instead of Math one) is often preferred. You could have a final Random r = new Random() and get a random int in the range [0, 4[ by simply using r.nextInt(4)
I have an array and have already sorted it. I want to be able to find which numbers repeat. Following that, I want to be able to count how many times these numbers repeat. For example in a list [1,2,3,3,4,4] 3 and 4 repeats and they both repeats twice. My following code is able to find which numbers repeats but unable to get my mind around on how to count the number of times they each repeat. And I am using ArrayList. Trying to skip that and keep everything to purely just arrays excluding hashmap too. Appreciate any help. Tnks.
public static void main(String[] args) {
int[] num = {1,2,3,3,4,4};
for(int x : num){
System.out.print(x + " ");
}
System.out.println("\n" + freq(num));
}
public static ArrayList<Integer> freq(int[] num){
ArrayList<Integer> list = new ArrayList<>();
for(int x=0; x < num.length-1; x++){
if(num[x] == num[x+1]){
if(!list.contains(num[x])){
list.add(num[x]);
}
}
}
return list;
}
Well, since your array is sorted,you could use another array where each index corresponds to the amount of hits for this number:
int[] count = new int[num[num.length - 1]];
Then you could increment the index of this counter for each match:
count[num[x] - 1] = count[num[x] - 1] + 1;
This would however not compact your representation, just bring it to another form. Since you do not know the result lenght before the computation, a more compact representation without lists or even better maps is however not possible since the size of an array must be known at creation. This solution will only work with numbers bigger than 0. For other ranges, you have to adjust the offset.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
int[] num = {1,2,3,3,4,4};
for(int x : num){
System.out.print(x + " ");
}
System.out.println("\n" + freq(num));
}
static class ValueCountPair {
public ValueCountPair( final int val )
{
value = val;
count = 2;
}
public int value;
public int count;
public String toString() {
return "[" + value + ": " + count + "]";
}
}
public static ArrayList<ValueCountPair> freq(final int[] num){
ArrayList<ValueCountPair> list = new ArrayList<ValueCountPair>();
ValueCountPair last = null;
for(int x=0; x < num.length-1; x++){
if(num[x] == num[x+1]){
if ( last == null || last.value != num[x+1] )
list.add( last = new ValueCountPair( num[x+1] ) );
else
++last.count;
}
}
return list;
}
}