Java Array homework [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to stack overflow and I'm trying to help a friend with their programming homework.
So far we have this
package range;
import java.util.Arrays;
import java.util.Scanner;
public class Range
{
static int[] series = new int[100];
static int seriesLength = 0;
public static void main(String[] args)
{
Scanner t = new Scanner(System.in);
boolean run = true;
while(run)
{
int option;
System.out.println("1. Loading a range of up to 100 numbers");
System.out.println("2. Showing the range of given(loaded) numbers");
System.out.println("3. Determination of the middle value of the series");
System.out.println("4. Determination of the biggest element of the series");
System.out.println("5. Determination of the smallest element of the series\n");
System.out.println("Enter the number of the option you want (1-5), or 0 to end");
option = t.nextInt();
switch(option)
{
case 1:
{
System.out.println("Please input a number from 1 -100");
seriesLength = t.nextInt();
System.out.println(seriesLength);
if((seriesLength < 1) || (seriesLength > 100))
{
System.out.println("Invalid input, series must be between 1 and 100.\nPress any key to try again.\n");
break;
}
for(int i = 0; i < seriesLength; i++)
{
series[i] = i+1;
}
break;
}
case 2:
{
System.out.println(seriesLength);
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
showSeries(series, seriesLength);
break;
}
case 3:
{
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
middleNum(series, seriesLength);
break;
}
case 4:
{
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
biggestNum(series, seriesLength);
break;
}
case 5:
{
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
smallestNum(series, seriesLength);
break;
}
case 0:
{
System.out.println("BYE, DOBRO DOBRO.");
run = false;
break;
}
default:
{
System.out.println("Invalid input");
break;
}
}
}
}
public static void showSeries(int[] input, int range)
{
for(int i = 0; i < range; i++)
{
System.out.println(input[i]);
}
}
public static void biggestNum(int[] input, int range)
{
Arrays.sort(input);
System.out.println(input[0]);
}
public static void middleNum(int[] input, int range)
{
int Middle = input.length / 2;
if ((input.length % 2) > 0)
{
System.out.println(input[Middle]);
}
else
{
System.out.println((input[Middle-1] + input[Middle]) / 2.0);
}
}
public static void smallestNum(int[] input, int range)
{
Arrays.sort(input);
for(int i = 0; i < range; i++)
{
System.out.println(input[i]);
}
}
}
The task was to write a program which works with an array of numbers using a menu
with few options. But also the task of each option needs to be a separate method and the main method needs to only show the menu and call for each method depending on the number(option) chosen. Also needs to check users errors, example if option 2 is chosen before option 1 or the chosen option doesn't exist and etc.
I'm confused on how to proceed as I'm no expert in java. How would this be done considering that the only things can be used are defined by the task

Maybe you want something more like this, Where the show series method actually sets the array, so the other methods can use the array
static int[] series = new int[100];
static int seriesLength = 0;
...
// Get the input for range
public static void showSeries(int range)
{
seriesLength = range;
series = new int[seriesLength];
for (int i = 0; i < series.legnth; i++) {
series[i] = i;
System.out.print(series[i] + " ");
}
}
Because this first method needs to be the first one called before anything, the array will be set. Then the other methods shouldn't have to take any arguments, as the array is already set, and they can just use the static array.

Related

Case 3 will not execute [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 2 years ago.
Improve this question
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
// Declare some variables you need
// -->
Scanner scan = new Scanner(System.in);
int endOption = 4;
int chosenOption = 0;
int countTo = 0;
int factorialCount2 = 0;
int lefty = 0;
do {
// Display the menu
displayMenu();
// Ask the user for one option
// -->
chosenOption = scan.nextInt();
switch (chosenOption) {
// Define four cases for different options. Don't forget "break".
// -->
case 1:
System.out.println("Enter a number: ");
countTo = scan.nextInt();
calcSum(countTo);
break;
case 2: System.out.println("Enter a number: ");
factorialCount2 = scan.nextInt();
factCont(factorialCount2);
break;
case 3: System.out.println("Enter a number: ");
lefty = scan.nextInt();
leftmostDig(lefty);
break;
case 4: System.out.println("Bye");
break;
}
} while (chosenOption<endOption);
scan.close();
}
/**
* Print the menu
*/
private static void displayMenu() {
System.out.println("Please choose one option from the following menu:");
System.out.println("1) Calculate the sum of integers from 1 to m");
System.out.println("2) Calculate the factorial of a given number");
System.out.println("3) Display the leftmost digit of a given number");
System.out.println("4) Quit");
}
private static int calcSum(int addingTo){
int sum = 0;
for(int i=1;i<=addingTo;i++){
sum = sum + i;
}
System.out.println("The sum of 1 to " + addingTo + " is " + sum);
System.out.println();
return sum;
}
private static int factCont(int number){
int multiply = 1;
for(int i=1; i<=number; i++){
multiply = multiply * i;
}
System.out.println("The factorial of " + number + " is " + multiply);
System.out.println();
return multiply;
}
private static int leftmostDig(int num){
int finalized = 0;
while(num >=10){
finalized = num/10;
}
System.out.println("The leftmost digit of " + num + " is " + finalized);
System.out.println();
return num;
}
}
So, yes this is a lab I am doing for school.. the only one that will not execute is case 3. I am not sure what exactly is happening. I tried this while I was at work on an online compiler and it worked. Now when I transfer it to the actual program I run into a snag. Let me know what you think it might be as I am very perplexed by what could be.
Your leftmostDig function contains a bug. If num is greater or equal to 10, it will never exit (it never changes the value of num). If you change it like the below, it will exit (and return the expected result).
private static int leftmostDig(int num) {
int finalized = num;
while (finalized >= 10) {
finalized = finalized / 10;
}

Java: Unreachable statement for switch using modulus operator

I am attempting to work through a hackerrank algorithm challenge which will predict the height of a tree after a series of alternating weather patterns. I'm not sure why my logic isn't working. Java says that the break points in my switch statement are not working. I have pasted the code below in full.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt(); // user input how many test cases
System.out.println("test cases set.");
int[] cycles = new int[i];
for (int x = 0; x < i; x++) {
cycles[x] = scan.nextInt(); // user input test cycles
}
for (int x = 0; x < i; x++) {
System.out.println(cycles[x]);
int temp = predictor(cycles[x]);
System.out.println(temp);
}
}
public static int predictor(int cycles) {
// determines the remainder to find even or odd cycle year
int heightRemainder = cycles % 2;
switch (heightRemainder) {
case 0:
System.out.println("Even number");
return cycles; // UNREACHABLE, cycles is a temp variable to check functionality
break;
case 1:
System.out.println("Odd number");
return cycles; // UNREACHABLE, same here
break;
}
return -1;
}
}
Yes, it will not work because your break statement is after return statement, execution control will not go to break statement.
Instead of returning in switch case use variable to store value of cycles and then return that variable at end of method, like this
public static int predictor(int cycles) {
// determines the remainder to find even or odd cycle year
int heightRemainder = cycles % 2;
int r=-1;
switch (heightRemainder) {
case 0:
System.out.println("Even number");
r =cycles;
break;
case 1:
System.out.println("Odd number");
r=cycles
break;
}
return r;
}
}
in the predictor method: remove the break; statement... that is dead code because you are returning the cycle values
switch (heightRemainder) {
case 0:
System.out.println("Even number");
return cycles; // UNREACHABLE, cycles is a temp variable to check functionality
case 1:
System.out.println("Odd number");
return cycles; // UNREACHABLE, same here
}

