java-is this good programming? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
package com.mohamadibrah;
import java.util.Scanner;
public class Main {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(returnAverage(printNumbers(enterNumbers()))); // 10
}
public static double returnAverage(double[] array){
double result=0;
for(int i=0;i<array.length;i++) {
result += array[i];
}
System.out.println("the average is:");
return (double)result/(array.length);
}
public static double[] enterNumbers(){
System.out.println("please enter the number of values:");
int sca = sc.nextInt();
double[] myAverage = new double[sca];
System.out.println("please enter the numbers:");
for(int i=0;i<myAverage.length;i++){
double input = sc.nextDouble();
myAverage[i] = input;
}
return myAverage;
}
public static double[] printNumbers(double[] array1){
System.out.println("your numbers are:");
double[] array2 = new double[array1.length];
for(int i=0;i<array2.length;i++) {
System.out.println("the number "+i+" is:"+array1[i]);
array2[i] = array1[i];
}
return array2;
}
}
the one with the "10" in the comment
is it good programming to stack multiple methods together if everything is working fine? or is it better to keep them separated as much as possible

The issues here are debuggability and readability.
Debuggability:
When you debug such a code, it can get pretty tricky to inspect each inner method return value.
Readability:
Asside from it being hard to follow, since the reader needs to read the code from the inside out, you miss the chance to give a meaningful name to a variable that holds the inner method return value, thus explaining to the reader what it is.
Consider the following alternate code with the above points in mind:
List<Double> userChosenNumbers = enterNumbers();
Double average = returnAverage(userChosenNumbers);
System.out.println(average);

Related

Trying to print out some sequence of numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to print out a sequence of numbers using this formula
Enter a number
if number is even divide number by 2.
But if number is odd multiply number by 3 and add 1
continue doing this until number becomes 1
sample input=3
Sample output=10 5 16 8 4 2
this is what I tried but still not getting it
package victor;
import java.util.Scanner;
public class proj {
public static void main(String[] args) {
Scanner put=new Scanner(System.in);
int temp=0;
boolean notOne=true;
System.out.println("input::: ");
int num=put.nextInt();
while(temp!=1){
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
else {
temp=num;
System.out.println(temp*3+1);
break;
}
}
if(temp!=1){
notOne=false;
}
}
}
It's not working because you keep re-assigining the variable temp to the initially scanned num.
You keep checking if the initially scanned num is odd or even, when you should check if temp is odd or even.
You also break out of the loop for no reason.
And finally, you're not saving the result of the operations, you're only printing out the result.
Try to understand the points I mentioned above by noticing the differences between your code and the following:
while(temp!=1){
if (temp%2==0){
temp = temp/2;
}
else {
temp = temp*3+1;
}
System.out.println(temp);
}
You are not updating the value of temp. You are just printing it. Take the following statement
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
Here you are setting temp to num and just printing temp/2 and never setting a value.
I wrote my version of it which is a bit more simpler. I hope this will help you. You can create a string to get a better output of course.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scan.nextInt();
while (number != 1) {
number = number % 2 == 0 ? number / 2 : ((number * 3) + 1);
System.out.println("Number became " + number);
}
}
}
Try this:
public class Main
{
public static void main(String[] args) throws Exception
{
System.out.println("Starting...");
//Lets start the program, first we need
//the Scanner class to access to the input
Scanner stdin = new Scanner(System.in);
System.out.print("Type a num: ");
//I dont use: nextInt() because when asking for another input, will scan only
//the rest of the line (Maybe just \n - line break )
int num = Integer.parseInt(stdin.nextLine());
//Optional
int loops = 0;
while(num!=1){
//Pair, so num/2
if ( num %2 == 0){
num/=2;
}
else{
//num*3 +1
num=num*3 +1;
//Note that:
//1 + num*3
//Doesnt alter the result
}
System.out.println("num: "+num);
loops++;
}
System.out.println("total loops: "+loops);
}
}

