Program will only output else statement - java

I'm working on creating a linear search in Java using the StdIn library from Princeton, and I can't figure out why my if-else statement will only print out “-1”.
It seems to me that its skipping over the if block entirely and going straight onto the else. I'm entering in my list with command-line arguments and ending the list by pressing control-d (not sure what it is on windows, sorry). Any help at all would be greatly appreciated.
public class SearchAlgs {
public static void main(String[] args) {
if (args[0].equals("linear")) {
int n = Integer.parseInt(args[1]);
LinearSearch(n);
}
else {
System.out.println("Please enter linear");
}
}
public static void LinearSearch(int n) {
int x = -1;
//int u = -1;
int c, search, array[];
int value = StdIn.readInt(); //input values
array = new int[value]; //array list
while (x < 0) {
//System.out.println(n);
//System.out.println("linear");
//loop to populate array list
for(c = 0; c < value; c++)
array[c] = StdIn.readInt();
//loop to search for "n"
for (c = 0; c < value; c++) {
if(array[c] == n){
System.out.println(n + " is at index " + c);
x++;
return;
}
else{
continue;
}
}
System.out.println("-1");
x++;
}
}
}
Edit:
I updated the entire LinearSearch(n) method. It now finds the value from the list that I enter and gives me the value of -1 when the value is not there. The problem now is that the ArrayList only populates to whatever the first number I enter is when I need to populate to however many ints are entered in the command-line argument

Your method will return (after printing -1) as soon as the searched value is not in the array:
else{
System.out.println("-1");
return; // EXITING HERE
}
so if the value entered is not the the first value in the array, you will get -1 and the method is terminated.
What you probably want is to return (after printing) as soon as the value IS FOUND, or continue searching up to the last array entry. After this loop exists, that is, nothing was found, you want to print -1 (and return/terminate).
Something like
loop array {
if value is equal array entry {
print message
return
}
// else continue looping
}
print -1

Finally after lots of effort I have completed your code.
Run program as follows java SearchAlgs 4 5 6 7
enter size:5
67546
Output would be :
6 is at index 2
7 is at index 3
5 is at index 1
4 is at index 0
Code:
import java.util.Scanner;
class SearchAlgs {
public static void main(String[] args) {
int list[]=new int[(args.length)-1];
int conv=0;
if (args[0].equals("linear")){
for(int i=0;i<(args.length-1);i++)
{
conv=Integer.parseInt(args[i+1]);
list[i]=conv;
}
LinearSearch(list);
}
else{
System.out.println("Please enter linear");
}
}
public static void LinearSearch(int n[]){
int x = -1;
int c, search, array[];
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.print("Enter size:");
int size = reader.nextInt();
array = new int[size]; //array list
while (x < 0){
//loop to populate array list
for(c = 0; c < size; c++)
array[c] = reader.nextInt();
//loop to search for "n"
for (c = 0; c < n.length; c++){
for(int z=0; z<n.length;z++){
if(array[c] == n[z]){
System.out.println(n[z] + " is at index " + z);
x++;
}
else{
continue;
}
}
}
x++;
}
}
}

Related

Else statement not printing, wondering if I am calling from setter method incorrectly in java