Java switch case menu scanner [duplicate]

This question already has an answer here:
Scanner objects in methods and NoSuchElementException [duplicate]
(1 answer)
Closed 7 years ago.
So I have a menu for the user using switch case.
public static void app() {
Scanner sc = new Scanner(System.in);
List list = list.read(file.txt);
StringBuilder menu;
int choice = 0;
do {
System.out.println(menu.toString());
choice = sc.nextInt();
switch (choice) {
case 1:
option1();
break;
case 2:
option2();
break;
case 3:
option3(list);
break;
case 4:
option4(list);
break;
case 5:
break;
default:
break;
}
} while (choice != 5);
}
The first 2 options are just methods(outside this class) that allow me to add another object to the list and I don't have any trouble with those 2. Options 3/4 also work, but it causes some issue with the switch case menu.
For options 3/4 I have to ask a certain max of the user, which I do by using a Scanner, but the same int is then also used by the switch case which leads to an error.
I get an exception in the thread "main"(which is where I call the app method) which gets printed right before the menu gets printed strangely enough and I also get a NoSuchElementException at the choice=sc.nextInt() line.
I had thought about closing the scanner right before I call the methods and reopening it afterwards, but that isn't possible.
public static void option3(list input) {
Scanner sc = new Scanner(System.in);
System.out.println(question);
int max = sc.nextInt();
int size = input.size();
if (size > 0) {
if (max == 0) {
print entire list
} else {
print list below max
}
}
sc.close();
}
You should use only one scanner for the same stream (in your case System.in). You can pass your scanner to the method and use it there:
public static void option3(list input, Scanner sc) {
System.out.println(question);
int max = sc.nextInt();
int size = input.size();
if (size > 0) {
if (max == 0) {
print entire list
} else {
print list below max
}
}
}
in your app() method:
case 3:
option3(list, sc);
break;

