I'm trying to have a program where the user enters names and they are put into an array. Then they should be ordered in ascending order by using Selection Sort. I tried doing this but it doesnt compile. Any ideas why?
Thanks!
import java.util.*;
public class SuperHeros{
public static void main(String[]args){
Scanner in=new Scanner(System.in);
System.out.println("Enter 5 Super Hero Names");
String name=in.nextLine();
String[] Super=new String[5];
int min=0;
for(int i=0; i<Super.length; i++){//Enter Names in unordered list
Super[i]=in.nextLine();
System.out.println(Super[i]);
min=i;
for(int j=i+1;j<Super.length;j++){// Have an ascending list
int temp=Super[i];
Super[i]=Super[j];
Super[i]=temp;
System.out.println(Super[i]);
}
}
}
}
You are attempting to assign a String into an int value at int temp = Super[i]. Also the way you setup your prints and in.nextLine() calls were causing issues when running the program.
import java.util.*;
public class Test{
public static void main(String[]args){
Scanner in=new Scanner(System.in);
String[] Super=new String[5];
for(int i=0; i<Super.length; i++){//Enter Names in unordered list
System.out.println("Enter Super Hero Name: ");
Super[i]=in.nextLine();
}
// Selection sort
for (int j = 0; j < Super.length - 1; j++){
int min = j;
for (int k = j + 1; k < Super.length; k++){
if (Super[k].compareTo(Super[min]) < 0){
min = k;
}
String temp = Super[j];
Super[j] = Super[min];
Super[min] = temp;
}
}
System.out.println(Arrays.toString(Super));
}
}
Related
I'm not that new to programming, but I had a problem when storing the user input to the string array and store it into an int array. Does anybody know how to fix my code? Or is there any other way?
I want to store this input into a separate int array and a string array.
User input:
"T 3"
"V 4"
"Q 19"
Expected result:
num[0] = 3
num[1] = 4
num[2] = 19
store[0] = "T"
store[1] = "V"
store[2] = "Q"
This code creates an index out of bounds:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i = 0; i < k; i++)
{
String[] paint = input.next().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
]//end class
input.next() will only work if you took String data type but here you had taken int as the data type so it won't work here.
The problem is that you're calling input.next() which returns the next token, delimited by spaces. Therefore, the token itself can't contain any spaces. So the .split(" ") method call will always return a one-element array, so there is only a paint[0] and there is no paint[1]. It's not clear what you're trying to achieve in your code; if you expand the question, you may get some more answers.
Update: now that you've shown us your input and expected results, I think what you need to do is:
store[i] = input.next();
num[i] = input.nextInt();
Try this out
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i=0; i<k; i++){
String s = sc.nextLine();
String str = sc.next();
int number = Integer.parseInt(sc.next());
num[i]=number;
store[i]=str;
}
for(int i=0; i<k; i++){
System.out.println(store[i] +" "+num[i]);
}
}
}
Check this. Minor changes done in your code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = Integer.parseInt(input.next());
int[] num = new int[k];
String[] store = new String[k];
input.nextLine();
for(int i = 0; i < k; i++)
{
String paint[] = input.nextLine().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
}//end class
The first for-loop you see does not execute and I'm not sure why. It is completely ignored, I tried it in a separate method and I tried it in the main method but something seems to be ignoring but I'm not sure how to get it to run, it simply goes to the next method run in the main method.
package math;
import java.util.Scanner;
public class mathAverageValue {
static int numOfVals;
static double total;
static double average;
static double[] arr = new double[numOfVals];
static String boole;
public static void input() {
Scanner s = new Scanner(System.in);
System.out.println("How many values will be averaged ? : ");
numOfVals = s.nextInt();
for(int i=0; i<arr.length; i++){
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
}
public static void process() {
for (int i=0; i < arr.length; i++) {
total = total + arr[i];
}
average = total / arr.length;
}
public static void output() {
System.out.println("Your average is : " + average);
System.out.println("Would you like to average again? Y or N : ");
Scanner i = new Scanner(System.in);
boole = i.next();
if ("Y".equals(boole)) {
input();
output();
}
}
public static void main(String[] args) {
input();
output();
}
}
Assign some value to static int numOfVals. Java by default assign 0 to it. Hence your for loop will never run. Also modify your array declaration like below:-
static double arr = new double[numOfVals];
The problem is that you have assigned a value to numOfVals and then created the array in the wrong order.
public static void input() {
Scanner s = new Scanner(System.in);
System.out.println("How many values will be averaged ? : ");
numOfVals = s.nextInt();
arr = new double[numOfVals]; // <-- PUT THIS HERE
for(int i=0; i<arr.length; i++){
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
}
It is ignored because it is a zero length array:
static int numOfVals; // This implicitly equals 0.
static double total;
static double average;
static double[] arr = new double[numOfVals]; // so this has no elements.
hence
for(int i=0; i<arr.length; i++){ //arr.length is 0
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
doesn't iterate
According to java primitive data types initialization, all types have a default value. In your case, static int numOfVals will be assigned with 0. This is the reason why the for loop is ignored. see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
package array;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = input.nextInt();
}
System.out.println(a);
}
}
You cannot print an array directly, you have to iterate through it's values.
for (int j=0;j<a.length;j++){
System.out.println(a[j]);
}
In my program the user determines the size on an array, then the user inputs values that are stored in descending order in the array as 'high scores'. The user then gets the option to update values in the array, although for my function which performs this task (insertScore) it doesnt print out the right values.
If:
240
110
50
is stored, and the user decides to update the values, by inserting 150, the array should update to be
240
150
110
and 50 will be removed, although for some reason when i run my code i keep getting '[Ljava.lang.Integer;#55f96302'? I have no idea why this is happening, and I have searched everywhere to find a way to fix this although i cant seem to find anyone else who has had that problem...
I know my error is mainly persisting in the insertScore function, but i cant find a reason why?
this is my code, thanks for any and all help:
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class HighScores {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many values would you like to set the High Score list too?:");
int userInput = input.nextInt();
Integer[] zeroSet = {};
Integer[] setScores = intialisingHighScores(userInput, zeroSet);
System.out.println("Now Enter the high scores you wish to display:");
Integer[] highScores = printHighScores(setScores, userInput);
System.out.println("The high scores are:");
for (int i=0; i<=(userInput-1); i++){
System.out.println((i+1) + ". " + highScores[i]);
}
while (userInput > 0){
setScores = insertScore(userInput, setScores);
}
}
public static Integer[] intialisingHighScores(int userInput, Integer[] zeroSet){
zeroSet = new Integer [userInput];
for (int index=0; index<=(userInput-1); index++){
zeroSet[index] = 0;
}
return zeroSet;
}
public static Integer[] printHighScores(Integer[] setScores, int userInput) {
Scanner inputNo = new Scanner(System.in);
for (int i=0; i<=(userInput-1); i++){
int scores = inputNo.nextInt();
if(scores<0){
System.out.println("No player can be that bad, please enter positive high scores only");
scores = inputNo.nextInt();
setScores[i] = scores;
}
else{
setScores[i] = scores;
}
}
Arrays.sort(setScores, Collections.reverseOrder());
return setScores;
}
public static int higherThan(Integer[] setScores){
Scanner inputNo = new Scanner(System.in);
System.out.println("Please enter any updated scores");
int newScore = inputNo.nextInt();
return newScore;
}
public static Integer[] insertScore(int userInput, Integer[] setScores){
int newScore = higherThan(setScores);
for (int i=0; i<=(userInput-1); i++){
if(setScores[i] < newScore ){
for (int n=(userInput-2); n>i; n--){
setScores[n+1] = setScores[n];
}
setScores[i] = newScore;
for(int loop=0; loop<=(userInput-1); loop++){
System.out.println(setScores);
}
}
}
return setScores;
}
}
When you use System.out.println(setScores);, you're calling the toString method of an array. By default, toString returns a String formatted as class name # hex hashcode. If you want a more readable representation of the array, use Arrays#toString:
System.out.println(Arrays.toString(setScores));
You are printing the array directly which uses the toString and gives you className#hashCode.
As you are looping thru the list you might want to use the following:
public static Integer[] insertScore(int userInput, Integer[] setScores){
int newScore = higherThan(setScores);
for (int i=0; i<=(userInput-1); i++){
if(setScores[i] < newScore ){
for (int n=(userInput-2); n>i; n--){
setScores[n+1] = setScores[n];
}
setScores[i] = newScore;
for(int loop=0; loop<=(userInput-1); loop++){
System.out.println(setScores[loop]); //***EDITED***//
}
}
}
return setScores;
}
I'm trying to print out the frequency of each integer in an array
import java.util.*;
public class NumFrequency {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount of numbers your going to input, up to 50");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the "+ num + " numbers now.");
for (int i=0 ; i<array.length; i++) {
array[i] = input.nextInt();
}
System.out.println("array created");
printArray(array);
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i=0; i<n; i++) {
System.out.print(arr[i]+" ");
}
}
private static int[] intFreqArray = new int[51];
public static void FreqOfInt(int[] array, int num) {
for (int eachInt : array) {
intFreqArray[eachInt]++;
}
for (int m = 0; m<intFreqArray.length; m++) {
if (intFreqArray[m] > 1) {
System.out.println(m+ " occurs " + intFreqArray[m] + " times.");
}
}
}
}
It'll print out the array created by the user but nothing after that I'm lost as to why it wont print out the last part.
You need to call FreqOfInt before you print.
Note that we normally use lower case letters for the names of Java methods.
In main, the last method call is to printArray, but you never call FreqOfInt. That's why that output doesn't show up.
Call it after calling printArray.