Problem: Write a program that reads a list of real numbers. After the program ends it should print out only the unique numbers. That is, only numbers that appear once in the list. If there are more than 50 unique numbers on the list, then you should only print the first 50.
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class Hmwk {
public static void main(String[] args) throws FileNotFoundException {
Scanner input=new Scanner (new File ("input.txt"));
int n = 0;
final int MAX_SIZE = 50;
double[] numbersArray;
while (input.hasNextDouble() && n<MAX_SIZE){
double in = input.nextDouble();
if (inList(in,numbersArray))
numbersArray[n]=in;
n++;
}
printReport(numbersArray);
}
public static boolean inList(double number, double[] list){
for (double i : list) {
if (i == number){
return false;
}
else
return true;
}
}
public static void printReport(double[] list) {
System.out.printf("The unique numbers were", Arrays.toString(list));
}
}
I'm getting errors saying that numbersArray may not have been initialized. I'm also getting an error saying that my boolean method inList must return a type boolean which confuses me because I have two options of returning true or false. Any help is much appreciated.
In fact, your variable
double[] numbersArray;
is not initialized, just declared. You can initialize it as:
double[] numbersArray = new double[MAX_SIZE];
After your comment:
It prints out "The unique numbers were" but thats it, no unique numbers
You're using
System.out.printf("The unique numbers were",Arrays.toString(list));
Two options:
Send a String parameter using %s where you want/need to print the array as string:
System.out.printf("The unique numbers were %s.",Arrays.toString(list));
Use System.out.println
System.out.println("The unique numbers were " + Arrays.toString(list));
public static void main(String[] args) throws FileNotFoundException {
Scanner input=new Scanner (new File ("input.txt"));
int n = 0;
final int MAX_SIZE = 50;
double[] numbersArray; // local variable are initialized at time of declaration
while (input.hasNextDouble() && n<MAX_SIZE){
double in = input.nextDouble();
if (inList(in,numbersArray))
numbersArray[n]=in;
n++;
}
printReport(numbersArray);
}
you have to initialize it like
double[] numbersArray = new double[SIZE];
In both cases you are not account for the fact that you might not end up inside the loop(s).
in your 1st case:
double[] numbersArray;
while (input.hasNextDouble() && n<MAX_SIZE){
double in = input.nextDouble();
if (inList(in,numbersArray))
numbersArray[n]=in;
n++;
}
what if, input does not have double from the get go? if that is the case your numbersArray never initialized. Though in more general terms even if there is a double not initializing your numbersArray will cause an exception.
in your second case:
for (double i : list)
{
if (i == number){
return false;
}
else
return true;
}
if list is empty, then there is no return statement to return from.
Hope that helps
As stated above, you need to initialize numbersArray as shown:
double[] numbersArray = new double[100]; //100 can be replaced with any integer, such as 50, 67, 62152, etc.
Try rewriting inList like this:
public static boolean inList(double number, double[] list){
for (double i : list)
{
if (i == number){
return false;
}
}
return true;
}
Related
When i am running this java code i got error. I am new to java. Can anyone help.
package raza.project.arrays;
import java.util.*;
public class arraysLearning {
public static void main(String[] args) {
int [] numbers = { 25,36,38,63,89,52,74};
double[] med = median(numbers);
}
//Return the median value of an array of numbers
//without changing the parameter array
public static double median(int[] numbers) {
int[] tmp = Arrays.copyOf(numbers, numbers.length);
Arrays.sort(tmp);
int mid = tmp.length/2; // Note: int division
if (tmp.length%2 == 0) { // even length?
return (tmp[mid-1]+tmp[mid])/2.0; //float division
}
else {
return tmp[mid];
}
}
}
java compiler is latest jdk14
This method: public static double median(int[] numbers) returns an object of type double.
When you want to call a method a get the result in a variable, you need to make sure the variable is of the same type as the type returned by the method.
You need to change this line:
double[] med = median(numbers);
With
double med = median(numbers);
Here, the variable is of type double and the method returns a double. Both types matches, the compiler is happy and your code compiles. But in your case, the type is double[] and the method returns a double object... There is no match, so your code doesn't compile
Your median() method is supposed to return a "double" value and not an array of double values.
public static void main(String[] args) {
int[] numbers = {25,36,38,63,89,52,74};
double med = median(numbers); // remove [] on this line.
}
You are returning a double value but you are returning it to a double array, there is type mismatch.
import java.util.*;
public class Test {
public static void main(String[] args) {
int [] numbers = { 25,36,38,63,89,52,74};
double med = median(numbers);
}
//Return the median value of an array of numbers
//without changing the parameter array
public static double median(int[] numbers) {
int[] tmp = Arrays.copyOf(numbers, numbers.length);
Arrays.sort(tmp);
int mid = tmp.length/2; // Note: int division
if (tmp.length%2 == 0) { // even length?
return (tmp[mid-1]+tmp[mid])/2.0; //float division
}
else {
return tmp[mid];
}
}
}
My setAverage method is getting a list of numbers to sum them up. If I give an ArrayList of lets say 200 200 200, the outcome is 600. But if I give it 200 200 250, the coutome is the same. I do not get it.
Also: I do not want to get the average now, I am at the point of just sum up the array.
import java.util.ArrayList;
public class calculation {
private ArrayList<Integer> x;
private int z;
public void setAverage(ArrayList<Integer> myList) {
x = myList;
for(int i: myList) {
z += i;
break;
}
}
public int getAverage() {
return z;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class eingaben {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation rechneAVG = new calculation();
ArrayList<Integer> myList = new ArrayList<Integer>();
while(scan.hasNextInt()) {
myList.add(scan.nextInt());
rechneAVG.setAverage(myList);
}
System.out.println(rechneAVG.getAverage());
}
}
Typically you're not looking to use a break statement in a foreach style loop, the break will terminate the loop which is what is causing your issues here.
Also I'm not a big fan of what you're doing with the setting of x to the value of the input list. Could you maybe restructure the function to return a value that is added to your list? Not really part of your question, more of an aside.
Assuming you are doing something like this before
ArrayList<Integer> list = Arrays.asList(new int[] {200,200,250});
calculation calc = new calculation();
calc.setAverage(list);
Then you should rewrite your class like this:
import java.util.ArrayList;
public class Calculation {
private ArrayList<Integer> intList;
private int avg;
public void setAverage(ArrayList<Integer> myList) {
intList = myList;
avg = 0;
for(int i: myList) {
avg += i;
}
}
public int getAverage() {
return avg;
}
}
That is: initialize z (I renamed it to avg) and ditch the break;
Also, never use break. I am fighting my own crusade to stop coders from using break/continue, but they tell me I'm crazy.
I just want to write a program that sorts 3 integers. The integers are entered from the input dialog. My code is really simple. I just need to get some data and put them in array called num. and then I create a method to sort the data by using bubble-sort logic. that method called sort. I have added command to display the sorted result with System.out.println("Sorted Result : "+Arrays.toString(num)) but that's not working.
The output just let me input data and then nothing happen.
Can anyone please tell me something I miss or what I did wrong?
Thank you.
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
for(int i=0;i<=num.length-1;i++){
for(int j=0;j<=num.length-i;j++){
if(num[j-1]>num[j]){
int temp = num[j];
num[j] = num[j-1];
num[j-1] = temp;
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
}
I believe you need a boolean flag to implement a bubble sort as you cannot know in advance how many times the loop will perform the swapping of consecutive elements.
Try this:
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
boolean swapped = true;
while(swapped){
swapped = false;
for(int i=0;i<num.length-1;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
Note that it can still be slightly improved: each time around the loop the largest number will end up as far as it can get towards the end of of the array: there's no need to check or swap till the end each time.
By using a variable as the upper limit of the index i and decreasing its value after the for loop you can reduce the total number of iterations.
int end = num.length-1;
while(swapped){
swapped = false;
for(int i=0;i<end;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
end--;
}
So currently I get a "Sum = 0.0" and a Mean equals "NaN", after fighting a lot of messages that warned agains a "possible lossy conversion from double to int". I think the code is finally taking doubles, but still does not do what I would like it to: take values from the command line, place them into an array, sum these and then calculate the mean.
Any ideas where the errors lie?
public class StudentMarks{
protected double[] marks;
//create an array filled with double values
public StudentMarks(double[] marks){
this.marks = new double[0]; //set the default array size
}
public void setMarks(){
this.marks = marks;
}
public void getArray(){
//one can only print arrays using loops..
//took me a little to realise that erm.
for(int i=0; i<marks.length; i++)
System.out.println(marks[i]);
}
public double calSum(){
double totals = 0.0;
for(double i: marks) {
//double mLength = Double.parseDouble(marks[i]);
totals+= i;
}
return totals;
}
//A method to calculate the mean of all elements
public double calMean(){
double means = (calSum()/marks.length);
return means;
}
//A main method to test
public static void main(String[] args) {
// Check to see if the user has actually sent a paramter to the method
if (args.length != 7){
System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
System.exit(-1);
}
double[] prompt = new double[args.length];
for (int i =0; i<args.length; i++){
prompt[i] = Double.parseDouble(args[i]);
}
StudentMarks test = new StudentMarks(prompt);
test.getArray();
// Calculate the sum of all the values in the array and print it
System.out.println("Sum: "+ test.calSum());
// Calculate the mean of all the values in the array and print it
System.out.println("Mean: "+ test.calMean());
}
}
Instead of
this.marks = new double[0];
use
this.marks = marks;
You are currently assigning the marks member variable to be a zero-length array rather than the parameter, so the sum of the elements is zero, and marks.length is zero, so calSum()/marks.length is 0.0 / 0.0, which is defined to be NaN.
One problem was in the initializer of the class. The class is currently initialized to a 0 length array. Instead you should initialize it with your input.
Use
public StudentMarks(double[] marks){
this.marks = marks;
}
Instead of
public StudentMarks(double[] marks){
this.marks = new double[0];
}
Here is a fixed up version of the code. Take a look at the inline comments for clarity.
public class StudentMarks{
protected double[] marks;
//create an array filled with double values
//Pass in the array of marks to initialize the class
public StudentMarks(double[] marks){
this.marks = marks; //set the marks array in the class to the passed in one
}
//Set the class marks variable to the passed in one
public void setMarks(double[] marks){
this.marks = marks;
}
//Change the name to "printMarks" to better reflect the purpose of the method
public void printMarks(){
//one can only print arrays using loops..
//took me a little to realise that erm.
for(int i=0; i<marks.length; i++){
System.out.println(marks[i]);
}
}
//
public double calSum(){
double totals = 0.0;
for(double i: marks) {
//double mLength = Double.parseDouble(marks[i]);
totals+= i;
}
return totals;
}
//A method to calculate the mean of all elements
public double calMean(){
double means = (calSum()/marks.length);
return means;
}
//A main method to test
public static void main(String[] args) {
//Print out an error and exit only if we have less than 1 element passed in
if (args.length != 7){
System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
System.exit(-1);
}
double[] prompt = new double[args.length];
//Note that there is no error checking here
for (int i =0; i<args.length; i++){
prompt[i] = Double.parseDouble(args[i]);
}
//Initialize the StudentMarks class with the value of the input
StudentMarks test = new StudentMarks(prompt);
test.printMarks();
// Calculate the sum of all the values in the array and print it
System.out.println("Sum: "+ test.calSum());
// Calculate the mean of all the values in the array and print it
System.out.println("Mean: "+ test.calMean());
}
}
I'm doing a program where user input five numbers and in the end the numbers are printed out which is working fine. What I can't get to work is a boolean function to check for duplicates. It should check for duplicates as the user write them in, so e.g. if number one is 5 and the second numbers is also 5, you should get an error until you write in a different number. Meaning if the user input a duplicate it should NOT be saved in the array. This is obviously an assignment, so I'm just asking for a hint or two.
This program is written based on pseudo-code given to me, and therefore I have to use a boolean to check for duplicates with the public boolean duplicate( int number ) class.
I've tried getting my head around it and tried something by myself, but obviously I'm doing a stupid mistake. E.g.:
if(int i != myNumbers[i])
checkDuplicates = false
else
checkDuplicates = true;
return checkDuplicates;
DuplicatesTest class:
public class DuplicatesTest {
public final static int AMOUNT = 5;
public static void main(String[] args) {
Duplicates d = new Duplicates(AMOUNT);
d.inputNumber();
d.duplicate(AMOUNT);
d.printInputNumbers();
}
}
Duplicates class:
public class Duplicates {
private int amount;
private int[] myNumbers;
private boolean checkDuplicates;
public Duplicates(int a) {
amount = a;
myNumbers = new int[amount];
}
public void inputNumber() {
for(int i = 0; i < amount; i++ ) {
int input = Integer.parseInt(JOptionPane.showInputDialog("Input 5 numbers"));
myNumbers[i] = input;
}
}
public boolean duplicate( int number ) {
<BOOLEAN TO CHECK FOR DUPLICATES, RETURN FALSE OR TRUE>
}
public void printInputNumbers() {
JTextArea output = new JTextArea();
output.setText("Your numbers are:" + "\n");
for(int i = 0; i < myNumbers.length; i++) {
if (i % 5 == 0) {
output.append("\n");
}
output.append(myNumbers[i] + "\t");
}
JOptionPane.showMessageDialog(null, output, "Numbers", JOptionPane.PLAIN_MESSAGE);
}
}
Sorry if the code tag is messy, I had some trouble with white fields in between and such. I'm new here.
Don't store the numbers in an array. Use a Set<Integer> instead. And then do a Set#contains() operation. It's O(1) operation which is actually far better than iterating over the array to search for duplicates.
Ok, if it's a compulsion to use an array, then you should modify your current approach, to return true as soon as you find a duplicate, instead of iterating over the array again. In your current approach, since you are setting the boolean variable to false in the else block, your method will return false if the last element of the array is not the same as what you are checking. So, just modify your approach to:
// loop over the array
if (number == myNumbers[i])
return true;
// outside the loop, if you reach, return false
return false;
Note that your current if statement will not compile. You are declaring an int variable there, which you can't do.
if (int i == myNumbers[i]) // this is not a valid Java code.
int nums[] = new int[5];
int count = 0;
public boolean duplicate(int number)
{
boolean isDup = false;
for (int i = 0; i <= count; i++)
{
if (number == nums[i])
{
isDup = true;
break;
}
}
if (!isDup)
{
count++;
nums[count] = number;
}
return isDup;
}