Final touches on my Java code?

I'm more than 90 percent done with my code... Wanna add a few things but I've got no idea how to proceed.
This is my code so far... I have other classes as well, and I'm calling them in this code.
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SensorStatsApp extends Sensor {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HumiditySensor hSensor = new HumiditySensor();
int sChoice = -2;
int hChoice = -2;
int seasonTemp = -2;
int humidityTemp = -2;
int iterations = -2;
while(true)
{
try {
System.out.println("What season would you like to simulate?");
System.out.println(" 1. Winter \n 2. Spring \n 3. Summer \n 4. Fall \n 5. Random \n 6. EXIT");
System.out.print("Selection: ");
sChoice = sc.nextInt(); // gathers user input for which season to simulate
System.out.println(); // adds a break from the previous question
if(sChoice == 6){
System.exit(0); // exits the program
}
System.out.println("What humidity would you like to simulate?");
System.out.println(" 1. Full Range \n 2. Low Humidity \n 3. High Humidity \n 4. Random \n 5. EXIT");
System.out.print("Selection: ");
hChoice = sc.nextInt(); // gathers user input for humidity to simulate
System.out.println(); // adds a break from previous question
if(hChoice == 5){
System.exit(0); // exits the program
}
System.out.print("Input number of simulations: ");
iterations = sc.nextInt(); // gathers user input for number of iterations
}
catch(InputMismatchException e) { // if user inputed non numeric characters
System.out.println(e + " - Error: expecting a number for input");
return; // exits the program
}
for(int i = 0; i < iterations; i++){
try {
seasonTemp = seasonToSimulate(sChoice); // sends the sChoice int to be converted
humidityTemp = humidityToSimulate(hChoice); // sends the sChoice int to be converted and processed
display(seasonTemp, humidityTemp, i); // displays the current iteration of information
}
catch(IOException e){
System.out.println(e + " - Error: user input"); // lets the user know why their sChoice failed.
return; // doesn't return anything cause the return type is void. This just ends the program.
}
}
}
}
public static void display(int sTemp, int hTemp, int iteration){
System.out.println();
System.out.println(++iteration + " Simulations:");
System.out.println("Season Temperature: " + sTemp);
System.out.println("Humidity Temperature: " + hTemp);
System.out.println();
}
public static int humidityToSimulate(int choice) throws IOException {
int temp = -2;
HumiditySensor hSensor = new HumiditySensor();
Boolean done = false; // if random another iteration through switch is needed
while(!done){ // if the user decides to use random then done != true so I can iterate one more time in the switch statement
switch(choice){ // sChoice is the season in terms of an int
case 1: { // full range, if choice is 1 it falls into this case and breaks at the statement break; (ends the current switch)
temp = hSensor.getHumidity();
done = true;
break;
}
case 2: { // low humidity, if choice is 2 it falls into this case.
temp = hSensor.getLowHumidity();
done = true;
break;
}
case 3: { // high humidity
temp = hSensor.getHighHumidity();
done = true;
break;
}
case 4: { // random
choice = (int) Math.random() * 3; // random times (3) for 3 humidity types
if(choice == 0) choice++; // 0 is a possibility but not an option
break;
}
case 5: { // exit
temp = -1; // lets the calling function know it's done
break;
}
default:
{
throw new IOException(); // user gave improper option
}
}
}
return temp;
}
public static int seasonToSimulate(int choice) throws IOException {
int temp = -1;
TemperatureSensor tSensor = new TemperatureSensor();
Boolean done = false; // if random through switch is needed
while(!done){
switch(choice) {
case 1: { // winter
temp = tSensor.getWinterTemp();
done = true;
break;
}
case 2: { // spring
temp = tSensor.getSpringTemp();
done = true;
break;
}
case 3: { // summer
temp = tSensor.getSummerTemp();
done = true;
break;
}
case 4: { // fall
temp = tSensor.getFallTemp();
done = true;
break;
}
case 5: { // random
choice = (int) Math.random() * 4;// random *(4) for 4seasons
if(choice == 0) choice++;// 0 is a possibility not an option
break;
}
case 6: { // exit
temp = -1; // lets the calling function know it's done
break;
}
default:
{
throw new IOException(); // user gave improper option
}
}
}
return temp;
}
}
How would I do the following in my program?
Each iteration should display the readings being generated for each temperature and humidity. At the end your program should display a summary of the simulation as follows:
Season: _________ (if random, then display Random:Summer for example)
1- First temperature generated
2- Last temperature generated
3- Lowest temperature generated
4- Highest temperature generated
5- Total sum of all temperatures generated
6- Average for the season
Humidity Type: _________ (if random, then display Random:Full for example)
1- First humidity reading generated
2- Last humidity reading generated
3- Lowest humidity reading generated
4- Highest humidity reading generated
5- Total sum of all humidity readings generated
6- Average humidity reading

