Your program should display whether the inputted integer value is found in list, how many of it is in list, and what are their locations in list?
sample
List : 1 3 2 5 7 8 5 6 9 4
Input value to search in List: 9
The value 9 is in List!
There are 4 of it in List.
Located at: list[4], list[5], list[6], list[8]
this is my code
import java.io.*;
public class List{
public static void main(String[] args){
int list[] = new int[10];
int i, num = 0, num1=0;
String input = " ";
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
for(i = 0; i < 10; i++){
list[i] = 0;
}
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
try{
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
returnvalue = b;
break;
}
}
System.out.print("Input value for list");
input = in.readLine();
num1 = Integer.parseInt(input);
}catch(IOException e){}
System.out.println("the position is" + returnvalue);
}
}
}
I think the position that is returning is not accurate can you help me?
This will do what you want... Modify the System.out.println(); part according to your need.
public static void main(String[] args) throws IOException {
int list[] = new int[10];
int i, num = 0, num1 = 0;
int returnvalue = 0;
String input = " ";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (i = 0; i < 10; i++) {
list[i] = 0;
}
for (i = 0; i < 10; i++) {
System.out.print("Input value for list[" + i + "] = ");
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
}
for (i = 0; i < 10; i++) {
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.print("Input value for checking in list ");
input = in.readLine();
num1 = Integer.parseInt(input);
boolean flag = false;
int[] arr = new int[10];
int count= 0;
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
flag = true;
arr[count]=b;
count++;
}
}
if(flag)
{
System.out.println("The value "+num1+" is in List!");
System.out.println("There are "+count+" of it in List");
System.out.print("Located at: ");
for(int j=0; j<count;j++)
{
System.out.print(" List["+arr[j]+"]");
}
}
else {
System.out.print(" Element Not found");
}
}
The Console Part for input output is...
Input value for list[0] = 4
Input value for list[1] = 5
Input value for list[2] = 6
Input value for list[3] = 4
Input value for list[4] = 5
Input value for list[5] = 6
Input value for list[6] = 5
Input value for list[7] = 4
Input value for list[8] = 4
Input value for list[9] = 6
list[0] = 4
list[1] = 5
list[2] = 6
list[3] = 4
list[4] = 5
list[5] = 6
list[6] = 5
list[7] = 4
list[8] = 4
list[9] = 6
Input value for checking in list 4
The value 4 is in List!
There are 4 of it in List.
Located at:List[0] List[3] List[7] List[8]
Fixes in your code
A try block is either with a catch block or with a finally block or both.
Having two same variables in inner and outer loop is not good. In your case the outer loop will iterate just once. I think which is not needed.
There are two nested for loop where the loop control variable is same:
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
...
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
...
So, the outer for loop will never iterate what you are expecting. Use a different loop control variable for the inside for loop.
here is my solution for your problem. no need to use that much of loops. you want to use only one foreach - How does the Java 'for each' loop work? (if you don't need to ask question again and agian). I was unable to test this lot :). But, I hope this will work.
import java.util.*;
class MyList{
public static void main(String arga[]){
int array[] = {1,3,2,5,7,8,5,6,9,4};
Scanner input = new Scanner(System.in);
// recursively ask the question
while(true){
System.out.print("Enter the value to search in list: ");
int value = input.nextInt();
System.out.println();
int i = 0;// to get the array index
int count = 0; // to get how many
String list = "Located at: ";
boolean isTrue = false; // to get entered value is in the list or not
for(int a: array){
if(a == value){
isTrue = true;
list += "list[" + i + "],";
count++;
}
i++;
}
if(isTrue){
//remove the last "," from the string
list = list.substring(0, list.length() - 1);
System.out.println("The value " + value +" is in List!");
System.out.println("There are " + count +" of it in List.");
System.out.println(list);
}else{
System.out.println("this value is not in the list");
}
}
}
}
Related
I'm finishing up a program that shows an array given from a file, then gives you the total, average, then specific totals of certain rows. The problem I'm having is that the Array has suddenly begun looping once terminated.
I'm working this in Eclipse IDE
String fileName = "";
if (args.length == 0) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name :");
fileName = sc.nextLine();
} else {
fileName = args[0];
}
File file = new File("C:\\Users\\AlaynaC\\Desktop\\2darray.txt");
try {
Scanner fin = new Scanner(file);
int size = fin.nextInt();
int[][] arr = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
arr[i][j] = fin.nextInt();
Scanner sc = new Scanner(file);
// The first line of the file contains the number of rows in the array.
int noOfRows = Integer.parseInt(sc.nextLine());
// initialize all with -1
int array[][] = new int[noOfRows][10];
for (int o = 0; o < noOfRows; o++) {
for (int g = 0; g < array[o].length; g++) {
array[o][g] = -1;
}
}
int index = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
// Each record in the file corresponds to a row in the array.
String numbers[] = line.split(" ");
// Now feeding the data into the array.
for (int o = 0; o < numbers.length; o++) {
array[index][o] = Integer.parseInt(numbers[o]);
}
index++;
}
sc.close();
// This allows the data to be printed to the console.
System.out.println("~~Array~~");
for (int o = 0; o < noOfRows; o++) {
for (int g = 0; g < array[o].length; g++) {
if (array[o][g] != -1)
System.out.print(array[o][g] + " ");
}
System.out.println();
}
}
}
System.out.println("Total: " + getTotal(arr));
System.out.println("Average: " + getAverage(arr));
System.out.println("Row Total: " + getRowTotal(arr, 3));
System.out.println("Column Total: " + getColumnTotal(arr, 2));
System.out.println("Highest in Row:" + highestInRow(arr, 2));
System.out.println("Lowest in Row:" + lowestInRow(arr, 2));
} catch (FileNotFoundException e) {
System.out.println(file.getAbsolutePath() + " is not found!");
}
}
I need the array to only display once. As of right now it is displaying multiple times once the file is entered.
When i ask the user to input a number to delete from the array it simply puts out 0 and than asks to try again i want the number to be deleted completely until the array is empty here is the code i have so far:
import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int arr[] = new int[20];
int num, found = 0,
arrSize = 10;
String choice;
Random randomGenerator = new Random();
for (int i = 0; i<10; i++)
{
arr[i] = randomGenerator.nextInt(100);
}
for(int i = 0; i<10; i++)
{
System.out.print("" + arr[i] + " ");
}
do
{
System.out.print("Number to Delete: ");
num = Integer.parseInt(keyboard.nextLine());
if(arrSize <=0)
{
System.out.println("The array is now empty");
break;
}
else
{
for (int i = 0; i<10; i++)
{
if(arr[i] == num)
{
found = 1;
}
if (found == 1)
arr[i] = arr[i + 1];
}
if (found == 0)
System.out.println("Number not found,");
else
{
arrSize--;
int i = 0;
for ( i = 0; i <arrSize; i++);
{
System.out.print("" + arr[i] + " ");
}
found = 0;
}
System.out.println(" Try again (y/n) ? ");
choice = keyboard.nextLine();
}
}while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
}
}
i want it to look something like this:
Array: 3, 63, 45
Delete NUmber: "User inputs 45"
Array: 3, 63
Issue is here:
for ( i = 0; i <arrSize; i++);
You have a semicolon after for loop. Remove that and your code works as expected.
Here is my assignment:
create an array of N random integers in the range of 1 to 100 (you can use the Java random class for this). Get the value of N from the user. Next ask the user to input a number in this range (1 to 100) and then search the array to locate all occurrences of the search number. For each occurrence, print out the number and the position at which it was found.
Then sort the array and search again, displaying all occurrences of the search number. If the search number is not found, then display a message to that effect.
Finally, print the sum of all of the numbers in the array.
I cannot figure out to how compare elements of the array to an integer. Please help! Here is what I have so far
public class Array {
public static void main(String[] args)
{
int num;
int searchNum;
int position = 0;
Scanner in= new Scanner(System.in);
System.out.println("How many random integers you want to create in range (1, 100)");
num = in.nextInt();
int[] myList = new int[num];
for (int i = 0; i < num; i++)
{
Random r = new Random();
int j = r.nextInt(101);
myList[i] = j;
}
System.out.println("Enter a number from 1-100 to search");
searchNum = in.nextInt();
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found at location: " + (position+1));
}
else
{
position += 1;
}
}
}
}
System.out.println("Enter a number from 1-100 to search");
searchNum = in.nextInt();
for (int i = 0; i < num; i++)
if (searchNum == myList[i])
System.out.println(searchNum + " found at location: " + (i+1));
You was nearly done, I believe.
public class Array {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("How many random integers you want to create in range (1, 100)");
final int num = in.nextInt();
int[] myList = new int[num];
Random r = new Random();
for (int i = 0; i < num; i++)
{
myList[i] = r.nextInt(101);
}
System.out.println("Enter a number from 1-100 to search");
final int searchNum = in.nextInt();
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found at location: " + i);
}
}
Arrays.sort(myList);
boolean any = false;
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found ");
any = true;
}
else if (searchNum > myList[i])
{
break;
}
}
if (!any)
{
System.out.println("the search number is not found");
}
}
}
can anybody help me figure out why my for loops cant print the right answer out.
Its like its skipping the first array number [0]. but if i try to make it print out my Array nr [1] out it works fine.
It must be somthing with my counter ans answer at the top.
package assignment9.pkg1;
import java.util.Scanner;
/**
*
* #author Anders
*/
public class Assignment91 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String studName = "Anders";
int counter = 1;// i think the problem is here
int answer = 1; // same
System.out.println(" welcome to student database, show informations about student" + studName);
Scanner courseScan = new Scanner(System.in);
Scanner gradeScan = new Scanner(System.in);
Scanner answerScan = new Scanner(System.in);
System.out.println(" Enter the name of courses");
String[] courseArray = new String[counter];
int[] gradeArray = new int[counter];
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
int n = gradeArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (gradeArray[j - 1] > gradeArray[j]) {
//swap the elements!
temp = gradeArray[j - 1];
gradeArray[j - 1] = gradeArray[j];
gradeArray[j] = temp;
// Swap the course array
String gradeArrayTemp;
gradeArrayTemp = courseArray[j - 1];
courseArray[j - 1] = courseArray[j];
courseArray[j] = gradeArrayTemp;
}
}
}
for (int l = 0; l < courseArray.length; l++) {
System.out.println("grade " + gradeArray[l] + "name " + courseArray[l]); // why does it not print all the array out
}
Scanner request = new Scanner(System.in);
System.out.println(" what do you want to do. Enter 1 to rename a course");
System.out.println(" enter 2 to change a grade ");
int regNumber = request.nextInt();
switch (regNumber) {
case 1: // rename a course
Scanner search = new Scanner(System.in);
System.out.println("Enter the name of the course you want to rename");
String searchCourse = search.nextLine();
for (int i = 0; i < courseArray.length; i++) {
if (searchCourse.equals(courseArray[i])) {
System.out.println("Yes there is a course named " + courseArray[i]);
System.out.println(" to change coursename insert new name");
// here i change the coursename
Scanner newName = new Scanner(System.in);
courseArray[i] = newName.nextLine();
} else {
System.out.println(" no record of this course");
}
System.out.println(" you have chosen to rename course into " + courseArray[i]);
}
}
}
}
In this section of the code:
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
note that you have used k to insert into array. the k do not update because is stuck in the inner while loop There for use another counter.
Also here
String[] courseArray = new String[counter];
you use counter to create the array. Which is 1. You are creating one eliment array.
You code will work like this:
int k = 0;
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
k++;
}
} else {
System.out.println("Sorry, there is no more memory");
}
And
for (int i = 0; i < courseArray.length; i++) {
if(courseArray[i] != null)
System.out.println("grade " + gradeArray[i] + "name " + courseArray[i]); // why does it not print all the array out
}
I have assumed that you take only 20 records depending on the loop. So i initiated arrays
String[] courseArray = new String[20];
int[] gradeArray = new int[20];
I am having a hard time with this code. The code is finished but the output is wrong.
My code prints Enter ten numbers: 1 2 3 5 6 6 8 7 4 1
It should print
The distinct numbers are:
1 2 3 5 6 8 7 4
but it doesn't. It prints:
10 10 10 10 10 7
How can I fix it?
Here is my code:
import java.util.*;
public class homework1 {
public static void main(String[] args){
// input from user
Scanner input = new Scanner(System.in);
int [] numbers = new int[10];
boolean[] distinct = new boolean[10];
System.out.println("Enter ten numbers");
for (int i=0; i<numbers.length; i++){
System.out.println("Number " + (i + 1) +": ");
numbers [i] = input.nextInt();
distinct[i] = true;
for(int j = 0;j<10; j++){
if(numbers[i] == numbers[j] && i != j) {
distinct[i] = false;
}
}
}
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=distinct.length;
count++;
}
}
System.out.println("The number of distinct number is: "+numbers[count]);
System.out.println("The distinct numbers are: ");
for(int i= 0; i < 10; i++) {
if(distinct[i]) {
System.out.print(numbers[i] + " ");
}
}
System.out.println();
}
}
This line:
numbers[count]=distinct.length;
Is setting your outputs to be the length of the array (Which in this case is hard coded to 10. Try:
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=numbers[j];
count++;
}
}
Which will set your output to be the distinct number.
Plug: Check out Code Review
This will solve your problem.
If you use HashMap, you will have less code.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> distinctNumbers = new HashMap<Integer, String>();
// input from user
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers");
for (int i = 0; i < 10; i++) {
System.out.println("Number " + (i + 1) + ": ");
Integer numberEntered = input.nextInt();
distinctNumbers.put(numberEntered, null);
}
System.out.println("The number of distinct number is: " + distinctNumbers.size());
System.out.println("The distinct numbers are: ");
Set<Integer> keys = distinctNumbers.keySet();
for (Iterator<Integer> iterator = keys.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.print(" "+ integer);
}
}
}
Remove line numbers[count] = distinct.length; This make your output are all 10
Then, I change your code a little to make it run right:
...
int count = 0;
for (int j = 0; j < 10; j++) {
if (distinct[j]) {
//numbers[count] = distinct.length; //remove it, it nonsense
count++;
}
}
// distinct number should be count, not number[count]
System.out.println("The number of distinct number is: " + count);
....
public static void main(String[] args) {
int arr[] = {1,3,5,4,7,3,4,7};
Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; i++) {
if(frequency.containsKey(arr[i])){
int value = frequency.get(arr[i]);
frequency.put(arr[i], value + 1);
}
else {
frequency.put(arr[i], 1);
}
}
for(Map.Entry<Integer, Integer> entry : frequency.entrySet()) {
System.out.println(entry.getKey());
}
}
package Chapter7;
import java.util.Scanner;
public class Exercise7_5 {
public static void main(String[] args) {
// Print distinct numbers
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers: ");
for (int i = 0, j = 0; i < 10; i++) {
if (storeDistinctNumbers(j,input.nextInt(), numbers))
j++;
}
for (int i = 0; numbers[i] != 0 ; i++)
System.out.print(numbers[i] + " ");
}
public static boolean storeDistinctNumbers(int j, int num, int[] numbers) {
for (int e: numbers) {
if (e == num)
return false;
}
numbers[j] = num;
return true;
}
}