How to check character values on a String array? - java

I was asked to write a Java program which gets 5 strings from user and collects it in an array. Furthermore, I need to check every single string in the array and only print the ones who has more than four characters.
public static void main(String[] args) {
Scanner mbk = new Scanner(System.in);
int repetition[] = { 1, 2, 3, 4, 5 };
String words[] = new String[repetition.length];
for (int i = 0; i < words.length; i++) {
System.out.println("Please enter element " + repetition[i] + ":");
words[i] = mbk.nextLine();
}
}
This is the code that I have written and I'm stuck. Can anyone help?

First of all, It's a very bad practice to use variable names like mbk, the variable name should be easily understood by any other developer reading your code. It's name should reflect it's purpose. Here's a small revision of your code.
Also, Leaving a I/O stream open can cause you a big time of trouble, so i have also added the scanner.close statement.
public static void main(String[] args) throws Exception {
Scanner userInput = new Scanner(System.in);
int maxArrayLength[] = { 1, 2, 3, 4, 5 };
String words[] = new String[maxArrayLength.length];
for (int i = 0; i < words.length; i++) {
System.out.println("Please enter element " + maxArrayLength[i] + ":");
words[i] = userInput.nextLine();
}
for(int lengthCheckCounter = 0; lengthCheckCounter < words.length; lengthCheckCounter++)
if(words[lengthCheckCounter].length() > 4)
System.out.println(words[lengthCheckCounter] + "-" + words[lengthCheckCounter].length());
userInput.close();
}
Another way of closing the I/O stream/resources could be to use try-with-resources block featured since JDK 1.7. Then we can write your code as follows:
try(Scanner userInput = new Scanner(System.in)) {
// All other code
}
If you are on JDK 1.8, you can use a single line to do everything as suggested in Lonely Neuron's comment:
// Initialize your words array here
// Take user input
// Print words greater than 4 using JDK 1.8 Filter below
Arrays.stream(words).filter(s -> s.length() > 4).forEach(System.out::println)

Yo, I gotchu:
this goes through the entire list, and prints anything that has a greater length than 4.
for (int i = 0; i < yourArray.length; i++) {
if (yourArray[i].length() > 4) {
System.out.println(yourArray[i]);
}
}

Use the length() method
for(String s: words){
if(s.length()>=4){
System.out.println(s);
}
}

words[j].length() will give you the length of the string in index j of your array. I am leaving you to compare it to 4, And to introduce a variable j (you may call it i again or any other name you find fitting).

import java.util.Scanner;
public class StackOf4 {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
String[] names=new String[5];
for(int i=0;i<5;i++) {
System.out.println("Enter a string:");
names[i]=scn.nextLine();
}
System.out.println("The strings with more than 4 characters are: ");
for(int i=0;i<5;i++) {
if(names[i].length()>4)
System.out.println(names[i]);
}
}
}

Related

I am not sure why the code will not output any statements. When I run it in my IDE nothing is outputted

package Fall21;
import java.util.Scanner;
public class BalloonRideWeight {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int personWeight = sc.nextInt();
int totalWeight = 0;
for (int i=0; i<n; ++i) {
totalWeight +=personWeight;
personWeight =sc.nextInt();
}
if (totalWeight >500)
System.out.println("Everyone too fat.");
else
System.out.println("Just right.");
sc.close();
}
}
would this be a runtime issue ???
I am just learning basics so any answers with arrays and more complex levels of code are not needed.
It probably doesn't output anything because u are using Scanner which expects input. When I run your program and I enter the following input
1
1
1
I get as output
Just right.
Each of these invocations
sc.nextInt();
expects you to enter an input that gets stored in the declared variable (left hand side of the statement).
So with my first two inputs, the values
n = 1, personWeight = 1
then the loop iterates 1 time, which contains another scanner invocation setting the personWeight. Which I again set to 1.
Only then it reaches the if condition that prints something to the console. See this for more info: https://www.w3schools.com/java/java_user_input.asp
EDIT:
If you want to parse multiple ints from one line, u can do:
String[] arguments = scanner.nextLine().split(" ");
int[] ints = new int[arguments.length];
for (int i = 0; i < ints.length; i++) {
ints[i] = Integer.parseInt(arguments[i]);
}
Or a fancier version:
int[] ints = Arrays
.stream(scanner.nextLine().split(""))
.mapToInt(Integer::parseInt)
.toArray();

if loop is not working? can anyone help me