Store ints into array from a file and find primes JAVA

In this interactive program, you will find a menu with options to perform different functions on an array. This array is taken from a file called "data.txt". The file contains integers, one per line. Obviously, I have not included the entire code (it was too long). However, I was hoping that someone could help me with the problem of finding the prime numbers in the array Right now, the console prints the address of the array for the primes ([I#4a13ccea). Any suggestions are welcome. Part of my program is below. Thanks.
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
private static void startMenus(Scanner sc) throws FileNotFoundException {
while (true) {
System.out.println("(Enter option # and press ENTER)\n");
System.out.println("1. Display the average of the list");
System.out.println("2. Display the number of occurences of a given element in the list");
System.out.println("3. Display the prime numbers in a list");
System.out.println("4. Display the information above in table form");
System.out.println("5. Save the information onto a file in table form");
System.out.println("6. Exit");
int option = sc.nextInt();
sc.nextLine();
switch (option) {
case 1:
System.out.println("You've chosen to compute the average.");
infoMenu1(sc);
break;
case 2:
infoMenu2(sc, sc);
break;
case 3:
infoMenu3(sc);
break;
case 4:
infoMenu4(sc);
break;
case 5:
infoMenu5(sc);
break;
case 6:
System.exit(0);
default:
System.out.println("Unrecognized Option!\n");
}
}
}
private static void infoMenu3(Scanner sc) throws FileNotFoundException {
File file = new File("data.txt");
sc = new Scanner(file);
int[] numbers = new int[100];
int i = 0;
while (sc.hasNextInt()) {
numbers[i] = sc.nextInt();
++i;
}
for (int j = 0; j < i; ++j) {
System.out.print("The numbers in the file are: " + numbers[j] + " ");
}
}
public static boolean prime(int x) {
boolean answer = true;
for (int i = 2; i <= x / 2; i = i + 1) {
if (i != x) {
if (i % x == 0) {
answer = false;
}
}
}
return answer;
}
public static int[] primes(int[] numbers) {
int primesCount = 0;
for (int i : numbers) {
if (prime(i)) {
primesCount = (primesCount + 1);
}
}
if (primesCount == 0) {
return null;
}
int[] result = new int[primesCount];
int index = 0;
for (int i : numbers) {
if (prime(i)) {
result[index] = i;
index = index + 1;
}
}
return result;
}
}
Loop through your array and print every element, or use the java.util.Arrays.toString(int[]) method if its format suits your needs.
Two marks
If you print an array like this, you will get the address of the array, not the inside.
System.out.println("The primes in the file are: " + primes(numbers));
Replace this line with a loop that iterates over primes(numbers)
The second is, in your public static boolean prime(int x) function you have this line
for (int i = 2; i <= x / 2; i = i + 1)
Although this works, to find a prime yo do not need to iterate until x / 2 . For performance benefits Square root of x would suit better.

Categories