Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
so this is the case.
I'm doing an excercise where I have to compare each random number with all my static numbers from an external file lotto.dat
I have to make a method doCompare() which returns either true or false. My question will appear after my code:
public static void drawNumbers()throws Exception{
Random rnd = new Random();
int rndN1 = rnd.nextInt(19)+1;
int rndN2 = rnd.nextInt(19)+1;
int rndN3 = rnd.nextInt(19)+1;
int rndN4 = rnd.nextInt(19)+1;
int rndN5 = rnd.nextInt(19)+1;
int rndN6 = rnd.nextInt(19)+1;
System.out.println();
System.out.println("Winner numbers: " + rndN1 + " " + rndN2 + " " + rndN3 + " " + rndN4 + " " + rndN5 + " " + rndN6);
String match = doCompare(rndN1);
if(match.equals("true")){
System.out.println("Match on the number: " + rndN1);
}
}
So is it possible somehow loop the "doCompare" with parameters "doCompare(rndN1)" then rndN2, rndN3 and so on or what else should I do to make this work?
Use a proper data structure, like an array or a List to store the random numbers and loop over them:
List<Integer> numbers = new ArrayList<>();
for(int cout = 0 ; count < 6 ; ++count) {
numbers.add(rnd.nextInt(19)+1);
}
// ...
for(int n : numbers) { // go through all the numbers in the list
doCompare(n);
}
Create a List which can collect your integers. Create a loop which create the integers and add them to a list. While creating the random integers, you can create the output string in the loop too. And at the end use another loop for the method call doComapre() and pealse change the return value of doCompare() method to boolean. Then you can use it in the if statement and have not to check if the return value is equals "true".
Random rnd = new Random();
List<Integer> rndNumbers = new ArrayList<>();
String outputString = "Winner numbers:";
for(int i = 0; i < 6; i++)
{
rndNumbers.add(rnd.nextInt(19) + 1);
outputString = outputString + " " + rndNumbers.get(i);
}
System.out.println();
System.out.println(outputString);
for(Integer curNumb : rndNumbers)
{
String match = doCompare(curNumb );
if (match.equals("true"))
{
System.out.println("Match on the number: " + curNumb );
}
}
Maybee you can use an array because you are always want to generate six numbers. And for the String creation you can replace the String with a Stringbuilder.
The simplest solution would be to create array or list and store rnd number and then loop over it
Yes, you can, but not as you want to do it.
you have to create a list of your rndNX values
Like so:
List<Integer> rndList = new ArrayList<Integer>();
fill it like so :
rndList.add(rnd.nextInt(19)+1);
rndList.add(rnd.nextInt(19)+1);
...
And use the list :
for(final Integer rndI : rndList)
{
String match = doCompare(rndI );
}
Random rnd = new Random();
System.out.println();
for(int i = 0; i < 6; i++)
{
int rndN = rnd.nextInt(19)+1;
String match = doCompare(rndN);
if(match.equals("true")){
System.out.println("Match on the number: " + rndN1);
}
}
You could do something like this. Instead of initializing all your random numbers first initialize them in a loop as needed.
Store the int values into the array or a list and loop through it.
Related
I am trying to make a for loop to print out all of the following strings to go into the println statement below but cannot figure out how to get the for loop to print the Array. I keep getting the error 'cannot find symbol.' There will be a scanner that allows for user inputs after each println statement.
public static void Real() {
String[] sequence;
sequence = new String[4];
sequence[0] = ("first");
sequence[1] = ("second");
sequence[2] = ("third");
sequence[3] = ("fourth");
int number;
for (number = 0; number <= sequence(); number++ ) {
System.out.println("Input your " + sequence + " lap time");
}
}
A couple of syntax errors present in your code, also, method name in java should start with a lowerase.
Code below should do the work.
public static void real() {
String[] sequence;
sequence = new String[4];
sequence[0] = "first";
sequence[1] = "second";
sequence[2] = "third";
sequence[3] = "fourth";
int number;
for (number = 0; number < sequence.length; number++ ) {
System.out.println("Input your " + sequence[number] + " lap time");
}
}
use number<sequence.length instead of number <= sequence()
and
use sequence[number] instead of sequence inside system.out.println()
public static void Real(String a[]) {
String[] sequence;
sequence = new String[4];
Scanner input= new Scanner(System.in);
sequence[0] = ("first");
sequence[1] = ("second");
sequence[2] = ("third");
sequence[3] = ("fourth");
int number;
for (number = 0; number <4 ; number++ ) {
System.out.println("Input your " + sequence[number] + " lap time");
System.out.println("Input");
variable = inupt.nextDatatype();
}
}
this is the answer after what i understood.
i don't know about this by the way sequence();
You can't print an array just by referring to its name in a print statement, you need to loop through all the elements and print element at each index. You access an element using the syntax array[index].
You need to loop from 0 to the last index, I think what you're trying to get from sequence() is the size of the array. To get the size of array you need to use array.length
So your code should look like this :
public static void Real() {
String[] sequence;
sequence = new String[4];
sequence[0] = ("first");
sequence[1] = ("second");
sequence[2] = ("third");
sequence[3] = ("fourth");
int number;
for (number = 0; number < sequence.length; number++) {
System.out.println("Input your " + sequence[number] + " lap time"); } }
How about using for-each loop?
for (String s : sequence)
System.out.println("Input your " + s + " lap time");
So our teacher told us to create a JApplet with a highscore.
He wanted us to use an Arraylist which contains 10 integer values. If u press a JButton these values are getting displayed in a JLabel. And you can enter a number and where it is placed in the Array. Like if I enter 10 and in the other text field 0, the number 10 is the first number which gets displayed when I press the button. But the other 10 integer values are supposed to move one digit up in the array.
e.g I enter nothing I get displayed
1,2,3,4,5,6,7,8,9,10
and when I enter 10 and 0 it should display
10,1,2,3,4,5,6,7,8,9,10.
My problem is that I don't get how to move the numbers like I can only get this thing if I enter 10 and 0:
10,2,3,4,5,6,7,8,9,10
Here is my Code:
public void neueListe (int Stelle,int Zahl, int[] highscore){
highscore[Stelle] = Zahl;
}
public void jButton1_ActionPerformed(ActionEvent evt) {
int Stelle = Integer.parseInt(jTextField2.getText());
int Zahl = Integer.parseInt(jTextField1.getText());
int[] highscore = new int [10];
highscore[0]=1;
highscore[1]=2;
highscore[2]=3;
highscore[3]=4;
highscore[4]=5;
highscore[5]=6;
highscore[6]=7;
highscore[7]=8;
highscore[8]=9;
highscore[9]=10;
neueListe(Stelle,Zahl, highscore);
jLabel1.setText(""+ highscore[0]+", " + highscore[1]+", " + highscore[2]+", "+ highscore[3] + highscore[4] + highscore[5] + highscore[6] + highscore[7] + highscore[8] + highscore[9]);
}
Convert your int[] into ArrayList and then simply add any element at any position using add method.
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(highscore));
arr.add(Zahl, Stelle); // arr.add(position, value)
System.out.println(arr);
if you want to print all no.s as string then use this.
String labelshow = "";
for(Integer item: arr){
labelshow += "," + item;
}
jLabel1.setText(labelshow);
Or you can simply put your no. in required position and shift rest of the elements towards right using a for loop.(size would be increased keep this in mind.)
int newarray[] = new int[highscore.length+1];
for(int i=0, j=0; i<highscore.length+1; i++){
if(i == Zahl){
newarray[i] = Stelle;
}
else{
newarray[i] = highscore[j++];
}
}
newarray contains your resultant array. You can print it or show it in JLabel.
This program should ask how many of an animal are left in the wild 5 times. Then it should use a second method to output the same information. But i cant figure this out; every time i change anything based on previous questions here i just add to the number of errors.
import java.util.Scanner;
class animals {
public static void main(String[] args) {
int[] q1 = question();
output(q1);
System.exit(0);
} // exit main
public static int[] question() {
String[] wild = { "Komodo Dragon", "Mantee", "Kakapo", "Florida Panther", "White Rhino" };
int number = 0;
int[] record = {};
for (int i = 1; i <= 5; i++) {
System.out.println(wild[number] + ":");
Scanner scanner = new Scanner(System.in);
System.out.println("How many are left in the wild?");
int howMany = scanner.nextInt();
record = new int[] {howMany};
number++;
}//end for loop
return record;
}// end method question
public static void output(int[] q1){
System.out.println("There are " + q1[0] + " Komodo Dragons in the wild");
System.out.println("There are " + q1[1] + " Mantees in the wild");
System.out.println("There are " + q1[2] + " Kakapos in the wild");
System.out.println("There are " + q1[3] + " Florida Panthers in the wild");
System.out.println("There are " + q1[4] + " White Rhinos in the wild");
}//end method output
} // end class animals
So this compiles alright, then when i've added 5 numbers in terminal after each loop i get
There are 3 Komodo Dragons in the wild
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at animals.output(animals.java:39)
at animals.main(animals.java:13)
Other than the fact that im getting the text, the monodo dragon number being provided is the last number i input not the first
This doesn't make sense
int[number] record = {};
most like what you meant was
int[] record = new int[wild.length];
and instead of
for (int i = 1; i <= 5; i++) {
you need
for (int i = 0; i < wild.length; i++) {
instead of the following which creates an array of 1 value [0]
record = new int[] {howMany};
which will produce the following when you try to access [1]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
you need
record[i] = howMany;
As you write each line of code in your IDE (or your editor) you should see if that compiles and if it doesn't adding more lines is unlikely to help. I suggest you try to compile and test as often as possible so you know where the source of your errors are and when you get a bug, you can step through the code in your debugger to see why the program is not doing what you expect.
This is what you need:
int number = 0;
int[] record = new int[5];
and another modification which you need to make:
int howMany = scanner.nextInt();
record[number] = howMany;
Remove comment from last line.
Now your program should work fine.
Learn some basic stuff about arrays.
My code asks the user to enter values of animal species and then displays it back to them. I just need to finally add a part which also tells the user the most endangered animal (the one will the lowest entered number). I've looked around on some places and triec using x< min or x=MAX_VALE etc. I just can't seem to make anything work. Is there a method which would be more appropriate for my program?
import java.util.Scanner;
public class endangered
{
public static void main(String[] param)
{
animal();
System.exit(0);
}
public static void animal()
{
int[] array = new int[5];
int j = 0;
String[] names = {"Komodo Dragon" , "Manatee" , "Kakapo" , "Florida Panther" , "White Rhino"};
System.out.println("Please enter the number of wild Komodo Dragons, Manatee, Kakapo, Florida Panthers and White Rhinos.");
Scanner scan = new Scanner(System.in);
for (int i=0; i<=4; i++)
{
while(scan.hasNextInt())
{
array[j] = scan.nextInt();
int max = array[j];
j++;
if(j==5)
{
System.out.println(array[0] + ", " + names[0]);
System.out.println(array[1] + ", " + names[1]);
System.out.println(array[2] + ", " + names[2]);
System.out.println(array[3] + ", " + names[3]);
System.out.println(array[4] + ", " + names[4]);
}
}
}
}
}
What you can do is sort the array using a built-in method and then retrieve the last value (the greatest) and first value (the smallest).
Arrays.sort(array);
int max = array[array.length - 1];
int min = array[0];
For more on the sort method in Java's Arrays class, here's a description of what it exactly does,
public static void sort(int[] a)
Sorts the specified array into ascending numerical order.
Parameters:
a - the array to be sorted
If you want to get the corresponding animal then I would suggest ignoring the above and use streams in Java 8. Combine the String and int array into one 2D String array. Make the rows equal to the number of animals and the columns equal to 2 (ex: for 5 animals, String[][] array = new String[5][2]). For each row in the 2D array, the first element should be the animal, and the second element should be the size (ex: String [][] array = {{"fox", "1"},{"deer","0"},{"bear", "2"}}). The following will return you a 2D array that is sorted in ascending order and gives you the corresponding animal with it,
String[][] sorted = Arrays.stream(array)
.sorted(Comparator.comparing(x -> Integer.parseInt(x[1])))
.toArray(String[][]::new);
String smallestAnimal = sorted[0][0]; //name of smallest animal
String smallest = sorted[0][1]; //population of smallest animal
String biggestAnimal = sorted[sorted.length - 1][0]; //name of biggest animal
String biggest = sorted[sorted.length - 1][1]; //population of biggest animal
In java 8, you can do something like this:
int min = Arrays.stream(array).reduce(Integer.MAX_VALUE, Math::min);
Update: The user asked for print of the animal as well.
If you need to return the animal as well, it would be best if we edit your code.
We will add 2 more variables. The first one, minVal will contain the lowest number that the user entered. The second one, minValIndex will contain the index of the species with the lowest count.
I removed your while cycle because there was no need for one.
public static void animal()
{
int[] array = new int[5];
int j = 0;
String[] names = {"Komodo Dragon" , "Manatee" , "Kakapo" , "Florida Panther" , "White Rhino"};
System.out.println("Please enter the number of wild Komodo Dragons, Manatee, Kakapo, Florida Panthers and White Rhinos.");
Scanner scan = new Scanner(System.in);
int minVal = Integer.MAX_VALUE;
int minValIndex = -1;
for (int i=0; i<=4; i++)
{
array[j] = scan.nextInt();
if(array[j] < minVal) {
minVal = array[j];
minValIndex = j;
}
int max = array[j];
j++;
if(j==5)
{
System.out.println(array[0] + ", " + names[0]);
System.out.println(array[1] + ", " + names[1]);
System.out.println(array[2] + ", " + names[2]);
System.out.println(array[3] + ", " + names[3]);
System.out.println(array[4] + ", " + names[4]);
}
}
System.out.println("The smallest entered number:" + minVal);
System.out.println("The species:" + names[minValIndex]);
}
You are not calculating max anywhere.
Replace:
int max = array[j]
With:
max = max > array[j] ? max : array[j];
To store the maximum value in the array. (This is a ternary operator)
Now the array have have equal values so in that case take care of this possibility by this code :
for(int i = 0; i <= 4; i++) {
if(array[i] == max) {
System.out.println("Max endangered:" + array[i] + name[i]);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to do some program and need of some help. For example, I entered this number on a textbox: 00669253, then for each number i want to multiply it with the number 87654321 so for example
(0x8) + (0x7) + (6x6).... and so on and then get the sum of all the number and do a mod of 11. How can I do this?
Thanks for your advance help.
You can first convert the number into String and then you can do it like this :
String no1="00669253";
String no2="87654321";
int sum=0;
for(int i=0;i<no1.length();i++){
sum+=Integer.parseInt(""+no1.charAt(i))*Integer.parseInt(""+no2.charAt(i));
}
After that you can do any operation on sum
You can try something like that:
public class TestMult {
public static void main(String[] args) {
String first = "00669253";
String second = "87654321";
long sum = 0L;
if (first.length() == second.length()) {
for (int i = 0; i < first.length(); i++) {
int firstInt = Character.getNumericValue(first.charAt(i));
int secondInt = Character.getNumericValue(second.charAt(i));
sum += firstInt * secondInt;
}
System.out.println("result: " + sum % 11);
} else {
System.err.println("lengths are not equal.");
}
}
}
try this,
public class Dummy {
public static void main(String[] args) {
String s = "112211";
String s2 = "010101";
char[] sDummy = s.toCharArray();
char[] s2Dummy = s2.toCharArray();
int sum = 0;
for (int i = 0; i < sDummy.length; i++) {
System.out.println("multiplying..." + sDummy[i] + "with " + s2Dummy[i] + "and adding prev sum " + sum + " to it");
sum = sum + (Integer.parseInt(sDummy[i] + "") * Integer.parseInt(s2Dummy[i] + ""));
}
sum = sum % 11;
System.out.println("sum with mod is = " + sum);
}
}
You need to add some checks in case if length of both string differs
Try this,
String inputValue = "00669253";
String multipleValue="87654321";
int result = 0;
for (int i = 0; i < inputValue.length(); i++)
{
result += Integer.parseInt(Character.toString(inputValue.charAt(i))) *
Integer.parseInt(Character.toString(multipleValue.charAt(i)));
}