Tidying code and fixing errors (java) - java

I need to modify the code so that,
its structure is better
it is more readable
it uses methods and parameters
only one statement needs to be changed if a different number of integers is to be input
My new code is at the bottom but it's not working yet, can't quite figure out what else I need to do to it. If anyone could help that would be fab.
Original Code
import java.util.Scanner;
public class MakeMeBetter
{
public static void main(String[] args)
{
int[] a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Scanner b = new Scanner(System.in);
System.out.println("Please input 10 numbers in the range 1-19 :> ");
int c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[0] = c;
int d = b.nextInt();
while (d < 1 || d > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[1] = d;
int e = b.nextInt();
while (e < 1 || e > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[2] = e;
int f = b.nextInt();
while (f < 1 || f > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[3] = f;
int g = b.nextInt();
while (g < 1 || g > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[4] = g;
int h = b.nextInt();
while (h < 1 || h > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[5] = h;
int i = b.nextInt();
while (i < 1 || i > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[6] = i;
int j = b.nextInt();
while (j < 1 || j > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[7] = j;
int k = b.nextInt();
while (k < 1 || k > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[8] = k;
int l = b.nextInt();
while (l < 1 || l > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[9] = l;
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
boolean noSwap = false;
int startAt = 0;
int stopAt = 9;
while (startAt < stopAt && noSwap == false)
{
noSwap = true;
for (int m=startAt; m<stopAt; m++)
{
if (a[m] > a[m+1])
{
int t = a[m];
a[m] = a[m+1];
a[m+1] = t;
noSwap = false;
}
}
stopAt = stopAt - 1;
}
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
double n = (a[0] + a[1] + a[2] + a[3] +
a[4] + a[5] + a[6] + a[7] +
a[8] + a[9]) / 10;
System.out.println("The minimum number is: " + a[0]);
System.out.println("The maximum number is: " + a[9]);
System.out.println("The average value is: " + n);
System.out.println("The median is: " + a[4]);
}
}
New Code
import java.util.Scanner;
import java.math.*;
public class MakeMeBetterImproved {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int array = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
int MyIntArray = array + i;
}
System.out.println("The minimum number is: " + math.min);
System.out.println("The maximum number is: " + math.max);
System.out.println("The average value is: " + math.average);
System.out.println("The median is: " + math.median);
}
}

Consider using a more dynamic structure than a primitive array.
I like ArrayLists: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Reorganize your long code into while or for loops.
An example:
ArrayList<Integer> a = new ArrayList<Integer>();
Scanner b = new Scanner(System.in);
Integer c = null;
while (a.size() != 10) {
System.out.println("Please input a number in the range 1-19 :> ");
c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
c = b.nextInt();
}
a.add(c);
}
System.out.println("\nArray contents");
for (int i=0; i<10; i++) {
System.out.print((a.get(i) < 10 ? " " : "") + a.get(i) + " ");
}
(And so on...)

Could you try this? I made a few changes.
package p2;
import java.util.Arrays;
import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int sum = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
sum += numbers[i];
}
Arrays.sort(numbers);
System.out.println("The minimum number is: " + numbers[0]);
System.out.println("The maximum number is: " + numbers[9]);
System.out.println("The average value is: " + sum / numbers.length);
System.out.println("The median is: " + median(numbers));
}
public static double median(int[] m) {
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
}

Related

Showing the whole process of GCD in Java

I'm not that new with Java (studied it years ago but stopped for 5-6 years because of work) and I'm trying to get in touch with it again. A friend of mine gave me practice problems I could work with to practice, but it is quite hard for me. It is basically showing the steps in finding GCD using Euclidean Algorithm. I did everything, but the last detail needed for the GCD is missing once I input a big number.
Here is the code I've done so far:
import java.util.Scanner;
class mpONE {
public static void main (String[] args)
{
System.out.println("Finding GCD Using Euclid's Algorithm");
Scanner num = new Scanner(System.in);
System.out.println("Enter your first (higher) number: ");
int n1 = num.nextInt();
System.out.println("Enter your second (lower) number: ");
int n2 = num.nextInt();
System.out.println("Numbers for finding GCD are: " + n1 + " " + n2);
System.out.println("Computing for GCD... ");
for (int i = 0; i <= n2; i++)
{
int g = n1/n2;
int f = (g * n2);
int h = n1 - f;
System.out.print(n1 + " = " + "(" + n2 + " * " + g + ") + " + h);
n1 = n2;
n2 = h;
System.out.println();
if (h == 0)
{
break;
}
}
for (int i = 1; i <= n1 && i <= n2; ++i) {
if (n1 % i == 0 && n2 % i == 0)
{
int ans = i;
System.out.println("Your GCD is " + ans);
}
}
}
}
With smaller numbers, it does work (the "+ h" should be 0), but with big numbers, it stops just before it shows the 0 remainder. Thanks for your help!
Just change the location of the if(h==0) block:
import java.util.Scanner;
class mpONE {
public static void main (String[] args)
{
System.out.println("Finding GCD Using Euclid's Algorithm");
Scanner num = new Scanner(System.in);
System.out.println("Enter your first (higher) number: ");
int n1 = num.nextInt();
System.out.println("Enter your second (lower) number: ");
int n2 = num.nextInt();
System.out.println("Numbers for finding GCD are: " + n1 + " " + n2);
System.out.println("Computing for GCD... ");
for (int i = 0; i <= n2; i++)
{
int g = n1/n2;
int f = (g * n2);
int h = n1 - f;
System.out.print(n1 + " = " + "(" + n2 + " * " + g + ") + " + h);
System.out.println();
if (h == 0)
{
break;
}
n1 = n2;
n2 = h;
}
for (int i = 1; i <= n1 && i <= n2; ++i) {
if (n1 % i == 0 && n2 % i == 0)
{
int ans = i;
System.out.println("Your GCD is " + ans);
}
}
}
}

Fill a 2-D array with all the factors of the numbers 1 to 1000 - java

I'm attempting to fill a 2D array with the numbers 1 to 1000 and then show all the factors of those numbers. I then need to find all the prime numbers in the same array and output them. Here's what I have so far, keep in mind that I was hoping to do every step in its own method then return them but have not got that far yet
int i = 0;
//int x = 0;
String primeNumber = "";
int[] [] factorArray = new int [1000] [];
for (int x = 0 ; x < 1000 ; x++)
{
int remainder;
int y;
remainder = x % 2;
y = x / 2;
if (remainder != 0)
System.out.println (x + ": " + "1, " + x);
else if (remainder == 0)
System.out.println (x + ": " + (y) + " , " + (y / 2) + " , " + " 1, " + x);
}
for (i = 1 ; i <= 1000 ; i++)
{
int ctr = 0;
for (int x = i ; x >= 1 ; x--)
{
if (i % x == 0){
ctr = ctr + 1;
}
}
if (ctr == 2)
{
primeNumber = primeNumber + i + " ";
}
}
System.out.print ("Prime numbers from 1 - 1000 are : \n" + primeNumber);

How to break out of a while loop in java?

// Setup dummy array
ArrayList<Integer> list = dateArray;
int counter = 1;
while (list.size() != 0) {
for (int j = 1; j < list.size(); j++)
{
//System.out.println(list.get(0) + " and " + list.get(j));
int difference = list.get(0) - list.get(j);
if (difference <6){
System.out.println(list.get(0) + " and " + list.get(j) + " and size is " +list.size() );
counter= counter +1;
System.out.println ("Counter is " + counter);
if (counter >= 4){
System.out.println ("j = " + j + " Counter =" + counter);
if (j ==list.size()-1) {
System.out.println ("here " + counter);
break;
}
}
}
}
list.remove(0);
};
Output:
1 and 2 and size is 4
Counter is 2
1 and 3 and size is 4
Counter is 3
1 and 4 and size is 4
Counter is 4
here 4
2 and 3 and size is 3
Counter is 5
3 and 4 and size is 2
Counter is 6
here 6
Ideally, i want it to stop when Counter is 4 and don't go on to execute "2 and 3 and size is 3 "
Much appreciated!
You need to use a label for the loop . Please try below snippet :
// Setup dummy array
ArrayList<Integer> list = dateArray;
int counter = 1;
outerwhileloop:
while (list.size() != 0) {
for (int j = 1; j < list.size(); j++)
{
//System.out.println(list.get(0) + " and " + list.get(j));
int difference = list.get(0) - list.get(j);
if (difference <6){
System.out.println(list.get(0) + " and " + list.get(j) + " and size is " +list.size() );
counter= counter +1;
System.out.println ("Counter is " + counter);
if (counter >= 4){
System.out.println ("j = " + j + " Counter =" + counter);
if (j ==list.size()-1) {
System.out.println ("here " + counter);
break outerwhileloop;
}
}
}
}
list.remove(0);
};
Just move the code to a method and call return. Or else, you can use something called labeled break.
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
You can use java label for that as:
int x = 1;
outerLoopLabel:
while(x != 10) {
int fact = 0;
for(int i=0;i <=x; i++) {
fact +=i;
if(fact > 25) {
break outerLoopLabel;
}
}
System.out.println("Number: "+ x + " and fact: " + fact);
++x;
}
Output without label :
Number: 1 and fact: 1
Number: 2 and fact: 3
Number: 3 and fact: 6
Number: 4 and fact: 10
Number: 5 and fact: 15
Number: 6 and fact: 21
Number: 7 and fact: 28
Number: 8 and fact: 36
Number: 9 and fact: 45
Output with label:
Number: 1 and fact: 1
Number: 2 and fact: 3
Number: 3 and fact: 6
Number: 4 and fact: 10
Number: 5 and fact: 15
Number: 6 and fact: 21
You can add a boolean variable like this:
// Setup dummy array
ArrayList<Integer> list = dateArray;
int counter = 1;
boolean isBreak = false;
while (list.size() != 0 && !isBreak) {
for (int j = 1; j < list.size(); j++)
{
//System.out.println(list.get(0) + " and " + list.get(j));
int difference = list.get(0) - list.get(j);
if (difference <6){
System.out.println(list.get(0) + " and " + list.get(j) + " and size is " +list.size() );
counter= counter +1;
System.out.println ("Counter is " + counter);
if (counter >= 4){
System.out.println ("j = " + j + " Counter =" + counter);
if (j ==list.size()-1) {
System.out.println ("here " + counter);
isBreak = true;
break;
}
}
}
}
list.remove(0);
};

number of integers in output? simple java program

I'm working on a simple java code that outputs all factors of a user-inputted number. How do I count and then display the number of factors outputted?
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
}
}
In the code above, it's the number of integers outputted in 'w' For instance, if the number inputted is 8 and its factors are 1,2,4,8, how do I write a code that says '8 has 4 factors' ?
Thanks
You simply need a variable to count factors:
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
int nFactors = 0;
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
++nFactors;
}
}
System.out.println(d + " has " + nFactors + " factors");
You need a counter variable. Here is the code:
int counter =0;
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
counter++;
System.out.println(w);
}
System.out.println(d + " has " + counter + "factors ");
Try with this code:
import java.util.Scanner;
public class EmbalzadoFactorial {
public static Scanner sc;
public static void main(String[] args) {
int Number, i;
sc = new Scanner(System.in);
System.out.print("Please Enter any number to Find Factors: ");
Number = sc.nextInt();
System.out.println("The factors are: ");
for(i = 1; i <= Number; i++) {
if(Number%i == 0) {
System.out.format(" %d ", i);
System.out.print ("and");
System.out.format("%s %n ", i);
}
}
}
}

