Setting up a highscore by using arrays - java

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.

Related

How can I get the system output value after the whole loop is done?

this is my first question in this community as you can see I'm a beginner and I have very little knowledge about java and coding in general. however, in my beginner practices, I came up with a little project challenge for myself. as you can see in the figure, the loop starts and it prints out the number that is given to it through the scanner. the problem with my attempt to this code is that it gives me the output value as soon as I press enter. what I want to do is an alternative of this code but I want the output values to be given after the whole loop is done all together.
figure
So, basically what I want is to make the program give me the input values together after the loop ends, instead of giving them separately after each number is put.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
calc(); }
public static int calc (){
Scanner scan = new Scanner(System.in);
int count = 1;
int pass = 0;
int notpass = 0;
System.out.println("how many subjects do you have? ");
boolean check = scan.hasNextInt();
int maxless = scan.nextInt();
if (check){
while(count <= maxless ){
System.out.println("Enter grade number " + count);
int number = scan.nextInt();
System.out.println("grade number" + count + " is " + number);
if (number >= 50){
pass++;
}else{
notpass++;
}
count++;
}
System.out.println("number of passed subjects = " + pass);
System.out.println("number of failed subjects = " + notpass);
}else{
System.out.println("invalid value!");
} return pass;
}
}
I think what you want to do is create an array of int numbers.
It would be something like this:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int maxless = 5;
int[] numbers = new int[maxless];
int count = 0, pass = 0, notPass = 0;
while(count < maxless){
System.out.println("Enter grade number " + (count + 1) + ":");
numbers[count] = scan.nextInt();
if(numbers[count] >= 50){
pass++;
}
else{
notPass++;
}
count++;
}
for(int i=0; i<maxless; i++){
System.out.println("Grade number " + (i + 1) + " is " + numbers[i]);
}
}
}
The output is the following:
Enter grade number 1:
90
Enter grade number 2:
76
Enter grade number 3:
54
Enter grade number 4:
67
Enter grade number 5:
43
Grade number 1 is 90
Grade number 2 is 76
Grade number 3 is 54
Grade number 4 is 67
Grade number 5 is 43
When dealing with arrays, just remember that the indexation begins at 0. You can read more about arrays here: http://www.dmc.fmph.uniba.sk/public_html/doc/Java/ch5.htm#:~:text=An%20array%20is%20a%20collection,types%20in%20a%20single%20array.
A tip: it's gonna be easier to help if you post the code on your question as a text, not an image, so we can copy it and try it on.
Approach 1 :
You can use ArrayList from Collection Classes and store the result there and after the loop is completed, just print the array in a loop.
Example :
//Import class
import java.util.ArrayList;
//Instantiate object
ArrayList<String> output = new ArayList();
while(condition){
output.add("Your data");
}
for(i = 0; i < condition; i++){
System.out.println(output.get(i));
}
Approach 2 :
Use StringBuilder class and append the output to the string, after the loop is completed, print the string from stringbuilder object.
Example :
//import classes
import java.util.*;
//instantiate object
StringBuilder string = new StringBuilder();
while(condition){
string.append("Your string/n");
}
System.out.print(string.toString());
Approach 3 : (As mentioned by Sarah)
Use arrays to store the result percentage or whatever and format it later in a loop. (Not a feasible approach if you want to store multiple values for the same student)
Example :
int studentMarks[] = new int[array_size];
int i = 0;
while(condition){
studentMarks[i++] = marks;
}
for(int j = 0; j < i; j++)
System.out.println("Marks : " + studentMarks[j]);

Java FXML TextArea.setText() Stops Working

I am trying to update a TextArea in my Java FXML program and am encountering a weird problem. I am able to update the instructions 2 times but on the third instance of the same update call the text field will not update. I am using the same method call for all updates and have gotten what should be displayed to print in the console, so I know the problem is with the TextArea update. Here is the code causing the problem:
private void freedomCheck(){ // method for starting out a composition, choosing "mode"
decisionIndex = 0;
this.addChord("I"); //initialize first chord to "I"
prompt[0] = "Please enter your degree of freedom: 1, 2, 3, or 4."; //display prompt
prompt[1] = "1: Composes and plays for you";
prompt[2] = "2: Fill in just notes with chords given to you";
prompt[3] = "3: Fill in chords and notes, with software giving you options for both";
prompt[4] = "4: Fill in chords and notes with full independence";
prompt(); // get user input (can be changed to button press, etc.
}
private void prompt(){
String displayString = "";
for(int i=0;i<5;i++){
displayString += prompt[i] + "\n";
}
setInstructions(displayString);
System.out.println(displayString);
}
public void setInstructions(String newString){
instruction_text.setText(newString);
}
The prompt[] array is used to quickly separate lines of text. This section of the code works and prints correctly on the display, but later when I try to update it with the same prompt() call:
public void promptNotes(){
decisionIndex = 4;
int index;
if (composition.noteLength() == 0)
index = composition.getSize() - 1;
else index = composition.noteLength();
prompt[0] = "The current chord is " + composition.getChord(index).getName() + "; please pick a note:";//prompt
Chord temp = composition.getChord(composition.getSize()-1);
ArrayList<Note> candidates = temp.getOfferedNotes();
int notesLen = candidates.size(); //length of notes list for current chord
for(int i = 1; i < 5; i++){
tempNotes[i] = candidates.get(notesLen - i);
prompt[i] = (i+1) + ": " + tempNotes[i].getName();
}
prompt();
}
The correct output is printed to the console, but the textArea does not update.

How would I determine the smallest value which has been entered?

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

