Sorting 5 generated numbers from lowest to highest [duplicate] - java

This question already has answers here:
int[] array (sort lowest to highest)
(11 answers)
Closed 6 years ago.
I have a project in school to make a simplified Yatzy program and now I've hit a road bump. I have generated 5 random dice throws and printed them out in one window, but I need to sort them from lowest to highest and I don't know how.
I've looked in forums like this one but I don't understand, feel free to ask questions if you don't understand. BTW I'm Swedish so the text in the "" lines are in Swedish if you don't understand.
This is my code:
import javax.swing.*;
public class Projekt1 {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Välkommen till Johans Yatzy");
JOptionPane.showConfirmDialog(null, "Vill du starta spelet?");
int[] tar = new int[5];
String output = "";
for(int i=0; i<5; i++){
tar[i] = (int)(Math.random()*6+1);
output = output + tar[i] + "\t";
}
JOptionPane.showMessageDialog(null, "Dina tärningskast blev följande: " + output);
}
}

Use
java.util.Arrays.sort(tar);
to sort the int array:
for(int i = 0; i < tar.length; i++){
tar[i] = (int)(Math.random()*6+1);
}
// sort tar array
java.util.Arrays.sort(tar);
for (int i = 0; i < tar.length; i++) {
output = output + tar[i] + "\t";
}

Related

My code's output is not the array I input [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 1 year ago.
I am trying to run the following code in order to input an array of any size I desire:
import java.util.Scanner;
import java.util.Arrays;
public class testing2 {
public static void main(String[] args) {
double[] inputs = new double[5];
int currentSize = 0;
System.out.println("Please enter values, Q to quit:");
Scanner in = new Scanner(System.in);
while (in.hasNextDouble())
{
if (currentSize >= inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length);
}
inputs[currentSize] = in.nextDouble();
currentSize++;
}
inputs = Arrays.copyOf(inputs, currentSize);
System.out.print(inputs);
}
}
But when I input any array, my output is just a combination of symbols such as: [D#13fee20c, and this is not the output I am hoping for. Could anyone help me?
You're not printing correctly:
for (int i = 0; i < input.length; i++)
System.out.print(input[i] + " ");
}

Output contents of array in reverse in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My task is to make an array of size 20. Ask the user how many numbers he/she wants to enter. Put all those numbers in an array, then output that array in reverse. I've gotten it completed up to the "output that array in reverse" part.
import java.util.Scanner;
public class Activity7 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System. in );
System.out.println("How many numbers?");
int quantityOfNumbers = keyboard.nextInt();
int[] numbers = new int[20]; //making an array the size of 20
//0 - 19 (Valid values of the array)
for (int subscript = 0; subscript < quantityOfNumbers; subscript++) {
System.out.println("Enter number " + subscript);
numbers[subscript] = keyboard.nextInt();
}
System.out.println("Array Contents");
for (int subscript = 19; subscript >= 0; subscript--) {
}
}
}
If you want to print the array with out the empty elements, you can use something like this. As 0 is the default int value, print it as long as it is not 0.
public static void reverse(int[] array)
{
for(int i=array.length-1;i>=0;i--)
{
if(array[i]!=0)
{
System.out.println(array[i]);
}
}
}
I'm not completely sure what you are looking for. Could you specify a bit more? I'm completing your code to match the provided output anyway:
import java.util.Scanner;
public class Activity7
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many numbers?");
int quantityOfNumbers = keyboard.nextInt();
int[] numbers = new int[20]; //making an array the size of 20
//0 - 19 (Valid values of the array)
for (int subscript = 0; subscript < quantityOfNumbers; subscript++)
{
System.out.println("Enter number " + subscript);
numbers[subscript] = keyboard.nextInt();
}
System.out.println("Array Contents");
for (int subscript = 19; subscript >= 0; subscript--)
{
if (subscript >= quantityOfNumbers) System.out.println("Subscript " + subscript + "is empty");
else System.out.println("Subscript " + subscript + "contains " + numbers[subscript]);
}
}
}