Getting min and max values from an array - Java

import java.util.Scanner;
public class Sales {
public static void main(String[] args) {
int[] sales;
sales = getSales();
printSales(sales);
printSummary(sales);
}
private static int[] getSales() {
Scanner input = new Scanner(System.in);
int[] temp;
System.out.print("Enter the number of salespeople: ");
temp = new int[input.nextInt()];
for (int i = 0; i < temp.length; i++) {
System.out.print("Enter sales for salesperson " +
(i + 1) + ": ");
temp[i] = input.nextInt();
}
return temp;
}
private static void printSales(int[] s) {
System.out.println();
System.out.println("Salesperson Sales");
System.out.println("----------- -----");
for (int i = 0; i < s.length; i++) {
System.out.printf("%6d%12d\n", i + 1, s[i]);
}
}
private static void printSummary(int[] s) {
int sum = 0;
int max_sale = 0; // Salesperson with the most sales
int min_sale = 0; // Salesperson with the least sales
for (int i = 0; i < s.length; i++) {
sum = (s[i] + sum);
if (s[i] > max_sale)
max_sale = s[1];
else if (s[i] > min_sale)
s[i] = min_sale;
}
System.out.println();
System.out.println("Total sales: " + sum);
System.out.println("Average sales: " + (double)sum / s.length);
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
s[max_sale]);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
s[min_sale]);
}
}
The purpose of the application is to take the number of salespeople as input, along with their sales and then display individual sales, total sales, and average. That is working fine, but it's also supposed to display which salesperson had the max and minimum sales and what they were (lines 51 - 54). At the moment, any time the max is greater than the number of salespeople I get an ArrayIndexOutOfBoundsException and for whatever reason can't figure it out.
1 - Modify your for loop to get the max and min without modifying the array
2 - Try to print max and min instead of printing sum[max] and some[min] (which can throws IndexOutOfBoundsException)
3 - min_sale should be greater than 0, actually a value enough large (because you can have only positive values in your array)
To summarize :
int sum = 0;
int max_sale = Integer.MIN_VALUE; // Salesperson with the most sales
int min_sale = Integer.MAX_VALUE; // Salesperson with the least sales
for (int i = 0; i < s.length; i++){
sum = (s[i] + sum);
if (s[i] > max_sale)
max_sale = s[i];
else if (s[i] < min_sale)
min_sale = s[i];
}
System.out.println("Salesperson " +
" had the maximum sale with " +
max_sale);
System.out.println("Salesperson " +
" had the minimum sale with " +
min_sale);
if (s[i] > max_sale)
max_sale = s[1];
else if (s[i] > min_sale)
s[i] = min_sale;
Here you are trying to assign the value in s[1] to max_sales. whereas you should be assigning max_sale = i. and the if condition should be
if(s[i] > s[max_sale] )
Updated code:
for (int i = 0; i < s.length; i++)
{
sum = (s[i] + sum);
// Finds the index of the sales person with best sales
if (s[i] >= s[max_sale])
max_sale = i;
// If this sales person is not the best, then check if he is last
else if (s[min_sale] > s[i])
min_sale = i;
}
the specific problem that's causing your error is here,
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
s[max_sale]);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
s[min_sale]);
you're using your result as though it were an index
change it to the following
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
max_sale);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
min_sale);

Categories