public class meaingCompare {
public static void main(String[] args) {
int cnt = 0;
String st1, u, st2;
st2 = "funny";
int n = 5;
System.out.println("Enter the string");
Scanner in=new Scanner(System.in);
st1 = in.nextLine();
String[] v = st1.split("\\s+");
for(int i = 0; i < st1.length(); i++) {
if(v[i].equalsIgnoreCase(st2))
cnt++;
}
if(cnt>=4)
System.out.println(" match found");
}
}
I am just a beginner in java.I want to get the output as match found if the no: of words in the input string match the word funny is greater than 4 but the if loop is not working.
Your stop condition in the for loop is wrong: since you're looping on the array of strings v you should stop when you've reached the last element. Modify:
for(int i=0;i<st1.length();i++)
to:
for(int i=0;i<v.length;i++)
when traversing due to this st1.length() we get ArrayIndexOutofBoundException so compare with array length instead of strings length.
This works:
public static void main(String[] args)
{
int cnt=0;
String st1,u,st2;
st2="funny";
int n=5;
System.out.println("Enter the string");
Scanner in=new Scanner(System.in);
st1=in.nextLine();
String[]v=st1.split("\\s+");
for(int i=0;i<v.length;i++)
{
if(v[i].equalsIgnoreCase(st2))
cnt++;
}
if(cnt>=4)
System.out.println(" match found");
}
}
First of all, there is no such thing as an if loop. You have a for loop.
Your problem is that in your for loop, you check if i is less then the length of the String st1. However you need to check if I is less then the length of the array v. So, change this statement:
for(int i = 0; i < st1.length(); i++)
to this:
for(int i = 0; i < v.length; i++)
Hope this helped.

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

writes several line to standard out put in reverse order

I want to write a program in java that takes all the lines input to standard input and writes them to standard output in reverse order.
this is may code but it has an error and I can't understand where is the problem
(In this program at first I ask for the number of lines and then save it in 'n'.)
any help?
thanks in advance
package getLine;
import java.util.Scanner;
public class S {
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("how many lines do you want to enter");
int n= s.nextInt();
String [] str;
str= new String[n];
for(int i=0;i<n;i++)
str[i]=s.nextLine();
for(int i=n;i>=0;i--)
System.out.println(str[i]);
}
}
Why don't you use a Stack<String> to buffer the lines? Then simply pop every line and output it.
Following is the code with output:
import java.util.Scanner;
public class S {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("how many lines do you want to enter");
int n = s.nextInt();
System.out.println("I want to enter " + n + " lines ");
n = n + 1;
String[] str;
str = new String[n];
int count = 0;
for (int i = 0; i < n; i++) {
str[i] = s.nextLine();
System.out.println(str[i]);
count++;
}
if (count == n) {
System.out.println("Reversed output");
for (int i = n - 1; i >= 0; i--) {
System.out.println(str[i]);
}
}
}
Output:
how many lines do you want to enter
2
I want to enter 2 lines
1
1
2
2
Reversed output
2
1
for(int i=n-1;i>=0;i--)
System.out.println(str[i]);
Do you get ArrayIndexOutOfBoundsException? The error lies here:
for(int i=n;i>=0;i--)
System.out.println(str[i]);
In the first step of that loop you attempt to print str[n], which doesn't exist.
Your array consists of n elements numbered from 0 to n-1.
The proper code is:
for(int i = n - 1; i >= 0; i--)
System.out.println(str[i]);
You need to start from n-1 because the maximum index accessible in an array is array.length-1.
for(int i=n-1;i>=0;i--){
Also you need to make this change:-
int n= Integer.parseInt(s.nextLine());
s.nextInt() reads the next integer all right, but the enter you hit after that, is consumed as the first element of your array. To avoid that, you can do as I mentioned above.
You don't have to do much to handle this, just replace your line in a code by the following code-
int n = s.nextInt()+1;

how to take user input in Array using java?

how to take user input in Array using Java?
i.e we are not initializing it by ourself in our program but the user is going to give its value..
please guide!!
Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
See also:
Why is it preferred to use Lists instead of Arrays in Java?
Fill a array with List data
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
import java.util.Scanner;
class bigest {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("how many number you want to put in the pot?");
int num = input.nextInt();
int numbers[] = new int[num];
for (int i = 0; i < num; i++) {
System.out.println ("number" + i + ":");
numbers[i] = input.nextInt();
}
for (int temp : numbers){
System.out.print (temp + "\t");
}
input.close();
}
}
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.
The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's main method.
Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.
If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.
Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.
**How to accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
This is my solution if you want to input array in java and no. of input is unknown to you and you don't want to use List<> you can do this.
but be sure user input all those no. in one line seperated by space
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();

Categories

Resources