When the user enters 0, the program is supposed to stop. I can't figure out how to do this. For example:
Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
My code prints the 0.
public class CountOccurrences {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter ten integers between 1 and 100: ");
String userInput = input.nextLine();
//this splits the user input into an array using a space
String[] inputString = userInput.split(" ");
String[] previousValues = new String[inputString.length];
int count = 1;
//Compare elements and update count for new string
for (int i = 0; i < inputString.length; i++) {
for (int j = i+ 1; j < inputString.length; j++) {
if (inputString[i].equals(inputString[j]) && notFound (previousValues, inputString[i]) { `
count++;
}
}
//Prints only unique strings
if(!userInput.equals("0")){
if (notFound(previousValues,inputString[i])) {
if (count>1) {
System.out.println(inputString[i] + " occurs " + count + " times");
} else {
System.out.println(inputString[i] + " occurs " + count + " time");
}
count = 1;
}
if (notFound(previousValues,inputString[i])) {
previousValues[i] = inputString[i];
}
}}
}
//This method returns a boolean value. It is true if the string is not in the array and vice versa
public static boolean notFound(String[] pastValues, String currentString) {
boolean valueNotFound = true;
int index = 0;
while(index < pastValues.length && valueNotFound) {
if ((pastValues!= null) &&(currentString.equals(pastValues[index]))) {
valueNotFound = false;
}
index++;
}
return valueNotFound;
}
//Method for printing an array
public static void printArray(String [] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+ " ");
}
}
}
You can do that by adding an else condition and using System.exit(0) and tell the user that the program is going to terminate.
static void exit(int status) Terminates the currently running program or Java Virtual Machine.
status 0 indicates that the program execution completed without exceptions.
You can look at the API here
Related
My problem is to count digits in a given string,
here's the code:
public static void main(String[] args) {
String s=" 1 3 4 5 22 3 2";
int[] counts=count(s);
for(int i=0;i<s.length();i++) {
if(counts[i]==1) {
System.out.println(s.charAt(i) + " appears " + counts[i] +" time");
}
else if(counts[i]!=1 && counts[i]!=0) {
System.out.println(s.charAt(i) + " appears " + counts[i] +" times");
}
}
}
public static int[] count(String s) {
int count[] = new int[99];
for(int i=0;i<s.length();i++) {
if(Character.isDigit(s.charAt(i))){
***count[i]++;***
}
}
return count;
}
the desired output is that if x appears more than once then it should say x appears n times, but my output is something like this Undesired Output
The part I've bolded out is where I localised the problem, I cannot find a way to access that if 2 appears more than once, then count[2] must also gain a +1 value, I've tried using a conversion from String to Int but nothing seemed to work. Thanks in advance!
Well, why didn't you make array of size 10 and keep data in it. Something like that:
public static void main(String[] args) {
String s=" 1 3 4 5 22 3 2";
int[] counts=count(s);
for(int i=0;i<10;i++)
if(counts[i]==1) {
System.out.println(i + " appears " + counts[i] +" time");
}
else if(counts[i]!=1 && counts[i]!=0) {
System.out.println(i + " appears " + counts[i] +" times");
}
}
public static int[] count(String s) {
int count[] = new int[10];
for(int i=0;i<s.length();i++)
if(Character.isDigit(s.charAt(i)))
count[(int)s.charAt(i) - (int)'0']++;
return count;
}
You have the correct check to see if the character is a digit, what you aren't doing correctly is incrementing the correct index. You want to convert the character to a number and use that number as your index. Try this
public static int[] count(String s) {
int count[] = new int[10];
for(int i=0;i<s.length();i++) {
if(Character.isDigit(s.charAt(i)))
{
count[Character.getNumericValue(i)]++;
}
}
return count;
}
assignment:
Write a program that reads in integers between 1 and 100 from the user and counts the
occurrences of each number. The user input ends when they enter a 0.
You must use an enhanced for-loop to solve this problem.
If a number occurs more than 1 time use the plural word “times” instead of “time”. Do not display numbers that were not entered.
I know and understand why my code's current output below appears with duplicates. The print logic is inside the for-each loop code block. If I close the code block I am no longer able to use the variables I initialized inside the loop. I have tried everything I can think of. Any suggestions would be appreciated
current output:
- 1 occurs 1 time,
- 1 occurs 2 times
- 2 occurs 1 time
- 2 occurs 2 times
- 3 occurs 1 time
- 3 occurs 2 times
needed output:
- 1 occurs 2 times
- 2 occurs 2 times
- 3 occurs 2 times
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] numbers = new int[10];
System.out.print("Enter Integers:");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = in.nextInt();
if (numbers[i] == 0) {
break;
}
}
enhancedLoop(numbers);
}
private static void enhancedLoop(int[] numbers) {
int[] counts = new int[101];
for (int value : numbers) {
counts[value]++;
if (value > 0)
if (counts[value]> 1)
System.out.println(value + " occurs " + counts[value]+ " times");
else
System.out.println(value + " occurs " + counts[value] + " time");
}
}
Variables are only available in the block in which they are declared. Move the output after the for loop and iterate over counts to display the values:
for (int i = 0, c = counts.length; i < c; ++i) {
if (counts[i] > 0) {
if (counts[i] > 1) {
System.out.println(value + " occurs " + counts[i]+ " times");
} else {
System.out.println(value + " occurs " + counts[i]+ " time");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] numbers = new int[10];
System.out.print("Enter Integers:");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = in.nextInt();
if (numbers[i] == 0) {
break;
}
}
enhancedLoop(numbers);
}
private static void enhancedLoop(int[] numbers) {
int[] counts = new int[101];
for (int value : numbers) {
counts[value]++;
if (value > 0)
if (counts[value]> 1)
System.out.println(value + " occurs " + counts[value]+ " times");
else
System.out.println(value + " occurs " + counts[value] + " time");
}
}
You can do this effectively using the below steps:
(1) Identify the unique numbers first
(2) Find the number of times each unique number occurs
So, you need to change your enhancedLoop(int[] numbers) method as shown below to achieve the result:
private static void enhancedLoop(int[] numbers) {
//convert the array to a list to make computations easier by using streams
List<Integer> numbersList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
//Get the unique numbers in the list
List<Integer> uniqueNumbers = numbersList.stream().distinct().collect(Collectors.toList());
//Now find out number of times each each unique number occured
for(int number : uniqueNumbers) {
long times = numbersList.stream().filter(num -> num == number).count();
System.out.println(number+" occurs "+times);
}
}
lets try to do this without lamdas, using simply a hashmap instead of arrays
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer>();
int tmp=0;
System.out.print("Enter Integers:");
//read a maximum of 10 int
for (int i = 0; i < 10; i++) {
tmp = in.nextInt();
//if we read a 0 we quit
if (tmp == 0) {
break;
}
//if we already saw the number we up the counter
if(numbers.containsKey(tmp)){
numbers.put(tmp, numbers.get(tmp)+1);
}else{
//otherwise we just add the new int
numbers.put(tmp, 1);
}
}
//call the print loop
enhancedLoop(numbers);
}
private static void enhancedLoop(HashMap<Integer, Integer> numbers) {
//you print what you counted
for(Map.Entry<Integer, Integer> entry : numbers.entrySet()) {
System.out.print(entry.getKey() + " occurs " + entry.getValue() + " time");
if (entry.getValue()>1)
System.out.print("s");
System.out.println("");
}
}
I have create a sample program in java .The concepts is split String value to generate Array list in one by one its means total string is input below:
Step one Total size:
Sting numberlist ="1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890........................1234567890";
ArrayList aList= new ArrayList(Arrays.asList(numberlist.split(",")));
for (int i = 0;i<aList.size();i++)
{
System.out.println(" new number-->" + aList.get(i));
// Toast.makeText(getApplicationContext(),"number is"+aList.get(i),Toast.LENGTH_SHORT).show();
}
I got the answer +alist.get(i) = 300 ,Than Step two know i having total size 300
The process is split the value one by one means
Display First 100 value 1234567890,1234567890,1234567890,.....
Display Second 100 value 1234567890,1234567890,1234567890,.....
Display Third 100 value 1234567890,1234567890,1234567890,.....
Sample programs is:
String numberlist="1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890........................1234567890";
int splitNumber = 100;
int length = numberlist.length();
ArrayList<String>splitList = new ArrayList<String>();
int splitCount = 0;
for(int i = 1 ; i<= length;i++)
{
splitCount++;
boolean last = false;
if(i==length)
{
last = true;
}
if((splitNumber == splitCount) || last)
{
String number = numberlist.substring(splitList.size()*splitNumber,i);
number = number.endsWith(",") ? number.substring(0,number.length()) : number;
number = number.startsWith(",") ? number.substring(1,number.length()) : number;
splitList.add(number);
splitCount = 0;
}
}
for(String number : splitList)
{
System.out.println();
System.out.println("Display First 100 value"+number);
}
}
but something wrong in the program don't know where is the problem anyone given me solutions.
I need my output is below:
Display First 100 value 1234567890,1234567890,1234567890,.....
Display Second 100 value 1234567890,1234567890,1234567890,.....
Display Third 100 value 1234567890,1234567890,1234567890,.....
its like one by one..
Note : sorry my grammar mistake..
Judging by your question, I assume the number of elements is divisible by splitNumber. There are a few approaches to this. Here I show one using modulo to create groups of size splitNumber and int division to get the group number:
public class Test {
public static void main(String[] args) throws Exception {
String numberlist = "1234,1234,1234,1234,1234,1234,1234,1234,1234";
int splitNumber = 3;
ArrayList<String> splitList = new ArrayList<String>(Arrays.asList(numberlist.split(",")));
if (splitList.size() % splitNumber != 0)
throw new Exception("Number of elelemnts not divisable by split number");
for (int i = 0; i < splitList.size(); i += splitNumber) {
System.out.print(((i / splitNumber) + 1) + " group of " + splitNumber +": ");
for (int j = 0; j < splitNumber; j++) {
System.out.print(splitList.get(i + j) +", ");
}
System.out.println();
}
}
}
Output:
1 group of 3: 1234, 1234, 1234,
2 group of 3: 1234, 1234, 1234,
3 group of 3: 1234, 1234, 1234,
Perform your own formatting.
If I understand the question correctly.. You can display 100 elements and whatever is leftover like this.
for (int i = 0; i < s.length(); i += 100) {
if ((i+100) > s.length()) {
System.out.println(s.substring(i, s.length()));
} else {
System.out.println(s.substring(i, i + 100));
}
}
So this code asks to input either a 1 for a pass or a 2 for a fail for ten students and it shows an error if the user inputs an invalid number. The logical error in this is for example all 10 students pass,the output is supposed to be "passed: 10 Failed:0".However, if I enter an error just once by mistake the error message will appear but the output will be"passed:9 failed:0 " even thought all 10 students passed.
import javax.swing.JOptionPane;
public class pass {
public static void main(String[] args) {
int passes = 0;
int failures = 0;
int result;
for (int studentCounter = 1; studentCounter <= 10; studentCounter++) {
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if (result == 1) {
passes = passes + 1;
} else if (result == 2) {
failures = failures + 1;
} else if ((result != 1) && (result != 2)) {
JOptionPane.showMessageDialog(null, "Error input 1 or 2");
}
}
JOptionPane.showMessageDialog(null, "Passed:" + passes + "Failed:" + failures);
System.exit(0);
}
}
It is right, as 9 have passed and 0 have failed. The error does not count in none of the groups.
The problem is in your if else logic:
Your For loop increments the integer in the condition else if((result!=1)&&(result!=2)) which means that for example, if you make 10 times a input other than 1 or 2, you'll get a result like 0 passes and 0 failed... but your loop is over....
I suggest you additionally to use the Oracle Java Code Conventions... failures ++; passes++;
You can have try with below code. Decrements student counter on invalid input.
import javax.swing.JOptionPane;
public class pass{
public static void main(String [] args){
int passes=0;
int failures=0;
int result;
for(int studentCounter = 1; studentCounter<=10; studentCounter++){
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if(result==1){
passes++;
}else if(result==2){
failures++;
} else if((result!=1)&&(result!=2)) {
studentCounter--;
JOptionPane.showMessageDialog(null,"Error input 1 or 2");
}
}
JOptionPane.showMessageDialog(null,"Passed:"+passes+" Failed:"+failures);
System.exit(0);
}
}
You can update your code like below to remove your logical error:
import javax.swing.JOptionPane;
public class pass{
public static void main(String [] args){
int passes=0;
int failures=0;
int result;
for(int studentCounter = 1; studentCounter<=10;){
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if(result==1){
passes = passes + 1;
studentCounter++
}else if(result==2){
failures = failures +1;
studentCounter++
} else {
JOptionPane.showMessageDialog(null,"Error input 1 or 2");
}
}
JOptionPane.showMessageDialog(null,"Passed:"+passes+"Failed:"+failures);
System.exit(0);
}
}
The loop is executed exactly 10 times. But if an error occurs, your code neither increases passes nor failures, and therefore passes + failures always is the amount of inputs without failures and always <= 10.
If you want to have exactly 10 results you have to make sure that there are exactly 10 correct inputs.
You can achieve this by increasing a results counter on correct inputs until it reaches 10:
int studentCounter = 0;
while(studentCounter < 10 ){
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if(result==1){
passes++;
studentCounter++;
}else if(result==2){
failures++;
studentCounter++;
} else {
JOptionPane.showMessageDialog(null,"Error input 1 or 2");
}
}
Note: Just a practice problem, not for marks.
This is a practice problem given in a first year Java course:
Design and implement an application that reads an arbitrary number of integers, by the user, that are in the range 0 to 50 inclusive, and counts how many occurrences of each are entered. After all the input has been processed, print all of the values (with the number of occurrences) that were entered one or more times.
In addition, write a method that returns no value which would compute the average of the occurrences of all numbers entered by the user.
This is what I have (I have skipped the "average occurrence" part until I clean this up):
import java.util.Scanner;
public class Main
{
public static Scanner scan = new Scanner(System.in);
public static int[] userIntegers() // this method will build the array of integers, stopping when an out-of-range input is given
{
System.out.println("Enter the number of integers to be recorded: ");
int numInts = scan.nextInt();
int[] userArray = new int[numInts];
int i = 0;
while(i < numInts)
{
System.out.println("Enter an integer between 1-50 inclusive: ");
int userInteger = scan.nextInt();
if(isValidInteger(userInteger))
{
userArray[i] = userInteger;
i++;
}
else if(isValidInteger(userInteger) == false)
{
System.out.println("Try again.");
}
}
return userArray;
}
public static void occurrenceOutput(int[] input) // this method will print the occurrence data for a given array
{
int[] occurrenceArray = new int[51];
int j = 0;
while(j < 51) // iterates through all integers from 0 to 50, while the integer in the array is equal to integer j, the corresponding occurance array element increments.
{
for(int eachInteger : input)
{
occurrenceArray[j] = (eachInteger == j)? occurrenceArray[j]+=1: occurrenceArray[j];
}
j++;
}
int k = 0;
for(int eachOccurrence : occurrenceArray) // as long as there is more than one occurrence, the information will be printed.
{
if(eachOccurrence > 1)
{
System.out.println("The integer " + k + " occurrs " + eachOccurrence + " times.");
}
k++;
}
}
public static boolean isValidInteger(int userInput) // checks if a user input is between 0-50 inclusive
{
boolean validInt = (51 >= userInput && userInput >= 0)? true: false;
return validInt;
}
public static void main(String[] args)
{
occurrenceOutput(userIntegers());
}
}
Can someone point me in a more elegant direction?
EDIT: Thanks for the help! This is where I am at now:
import java.util.Scanner;
public class simpleHist
{
public static void main(String[] args)
{
getUserInputAndPrint();
getIntFreqAndPrint(intArray, numberOfInts);
}
private static int numberOfInts;
private static int[] intArray;
private static int[] intFreqArray = new int[51];
public static void getUserInputAndPrint()
{
// The user is prompted to choose the number of integers to enter:
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of Integers: ");
numberOfInts = input.nextInt();
// The array is filled withchInteger = integer; integers ranging from 0-50:
intArray = new int[numberOfInts];
int integer = 0;
int i = 0;
while(i < intArray.length)
{
System.out.println("Enter integer value(s): ");
integer = input.nextInt();
if(integer > 50 || integer < 0)
{
System.out.println("Invalid input. Integer(s) must be between 0-50 (inclusive).");
}
else
{
intArray[i] = integer;
i++;
}
}
// Here the number of integers, as well as all the integers entered are printed:
System.out.println("Integers: " + numberOfInts);
int j = 0;
for(int eachInteger : intArray)
{
System.out.println("Index[" + j + "] : " + eachInteger);
j++;
}
}
public static void getIntFreqAndPrint(int[] intArray, int numberOfInts)
{
// Frequency of each integer is assigned to its corresponding index of intFreqArray:
for(int eachInt : intArray)
{
intFreqArray[eachInt]++;
}
// Average frequency is calculated:
int totalOccurrences = 0;
for(int eachFreq : intFreqArray)
{
totalOccurrences += eachFreq;
}
double averageFrequency = totalOccurrences / numberOfInts;
// Integers occurring more than once are printed:
for(int k = 0; k < intFreqArray.length; k++)
{
if(intFreqArray[k] > 1)
{
System.out.println("Integer " + k + " occurs " + intFreqArray[k] + " times.");
}
}
// Average occurrence of integers entered is printed:
System.out.println("The average occurrence for integers entered is " + averageFrequency);
}
}
You are actually looking for a histogram. You can implement it by using a Map<Integer,Integer>, or since the range of elements is limited to 0-50, you can use an array with 51 elements [0-50], and increase histogram[i] when you read i.
Bonus: understanding this idea, and you have understood the basics of count-sort
To calculate occurences, you can do something like this:
for(int eachInteger : input) {
occurrenceArray[eachInteger]++;
}
This will replace your while loop.