need to determine the positive, negative and zero numbers in program and add all the positive and negative numbers separately [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 4 years ago.
Improve this question
I need to determine the positive, negative and zero numbers in a program and add all the positive and negative numbers separately. I'm using while loop (can use do-while) because for loop and array is not allowed. Badly need your help. Here's my code. The code should allow entering 10 numbers before determining.
public class Mix22 {
public static void main(String[] args) {
Scanner ety = new Scanner(System.in);
int count=0;
int positive=0;
int negative =0;
int num=0;
System.out.println("Enter a number: ");
num = ety.nextInt();
while(num!=10){
if(num<0)
negative++;
if (num>0)
positive++;
System.out.println("Enter a number: ");
num = ety.nextInt();
}
System.out.println("Negative numbers in the program: " + negative);
System.out.println("Positive numbers in the program: " + positive);
}
}
Is the problem that you want to run the loop 10 times? You've got a count variable that you are not otherwise using. The loop should look something like:
int count=0;
while (count != 10) {
...
++count;
}
Conventionally a for loop is used for this (if allowed):
for (int count=0; count<10; ++count) {
...
}

Creating a random output from an user input array [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 6 years ago.
Improve this question
public class decisionMaker {
public static void main(String args[]) {
String option[] = new String[10];
// Output
for (int i = 0; i <= 9; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the next option:");
option[i] = input.next();
System.out.println(" ");
}
for (int i = 0; i <= 9; i++) {
System.out.println("option: ");
System.out.println("option[i]+" ");
}
// Output
}
I'm trying to figure out how to add a count to the options, exit and end the program after entering a certain letter or number, and how to create a random output from the user input. I want it to give me one option that I had input at random. Can anyone help me with one or a few of these things. I'm trying to learn to code on my own, and I'm stuck on these.
Randomness
You can generate random numbers using java.util.Random;:
import java.util.Random;
public class SomeClass{
static Random rand = new Random();
public static void main(String args[]){
System.out.println(rand.nextInt());
}
}
About some broken code:
If you want to print out the value of a variable with System.out.println() then you need only type the variable without any quotation marks. The code you've written below will not compile:
System.out.println("option: ");
System.out.println("option[i]+" ");
Assuming that's what you want to do, it should instead be written as:
System.out.println("option: ");
System.out.println(option[i]);
Or even System.out.println("option: \n"+option[i]);
(The escape sequence \n when placed inside of quotation marks just indicates to the console to add a new line.)
Scanner:
Additionally, as nick zoum pointed out, your Scanner object should be initialized outside of the for loop, such as right underneath of the main() method.
Please comment below if you need clarification or if I misunderstood what you were looking for. It was very hard to understand your question.
You could try something like this:
public class DecisionMaker {
public static void main(String[] args) {
// output
Scanner scanner = new Scanner(System.in);
int size = getInt(scanner);
String option[] = new String[size];
for (int index = 0; index < size; index++) {
System.out.print("Enter the next option:");
option[index] = scanner.next();
}
int index = (int) (Math.random() * size);
System.out.println(option[index]);
scanner.close();
// output
}
public static int getInt(Scanner scanner) {
int size = 0;
while (size <= 0) {
if (scanner.hasNext()) {
if (scanner.hasNextInt()) {
size = scanner.nextInt();
}
}
if (size <= 0) {
System.out.println("The input: " + scanner.next() + " is not a valid value.");
}
}
return size;
}
}
How the program works:
The Scanner is initialized in the beginning and there is only
one instance of it.
Then the program will wait until the user inserts a valid number for
the size of options.
The next 5 lines were essentially copied from your code.
Finally we get a random Integer in the range of 0 - (size - 1) and print
the String of the array with that index.

How do i extract the first number [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 6 years ago.
Improve this question
so basically I want the user to do a input through the console and I want to finger out the first number and give it out on to the console, like for example:
hello465924whats334up // userinput
465924 // console output
this is basically the code that i have till now:
import java.util.Scanner;
public class ZahlZusammenFueger {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter something!");
String e = s.nextLine();
}
}
Since that number is substring, find the indexes where it begins and where it ends. Like this:
int i = 0;
int j = 0;
Scanner s = new Scanner(System.in);
System.out.println("Please enter something!");
String e = s.nextLine();
while (!Character.isDigit(e.charAt(i))) i++; // finding index
// where substring of first number starts
j = i;
while (Character.isDigit(e.charAt(j))) j++; // finding index
// where substring of first number ends
String number = e.substring(i, j));
Now, you can make Integer from it, or Long (depending on size) by doing this:
System.out.println(Integer.parseInt(e.substring(i, j)));
System.out.println(Long.parseInt(e.substring(i, j)));

MergeSort-My first DS algo in java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
package allSortings;
import java.util.Scanner;
public class MergeSort {
public static int A[],B[];
void mergeArray(int A[],int first,int mid,int last){
int i=first,j;
j=mid;
while(i<=mid && j<=last)
{
if(A[i]<A[j])
B[first++]=A[i++];
else B[first++]=A[j++];
}
while(i<=mid)
B[first++]=A[i++];
while(j<=last)
B[first++]=A[j++];
}
void copyArray(int A[],int last,int B[])
{
int i=0;
while(i<last)
{
A[i]=B[i];i++;
}
}
void splitArray(int A[],int first,int last)
{
if(first<last)
{
int mid=first+last/2;
System.out.println("first:"+first);
splitArray(A,first,mid);
splitArray(A,mid+1,last);
//mergeArray(A,first,mid,last);
//copyArray(A,last,B);
}
}
public static void main(String args[])
{
int n;
A=new int[100];
B=new int[100];
System.out.println("Enter the no. of elements in the Array:"+"\n");
Scanner input;
input=new Scanner(System.in);
n=input.nextInt();
MergeSort m1=new MergeSort();
for(int i=0;i<n;i++)
A[i]=input.nextInt();
System.out.println("\nThe Original array is:");
for(int i=0;i<n;i++)
System.out.format("%d"+" ",A[i]);
m1.splitArray(A,0,n-1);
System.out.println("\nThe Sorted array is:");
for(int i=0;i<n;i++)
System.out.format("%d"+" ",A[i]);
}
}
I keep getting at allSortings.MergeSort.splitArray(MergeSort.java:34).Guys any clue (I am new to Java, so I dont know to use a debugger)?
The value of "first" variable always gets 2 and then does not change.
You're only dividing one summand by 2, but you should divide the sum by 2 instead. Replace
int mid=first+last/2;
with
int mid=(first+last)/2;

Categories