I'm trying to make a hangman game, but I'm getting hung up on things like arrays [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.Scanner;
import java.util.ArrayList;
public class hangman {
public static void ttt(String inputWord) {
int wordLength = inputWord.length();
String blanks = "";
for (int i = 0; i < wordLength; i++) {
blanks = blanks.concat("_ ");
}
// System.out.print(wordLength);
System.out.println(blanks);
int points = 0;
int counter = 0;
ArrayList<String> usedChars = new ArrayList<String>();
while (points < wordLength) {
Scanner reader = new Scanner(System.in);
System.out.println("Guess: ");
String guess = reader.next();
// int checker = 0;
// for(int k = 0; k < usedChars.size(); k++) {
// if(usedChars.get(k) != guess) {
// checker = checker + 1;
// }
// else {}
// }
// if(checker == usedChars.size()) {
for (int i = 0; i < wordLength; i++) {
if (guess == inputWord.substring(i, i + 1)) {
points = points + 1;
usedChars.add(guess);
System.out.println("hit"); // this is me trying to see if
// this part is working
} else {
}
}
System.out.println("Used letters: " + usedChars);
// }
// else {
// System.out.print("Sorry, that letter has already been used");
// }
counter = counter + 1;
if (counter == 5) {
points = wordLength;
}
}
System.out.println("Game over");
}
public static void main(String[] args) {
ttt("to");
}
}
Don't worry about the commented out code, that's just me going over the top trying to prevent duplicate guesses, but it's more important that I get the rest of the code to work first.
Anyway, the only part of my code that seems to be working is the counter part. You can try it yourself, but it seems like all it does it take 5 guesses (5 lives, kind of random) and print game over.
edit: in hindsight i need to revisit that counter part, because it should only increase for incorrect guesses
The first thing I noticed was that my array isn't working correctly. It's not .add()'ing like I ask it to add my guesses. (Source: https://beginnersbook.com/2013/12/java-arraylist-add-method-example/)
Then, the more serious problem of the code not even being able to record correct guesses :/
I'm starting to code in my school's java class and decided to try this on my own for fun, any help would be greatly appreciated! :P
change the following boolean expression
guess == inputWord.substring(i, i + 1)
to
guess.equals(inputWord.substring(i, i + 1))
because guess is a String object. using '==' operator will only compare the reference, not the value.
also you might want to use
String guess = reader.nextLine();
instead of
String guess = reader.next();

How do I change a string array into an int array? [duplicate]

This question already has answers here:
How to convert string array to int array in java [duplicate]
(6 answers)
Closed 6 years ago.
I am making a code that stores sport scores and matches through user input however I have used a string array to store both string and int value - while this did not seem to be a problem at first I have realized that validation becomes tedious as you can equally store a string in the "score" section even though it is incorrect.
I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem.
The user input looks like this;
Home_Team : Away_Team : Home_ Score : Away Score
I want to be able to add all the Away/Home scores to produce an output like so;
Total Home score: x
Total Away Score: x
Here is my for loop so far,
for (int i = 0; i < counter; i++) { // A loop to control the Array
String[] words = football_list[i].split(":"); // Splits the input
if (words.length == 4) {
System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["+ words[3].trim() + "]");
}else{
System.out.println("Your input was not valid.");
matches--;
invalid++;
The logic for my new code will be "If Element[] does not contain an int value print "Invalid input"
"I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem."
To make an integer from a String, use this :
int x = Integer.parseInt( some_string );
Java Split String Into Array Of Integers Example
public class Test {
public static void main(String[] args) {
String sampleString = "101,203,405";
String[] stringArray = sampleString.split(",");
int[] intArray = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
String numberAsString = stringArray[i];
intArray[i] = Integer.parseInt(numberAsString);
}
System.out.println("Number of integers: " + intArray.length);
System.out.println("The integers are:");
for (int number : intArray) {
System.out.println(number);
}
}
}
Here is the output of the code:
Number of integers: 3
The integers are:
101
203
405

Find duplicate word from a sentence using for loop (no inbuilt function) [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
As i am new to java i got a task to find duplicate word only and its count. i stuck in a place and i am unable to get the appropriate output. I can not use any collections and built in tool. i tried the below code. Need some help, Please help me out.
public class RepeatedWord
{
public static void main(String[] args)
{
String sen = "hi hello hi good morning hello";
String word[] = sen.split(" ");
int count=0;
for( int i=0;i<word.length;i++)
{
for( int j=0;i<word.length;j++)
{
if(word[i]==word[j])
{
count++;
}
System.out.println("the word "+word[i]+" occured"+ count+" time");
}
}
}
}
Compare String with equals() not with ==
if(word[i].equals(word[j]))
== compares the refrence
equals() compares the value of that object.
Apart from that second loop should have j<word.length
Change code to
String sen = "hi hello hi good morning hello";
String word[] = sen.split(" ");
int count = 0;
for (int i = 0; i < word.length; i++) {
count = 0;
for (int j = 0; j < word.length; j++) {
if (word[i].equals(word[j])) {
count++;
}
}
if(count>1) //show only duplicate word
System.out.println("the word " + word[i] + " occured " + count + " time");
}
DEMO

Categories