How to split string value to Array list value (Total Array size is 300) using java sample program

I have create a sample program in java .The concepts is split String value to generate Array list in one by one its means total string is input below:
Step one Total size:
Sting numberlist ="1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890........................1234567890";
ArrayList aList= new ArrayList(Arrays.asList(numberlist.split(",")));
for (int i = 0;i<aList.size();i++)
{
System.out.println(" new number-->" + aList.get(i));
// Toast.makeText(getApplicationContext(),"number is"+aList.get(i),Toast.LENGTH_SHORT).show();
}
I got the answer +alist.get(i) = 300 ,Than Step two know i having total size 300
The process is split the value one by one means
Display First 100 value 1234567890,1234567890,1234567890,.....
Display Second 100 value 1234567890,1234567890,1234567890,.....
Display Third 100 value 1234567890,1234567890,1234567890,.....
Sample programs is:
String numberlist="1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890........................1234567890";
int splitNumber = 100;
int length = numberlist.length();
ArrayList<String>splitList = new ArrayList<String>();
int splitCount = 0;
for(int i = 1 ; i<= length;i++)
{
splitCount++;
boolean last = false;
if(i==length)
{
last = true;
}
if((splitNumber == splitCount) || last)
{
String number = numberlist.substring(splitList.size()*splitNumber,i);
number = number.endsWith(",") ? number.substring(0,number.length()) : number;
number = number.startsWith(",") ? number.substring(1,number.length()) : number;
splitList.add(number);
splitCount = 0;
}
}
for(String number : splitList)
{
System.out.println();
System.out.println("Display First 100 value"+number);
}
}
but something wrong in the program don't know where is the problem anyone given me solutions.
I need my output is below:
Display First 100 value 1234567890,1234567890,1234567890,.....
Display Second 100 value 1234567890,1234567890,1234567890,.....
Display Third 100 value 1234567890,1234567890,1234567890,.....
its like one by one..
Note : sorry my grammar mistake..
Judging by your question, I assume the number of elements is divisible by splitNumber. There are a few approaches to this. Here I show one using modulo to create groups of size splitNumber and int division to get the group number:
public class Test {
public static void main(String[] args) throws Exception {
String numberlist = "1234,1234,1234,1234,1234,1234,1234,1234,1234";
int splitNumber = 3;
ArrayList<String> splitList = new ArrayList<String>(Arrays.asList(numberlist.split(",")));
if (splitList.size() % splitNumber != 0)
throw new Exception("Number of elelemnts not divisable by split number");
for (int i = 0; i < splitList.size(); i += splitNumber) {
System.out.print(((i / splitNumber) + 1) + " group of " + splitNumber +": ");
for (int j = 0; j < splitNumber; j++) {
System.out.print(splitList.get(i + j) +", ");
}
System.out.println();
}
}
}
Output:
1 group of 3: 1234, 1234, 1234,
2 group of 3: 1234, 1234, 1234,
3 group of 3: 1234, 1234, 1234,
Perform your own formatting.
If I understand the question correctly.. You can display 100 elements and whatever is leftover like this.
for (int i = 0; i < s.length(); i += 100) {
if ((i+100) > s.length()) {
System.out.println(s.substring(i, s.length()));
} else {
System.out.println(s.substring(i, i + 100));
}
}

I need to get from the user input random

import java.util.Scanner;
public class hh {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int numbers = input.nextInt();
// Declare an array called numbers with a size of 10
int[] numbers1 = new int[numbers];
insertRandomNumbers(numbers1);
// Print size of numbers
System.out.println("Initial Array: ");
for (int i = 0; i < numbers1.length; i++) {
System.out.print(numbers1[i] + " ");
}
System.out.println("");
//Print First and Last Elements
System.out.println();
System.out.println("First and Last Elements");
int [] lastStep = lastStep(numbers1);
for (int i = 0; i < lastStep.length; i++) {
System.out.print(lastStep[i] + ", ");
}
} // end main
public static int[] lastStep(int[] numbers1) {
//to get first
int [] firstElement= numbers1.get(0);
//last number
int [] lastElement= numbers1.get(numbers1.size()-1);
}
return lastStep;
public static void insertRandomNumbers(int[] x) {
for (int i = 0; i < x.length; i++) {
x[i] = random();
// System.out.print(x[i] + " ");
}
// System.out.println();
}
public static int random() {
int r = 0 + (int) (Math.random() * (101 - 0)) + 0;
return r;
}
My program ask the user to enter a number, then if 10 is entered 10 random numbers are created. With those 10 numbers I need to get the first and last numbers. The way I have my method right now I am getting ERROR: Cannot invoke get(int) on the array type int[]
WHEN I USE
public static int[] lastStep(int[] numbers1) {
//to get first
int [] firstElement= numbers1.array[0];
//last number
int [] lastElement= numbers1.array[numbers1.size()-1];
}
return lastStep;
I get that array cannot be resolved or is not a field
That's because you're using an Array not an ArrayList. Try using numbers1[0] and numbers1[numbers.length - 1]
You should consider changing your lastStep function. From what I can see, it does nothing, because the return statement is outside the function braces. There is also no variable lastStep inside the function that can be returned. Try the following:
public static string firstAndLast(int[] numberArray)
{
return numberArray[0] + ", " + numberArray[numberArray.length - 1];
}
Then just call it like:
System.out.println(firstAndLast(numbers1));
You can't use .get(0) on an array, you have to use array[0].
In your case it would be: numbers1[0]
Use Array List for to add random numbers , then print the last and first one.

Categories

Resources