I'm trying to make a program in java which creates an array. I am trying to have OOP approach. I've made a class file which contains a setter method and my array:
public class MenuTestClass{
private int myMonths[];
private double average; //store average value of numbers
private boolean averageCanBeCalculated;
private int max; // store max number from array. to be calculated
public MenuTestClass(){
myMonths = new int[5];
}
public MenuTestClass(int[] myMonths){
this.myMonths = myMonths;
}
public void setMyMonths(int[] values){ //declare setter method
myMonths = values;
}
The elements of the array is taken from the user in my main method:
//Menu loop
int myMonths[] = new int[5];
int index = 0;
int num;
while(choice !=6){
switch (choice){
case 1:
int n = 1; //int n = number of projects
Scanner sc = new Scanner(System.in);
System.out.println("How many months was your project?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//if months is lesser than 2/greater than 12
if((a < 2) || (a > 12)){
System.out.println("Please enter an amount between 2 and 12 months");}
//if months is between 2 and 12 add it to the array
else{myMonths[index++] = a;}
}
calc.setMyMonths(myMonths); //creating the object
break;
I am trying to create a function which displays all the elements of the array. If the array is empty I want it to display a message stating this. However, my else statement will not run. I am trying to figure out why this is & am I calling the array incorrectly? Please see my code below:
case 2:
if(myMonths.length > 0){
// print the values
for(int i=0; i < myMonths.length; i++){
System.out.println(myMonths[i] + " ");
}
} else {
System.out.println("No values entered");
}
Any help would be great! Thanks in advance
Your code :
for(int i=0; i < myMonths.length; i++){
if(myMonths.length != 0){ //if the array is not empty display all items
System.out.println(myMonths[i] + " ");
}
else{System.out.println("No values entered");} //if array is empty display this message
}
if myMonths.length > 0 then it will check for length !!
your code should be:
if(myMonths.length > 0){
// print the values
for(int i=0; i < myMonths.length; i++){
System.out.println(myMonths[i] + " ");
}
} else {
System.out.println("No values entered");
}
UPDATE:
before you create your Array .. Ask the User for Size,
then you can check if empty or not
System.out.println("inter the size:");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] arr = new int[size];
if (arr.length > 0) {
// do your loop
System.out.println("Not Empty");
} else {
// Empty array
System.out.println("Empty");
}

How do I find the number of occurences of repeating elements in array in Java EE?

I tried writing a code fragment to find the number of occurences of a repeating element in a 1 dimensional array in Java....the counter doesnt seem to go above 1...could someone help me please..
here is my code:
import java.util.*;
public class duplicate{
public static void main(String args[]){
int i,n,c,j,m=-1;
Scanner a = new Scanner(System.in);
System.out.println("Enter the value of length");
n=a.nextInt();
int b[] = new int[n];
System.out.println("Enter the elements of the array.");
for(i=0;i<n;++i)
b[i]=a.nextInt();
for(i=0;i<n;++i){
c=0;
if(b[i]==m)
continue;
else{
m=b[i];
for(j=0;j<=i;++j){
if(b[j]==b[i])
c++;
}
System.out.println("The element"+b[i]+" has occured "+c+" times.");
}
}
}
}
There are many things sketchy with your code snippet. First of all, I would advise you to properly format your code and maybe improve some variable naming.
I took the portion of your code to show it is buggy:
for (i = 0; i < n; ++i) {
c = 0;
if (b[i] == m) {
continue;
} else {
/*
* here you always set m to the current value of the array so in the next
* iteration, your check in the "if clause" will be true what means that the
* counter will never count up if there are 2 or more consecutive equal numbers
*/
m = b[i];
for (j = 0; j <= i; ++j) {
// also this logic is flawed, because you only count the values
// before the current one
if (b[j] == b[i])
c++;
}
System.out.println("The element" + b[i] + " has occured " + c + " times.");
}
}
What i would rather advise you to use for this kind of task, is to use a HashMap and count the occurrences for each value there.
Example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of length");
int size = scanner.nextInt();
int[] values = new int[size];
System.out.println("Enter the elements of the array.");
for (int i = 0; i < size; i++) {
values[i] = scanner.nextInt();
}
Map<Integer, Integer> map = new HashMap<>();
for (int key : values) {
if (map.containsKey(key)) {
int occurrence = map.get(key);
occurrence++;
map.put(key, occurrence);
} else {
map.put(key, 1);
}
}
for (Integer key : map.keySet()) {
int occurrence = map.get(key);
System.out.println(key + " occurs " + occurrence + " time(s).");
}
}

program that reads integers between 1 and 100 and counts the occurrence of each

Write a program that reads integers between
1 and 100 and counts the occurrence of each (you should store the numbers in an array). Output should be in ascending order. Assume the input ends when the user enters a 0.
Hi guys, I know that this question has been posted before, perhaps a lot of times, but as I am a complete beginner at java, I don't completely understand the complexity of the codes that are posted. I just started taking Java classes, and would appreciate if you could help me figure out how to get my program to output the correct occurrences at the end. I'm so close to getting the answer but I can't figure it out for the life of me!! Thanks in advance!
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
//declarations
int [] myArray = new int [100];
int input = 5;
Scanner keyboard = new Scanner(System.in);
//input and processing
System.out.println("Please enter integers between 1 and 100 (enter 0 to stop): ");
while (input != 0)
{
input = keyboard.nextInt();
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] = input;
}
}
}
//output (This is where I need help!!!!)
for (int k = 0; k < myArray.length; k++)
{
if (myArray[k] != 0)
{
System.out.print(k + " occurs " + myArray[k] + " time");
if (myArray[k] > 1)
{
System.out.println("s");
}
else
System.out.println("");
}
}
keyboard.close();
}
}
You are storing the number entered by the user in the array. Instead, you should store a counter in each position of the array for the corresponding integer. When the user inputs a number, you should increase the corresponding counter.
The second part of your code (output results) seems ok. It is the first one that needs fixing.
I think the first for loop should be something like this:
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] += 1;
}
}
}
This should store add 1 to the array everytime the numbers occurs.
hey this my source code that worked out or me.
package test2;
import java.util.Arrays;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// ask for user to input numbers
System.out.println("Enter some integers between 1 and 100 (and 0 when done): ");
int[] myArray = new int[1000];//create a new array for user inputs
int number;//variable for user inputs
int count = 0;
do
{
number = input.nextInt();
myArray[count] = number;
count++;
}
while (number != 0);
int[] mySort = new int [count - 1]; //create a new array with only the numbers
for(int i = 0; i< (count-1); i++) { //get the array until 0th number into new
mySort[i] = myArray[i];
}
java.util.Arrays.sort(mySort);// sort the array in ascending order
int n = 0;
for(int i = 0; i < mySort.length; i++) {//check if the number have checked before
int occurance = 0;
if(n >= mySort[i]) {
continue;
}
else {
n = mySort[i];//if a new number found do the calculation+
for (int j=0; j<mySort.length; j++)
if (n == mySort[j])
occurance++;
System.out.print(n + " occurs " + occurance );
{
if (occurance == 1) {
System.out.println(" time.");
}
else {
System.out.println(" times.");
}
}
}
}
}
}

