I need help with the below problem. First I have listed the Numbers.java, and below that is my attempt at Strings.java. Please help!
Write a program Strings.java, similar to Numbers.java, that reads in an array of String objects and sorts them. You may just copy and edit Numbers.java.
package hw05;
/*
Demonstrates selectionSort on an array of integers.
*/
import java.util.Scanner;
public class Numbers {
// --------------------------------------------
// Reads in an array of integers, sorts them,
// then prints them in sorted order.
// --------------------------------------------
public static void main(String[] args) {
Integer[] intList;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("\nHow many integers do you want to sort? ");
size = scan.nextInt();
intList = new Integer[size];
System.out.println("\nEnter the numbers...");
for (int i = 0; i < size; i++)
intList[i] = scan.nextInt();
Sorting.selectionSort(intList);
System.out.println("\nYour numbers in sorted order...");
for (int i = 0; i < size; i++)
System.out.print(intList[i] + " ");
System.out.println();
}
}
My Strings class
package hw05;
/*
Demonstrates selectionSort on an array of strings.
*/
import java.util.Scanner;
public class Strings {
// --------------------------------------------
// Reads in an array of strings, sorts them,
// then prints them in sorted order.
// --------------------------------------------
public static void main(String[] args) {
String[] stringList;
String size;
Scanner scan = new Scanner(System.in);
System.out.print("\nHow many strings do you want to sort? ");
size = scan.nextLine();
stringList = new String[size];
System.out.println("\nEnter the strings...");
for (String i = 0; i < size; i++)
stringList[i] = scan.nextLine();
Sorting.selectionSort(stringList);
System.out.println("\nYour strings in sorted order...");
for (String i = 0; i < size; i++)
System.out.print(stringList[i] + " ");
System.out.println();
}
}
You're going to get an error because of this declaration here:
String size;
As you are using it later as an integer:
stringList = new String[size];
You should use Integer.parse like this:
stringList = new String[Integer.parseInt(size)];
But you are using size later again for your loops, so I would suggesting reverting it back to an int like you have in your Numbers.java. Be sure to change your scanner back to:
scan.nextInt();
Other than this, I can't see any other problems. Maybe if you posted the output and pointed out what wasn't working?
Related
I just started with Java a few weeks ago and today I've tried to write a program which is able to calculate the average IQ of numbers the user can input. I've written two classes, IQ and IQTester (IQTester = Main only). Now my problem is, whenever I want to calculate something in method compute() (e.g. the average of the array) the whole array is empty. Does anybody know how I can "pass" the array from the constructor to the method compute()?
package IQProgramm;
public class IQ {
private int values[] = new int[10];
private double average;
public IQ(String numbers) {
this.values = values;
String[] values = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < values.length; ++i) {
System.out.print(values[i] + " ");
}
System.out.println("\n");
}
public void compute() {
for (int i = 0; i < values.length; ++i) {
System.out.println(values[i]);
}
}
}
package IQProgramm;
import java.util.Scanner;
public class IQTester {
public static void main(String[] args) {
Scanner readIQ = new Scanner(System.in);
System.out.println("Please enter your numbers: ");
String numbers = readIQ.nextLine();
IQ iq = new IQ(numbers);
iq.compute();
}
}
You have 2 different arrays named values, that's why it doesn't work well.
The first defined here String[] values = numbers.split(";"); is visible only in the constructor. If you want to set the value of the one that is available in the rest of the IQ class (private int values[] = new int[10];), you need to edit this one by using
this.values[i] = Integer.parseInt(values[i])
this refers to the variable values of the class IQ.
It is a good practice not to have 2 values with same name. You can change String[] values name to valuesStr for example.
Constructor with the fix:
public IQ(String numbers) {
String[] valuesStr = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < valuesStr.length; ++i) {
this.values[i] = Integer.parseInt(valueStr[i])
System.println(this.values[i]+" ");
}
System.out.println("\n");
}
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
import java.util.*;
public class Commission {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter sales amount separated by space:");
double[] saleAmounts = Inputs(input);
}
Below is where my function scans numbers, but I need it to scan an x amount of values entered 'at the same time' to set the array length. Also, I need it so the user only enters in values once
(i have the length at 5 for a logic test)
private static double[] Inputs(Scanner sc) {
double[] sales = new double[5];
for (int i = 0; i < sales.length; i++){
sales[i] = sc.nextDouble();
}
return sales;
}
Array is a data structure with set size. If you want to have dynamic sized 'array', use List or ArrayList for example.
From the user, read an entire line (they enter values separated by spaces and hit enter), then pass that to your method and split it on space.
Something like: no exception checking included
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter sales amounts separated by spaces, then hit Enter: ");
double[] saleAmounts= Inputs(input.nextLine());
for(int i=0; i < saleAmounts.length; i++)
{
System.out.println("index " + i + " : " + saleAmounts[i]);
}
}
private static double[] Inputs(String inputLine)
{
String[] values = inputLine.split(" ");
double[] sales = new double[values.length];
for (int i = 0; i < values.length; i++)
{
sales[i] = Double.parseDouble(values[i]);
}
return sales;
}
I am stuck on how to call my method.
I get a cannot find symbols (playerName,battingArray) error message.
-Am I not calling it correctly?
-Is the method set up to populate the arrays properly?
I am not even sure if this is the best way to go about doing this.
ANY HELP IS SO GREATLY APPRECIATED!!
//Import util to accept input
import java.util.Scanner;
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//Assign number of players to variable and call method readNumPlayers
int numPlayers = readNumPlayers();
System.out.println(numPlayers);
//Call readData method
readData(playerName, numPlayers, battingArray);
}//end main
//readNumPlayers method
public static int readNumPlayers() {
System.out.println("Number of players: ");
int numPlayers = input.nextInt();
if (numPlayers <=0) {
System.out.println(" Error- Try again ");
System.out.println("Number of players: ");
numPlayers = input.nextInt();
}//end catch to ensure entry is positive integer
return numPlayers; //return
}//end readNumPlayers
//readData method
public static void readData(String[] playerName, int numPlayers,
double[] battingArray) {
playerName = new String[numPlayers];
System.out.println("Enter player's last name: ");
for (int i = 0; i < playerName.length; i++) {
playerName[i] = input.next();
} //end for loop
battingArray = new double[numPlayers];
System.out.println("Enter player's batting average: ");
for (int i = 0; i < battingArray.length; i++) {
battingArray[i] = input.nextDouble();
}// end for loop
}//end readData
}
When you pass the arrays as parameters the caller of readData is supplying references to the arrays to fill in, and, while you can affect the contents of the array referenced you can't change the reference itself — so you should not allocate arrays in your method - for example, your line:
battingArray = new double[numPlayers];
When you allocate a new array and fill that in, the caller has no access to that array, and you have not put anything in the array that the caller passed (and does have access to)
Just use the double[] battingArray parameter that the caller passed in.
Here are two versions of a very simple example; in the first the readData method allocates it's own array and fills it in. You'll see that when main prints the array content you get null because the array filled by readData is not the same array that was passed.
In the second, readData just puts values into the array that the caller passed.
First:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int count = 2;
String[] names = new String[count];
double[] avgs = new double[count];
readData(names, avgs, count);
System.out.println("names[0] in main: " + names[0]);
}
public static void readData(
String[] playerNames,
double[] battingAvg,
int numPlayers
)
{
Scanner in = new Scanner(System.in);
// allocating a new array
String[] playerNames2 = new String[numPlayers];
for (int i = 0; i < numPlayers; i++)
{
System.out.print("Players name: ");
String line = in.nextLine();
// putting the value into the newly allocated array
playerNames2[i] = line.trim();
}
System.out.println("playerNames2[0] in readData: " + playerNames2[0]);
}
}
Second:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int count = 2;
String[] names = new String[count];
double[] avgs = new double[count];
readData(names, avgs, count);
System.out.println("names[0] in main: " + names[0]);
}
public static void readData(
String[] playerNames,
double[] battingAvg,
int numPlayers
)
{
Scanner in = new Scanner(System.in);
// no array allocated this time
for (int i = 0; i < numPlayers; i++)
{
System.out.print("Players name: ");
String line = in.nextLine();
// put the value into the array that was passed
playerNames[i] = line.trim();
}
System.out.println("playerNames[0] in readData: " + playerNames[0]);
}
}
Since the caller is telling you how big the arrays are (numPlayers parameter), let's say "10", if the caller's arrays aren't actually big enough (say they did new String[5]) it's possible that you get an ArrayIndexOutOfBoundsException, so readData would probably want to catch that and return without finishing the loop.
(I've created a Java repl where you can see version 2)
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;
}