I have been asked to make an Create a new integer array with 16 elements

Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.

How to sum elements of a stack

import java.util.*;
public class multiple {
public static int userNumber;
public static int userChoice;
static Stack<Object> stack = new Stack<Object>();
static int[] list = new int[100];
public static void main(String[] args) {
introduction();
multiple();
printStack(stack);
}
public static void introduction() {
Scanner input = new Scanner(System.in);
System.out.print("Welcome to the program, please enter the number less than 100 that you would like "
+ "to find whoes number \nbelow have muliples of 3 and 5: ");
userNumber = input.nextInt();
System.out.println();
// System.out.println("Ok, now that youve entered," + userNumber +
// " we will find out which numbers of you number are three and five. "
// +
// "would you like the result published as a:\n 1.alist \n 2.A sum of the result \n 3.Or both?");
// userChoice = input.nextInt();
// if (userChoice >=1 && userChoice <=3)
// System.out.println( "The Computer will now program for" +
// userChoice);
// else
// System.out.println("incorrect entry for menu. Please try again");
}
public static void multiple() {
for (int i = 1; i < userNumber; i++) {
if (i % 3 == 0 || i % 5 == 0) {
stack.push(i);
}
}
}
// public static addElementsofstac
private static void printStack(Stack<Object> s) {
if (s.isEmpty())
System.out.println("You have nothing in your stack");
else
System.out.println(s);
}
}
I am trying to make a simple program that will take input for a user, find out the multiples of 3 & 5, then return the sum of the multiple. I have all the multiples discovered. I have a hunch that i need to convert the stack to an array. if so, would i just use stack.toArray()? then i would add them in a for loop?
Alternative without the need for intermediary counter variable:
int sum = 0;
while (stack.size() > 0) sum += stack.pop();
Why would you need an array?
You just need to do something along the lines of:
int sum = 0;
for(i=0;i<stack.size();i++){
sum = sum + stack.pop();
}
Though I agree with the others in that there's really no purpose of the stack itself.
EDIT: your clarification is only more confusing. How are 3, 6 and 9 multiples of 10? Are you talking about integers less than an inputted number that are multiples of 3 and 5?
I usually do this way:
ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
int ans = 0;
<...>
for (Integer n : stack) {
ans += n;
}

Categories

Resources