I am having trouble understanding how to remove a letter from a char array here is my code
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String [] args)
{
start();
}
public static void start()
{
Scanner scan = new Scanner(System.in);
Random rand = new Random();
String [] Words = {"Dog","cat","Food","Bacon","Turkey","hood","poo","Good","look"};
String RandomWord = Words[rand.nextInt(Words.length)];
char [] array = RandomWord.toCharArray();
boolean [] parrallelArray = new boolean[array.length];
int i = 0;
int placeholder = 0;
System.out.println(findUniqueLetters(array));
char input = 0;
while(i<findUniqueLetters(array)){
i++;
System.out.println("You have a "+RandomWord.length()+" Word "+RandomWord);
System.out.println("Guess a letter : ");
input = scan.next().charAt(0);
for(int j = placeholder; j<array.length;j++){
if(input == array[j]){
j++;
placeholder = j;
System.out.println("You got it right");
break;
}
else if(!(input ==array[j])){
j++;
placeholder = j;
System.out.println("You got it wrong");
break;
}
}
}
System.out.println("You have wasted all your tries!");
}
public static int findUniqueLetters(char [] a){
int Unique = 1;
for(int i = 1; i<a.length;i++){
if(!(a[i] == a[i-1])){
Unique++;
}
}
return Unique;
}
}
Is there another way to do this or is deleting it the only way to do this?
I have tried to switch the repeated letter in the array with the non repeated one in the array but that only works for some words.
Please use a Set. more here - > http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Related
My task is to read the strings by input, and then display the strings that have more than 4 vowels in each. I have this code:
import java.util.Scanner;
public class Main {
static boolean vowelChecker(char a) {
a = Character.toLowerCase(a);
return (a=='a' || a=='e' || a=='i' || a=='o' || a=='u' || a=='y');
}
static int counter(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++)
if (vowelChecker(str.charAt(i))) {
++count;
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
int n;
n=scanner.nextInt();
String[] array = new String[100];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
array[i]=scanner.nextLine();
}
String str = scanner.nextLine();
int b = counter(str);
if (b > 4) {
System.out.println("What do I write here?");
}
}
}
And my question is: how to correctly write the code so that the output would be strings from input that have more than 4 vowels?
import java.util.Scanner;
public class Test {
private static final char[] VOWELS = new char[]{'a', 'e', 'i', 'o', 'u', 'y'};
public static void main(String[] args) {
// Initialize and open a new Scanner
final Scanner scanner = new Scanner(System.in);
// Get the number of lines we want to analyze
System.out.print("Enter the number of elements you want to store: ");
final int n = Integer.parseInt(scanner.nextLine());
// Get all the lines from the user
System.out.println("Enter the elements of the array: ");
final String[] lines = new String[n];
for(int i = 0; i < n; i++) {
lines[i]=scanner.nextLine();
}
// Close the Scanner
scanner.close();
// Check each line, count the number of vowels, and print the line if it has more than 4 vowels.
System.out.println("\nInputs that have more than 4 vowels");
for(int i = 0; i < n; i++) {
if (countVowels(lines[i]) > 4) {
System.out.println(lines[i]);
}
}
}
private static boolean isVowel(char a) {
for (int i = 0; i < VOWELS.length; i++) {
if (Character.toLowerCase(a) == VOWELS[i]) {
return true;
}
}
return false;
}
private static int countVowels(final String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (isVowel(str.charAt(i))) {
count++;
}
}
return count;
}
}
Like others have pointed out, you never read from the array.
Read for each of the strings, if the counter() returns a value larger than 4, we want to print it. So, this could do the trick:
for(int i=0; i<n; i++)
{
if (counter(array[i]) > 4)
System.out.println(array[i]);
}
Using nextInt won't absorb the newline character \n, that's why you are inputting 1 string less. There are some workarounds that you can read about here.
So this first part makes sense :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store:
");
int n;
n=scanner.nextInt();
String[] array = new String[100];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
array[i]=scanner.nextLine();
}
after this part I would just do :
for (String s: array) {
if (Objects.isNull(s))
break;
if (count(s) >= 5) {
System.out.println(s);
}
}
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
class Main {
static long counter(String str) {
return Arrays.stream(str.split(""))
.filter(c -> Arrays.asList("a", "e", "i", "o", "u", "y").contains(c.toLowerCase()))
.count();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
int n;
n = scanner.nextInt();
scanner.nextLine();
String[] array = new String[n];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
String str = scanner.nextLine();
if (counter(str) > 4) {
array[i] = str;
}
}
System.out.println(Arrays.toString(Arrays.stream(array).filter(Objects::nonNull).toArray(String[]::new)));
}
}
I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps
I present three random letters to the user, lets say ' J U D ' and my user has to give a word for each letter starting with the assigned random letter, for example:
"Just Use Data".
I have been unsuccessful searching for how to validate that the user's input starts with the assigned random letter.
My code
public static void generateLetters(){
Random randomLetter = new Random();
int i;
char[] letter = {'A', 'B', 'C', 'D', 'E', 'F'};
// It's A-Z, but for typing sake... you get the point
char[] letters = new char[26];
for(i = 0; i <= 3; i++){
letters[i] = letter[randomLetter.nextInt(26)];
System.out.printf(letters[i] + " ");
}
}
The above block will generate letters randomly and works fine. Below, I'll enter basically what I have for the user input.
public static String[] getWord(String[] word){
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
return word;
}
Simple thus far and this is my main function:
public statc void main(String[] args){
generateLetters();
getWord();
}
I need to take the string returned from getWord() and verify that each word input does begin with the randomly assigned letters. I've been unsuccessful in doing this. All of the syntax I find during my online research just gets me confused.
generateLetters() should return the generated letters.
getWord() doesn't actually do anything with the user input. Make it return a String that contains the user input.
You can use a separate method to validate the input.
Here's a fixed version of your code.
public static void main(String[] args) {
char[] letters = generateLetters();
System.out.println(letters);
String input = getWord();
System.out.println("Input is " + (isValid(letters, input) ? "valid" : "invalid"));
}
public static boolean isValid(char[] letters, String input) {
String[] words = input.split(" ");
for (int n = 0; n < words.length; n++)
if (!words[n].startsWith("" + letters[n]))
return false;
return true;
}
// Here're the fixed versions of your other two methods:
public static String getWord(){
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
wordInput.close();
return inputWord;
}
public static char[] generateLetters(){
Random randomLetter = new Random();
char[] letter = new char[26];
char c = 'A';
for (int i = 0; i < 26; i++)
letter[i] = c++;
char[] letters = new char[26];
for(int i = 0; i < 3; i++)
letters[i] = letter[randomLetter.nextInt(26)];
return letters;
}
You can try this one.
public static String getWord() {
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
wordInput.close();
return inputWord;
}
public static void main(String[] args) {
char[] letters = generateLetters();
String input = getWord();
StringTokenizer st = new StringTokenizer(input, " ");
int counter = 0;
boolean isValid = true;
while (st.hasMoreTokens()) {
String word = st.nextToken();
if (!word.startsWith(String.valueOf(letters[counter]))) {
isValid = false;
break;
}
counter++;
}
if (isValid) {
System.out.println("valid");
} else {
System.out.println("Invalid");
}
}
This code will only work for the input you have provided, i am assuming thats what you need i.e. if the random letters are ' J U D ' only the input "Just Use Data". will qualify as correct input and not Use Just Data. I have also not checked the boundaries of input.
import java.util.Random;
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
char[] letters = generateLetters();
String input = getWord();
String[] words = input.split(" ");
if (words.length == letters.length) {
if (check(letters, words)) {
System.out.println("Yeah");
} else {
System.out.println("Oops");
}
} else {
System.out.println("INVALID");
}
}
public static Boolean check(char[] letters, String[] words) {
for (int i = 0; i < letters.length; i++) {
if (words[i].charAt(0) != letters[i]) {
return false;
}
}
return true;
}
public static String getWord() {
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
return inputWord;
}
public static char[] generateLetters() {
Random randomLetter = new Random();
char[] letters = new char[3];//Make it varaible length
for (int i = 0; i < letters.length; i++) {
letters[i] = (char) ((int) randomLetter.nextInt(26) + 'A');
System.out.printf(letters[i] + " ");
}
return letters;
}
}
Method 2 Regex
public static Boolean check(char[] letters, String word) {
return word.matches(letters[0]+"(\\S)*( )"+letters[1]+"(\\S)*( )"+letters[2]+"(\\S)*");
}
hi am trying to write a palindrome checker code but if i enter "madam" it still tells me its not a palindrome please help. tell me whats causing it
import java.util.Scanner;
public class parlindrome
{
String original, reverse = "";
public void checkpalindrome(){
Scanner h = new Scanner(System.in);
System.out.println("enter a word : ");
original = h.nextLine();
int length = original.length();
for(int i = length-1; i >= 0; i--)
{
{
reverse = reverse + original.charAt(i);
if(original.equals(reverse))
{
System.out.println("entered word is a palindrom ");
}
else
{
System.out.println("entered word is not a palindrome ");
break;
}
}
}
}
public static void main(String[]args)
{
parlindrome k=new parlindrome();
k.checkpalindrome();
}
}
You should finish the loop that reverses the String before checking if it's a palindrome :
for(int i=length-1;i>=0;i--) {
reverse=reverse+original.charAt(i);
}
if(original.equals(reverse)) {
System.out.println("entered word is a palindrom ");
}
Also, if you want this method to work more than once, you should make reverse a local variable and initialize it to an empty String inside the method.
You could do it in a more effective way, using Java´s reverse.
public void checkpalindrome(){
Scanner h = new Scanner(System.in);
System.out.println("Enter a word: ");
String original = h.nextLine();
if(original.equals(new StringBuilder(original).reverse().toString()))
System.out.println("Entered word is a palindrom");
else
System.out.println("Entered word is not a palindrom");
}
try this:
import java.util.Scanner;
public class parlindrome {
public boolean checkpalindrome(String original) {
String reverse = "";
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
reverse += original.charAt(i);
}
if (reverse.equals(original)) {
System.out.println("entered word is a palindrom ");
return true;
}
System.out.println("entered word is not a palindrom ");
return false;
}
public static void main(String[] args) {
Scanner h = new Scanner(System.in);
System.out.println("enter a word : ");
String original = h.nextLine();
parlindrome k = new parlindrome();
k.checkpalindrome(original);
}
}
Just remove validation part from for loop. Your code should be as below:
for (int i = length - 1; i >= 0; i--)
reverse += original.charAt(i);
if (original.equals(reverse))
System.out.println("entered word is a palindrom ");
else
System.out.println("entered word is not a palindrome ");
h.close();
In my searchForANumber method, I'm trying to display if a number is found within my array or not. The problem is, I'm using and if, else to determine if the searchValue matches a value in the array statement in my for loop, and when I do this, the last variable in the array is tested, and my returned value is based on only the final value. How can I make so that my return phrase is based on all elements in the array and not just the last one? Do I use a while, do-while, switch loop? Any help is appreciated.
import java.util.Scanner;
public class Practice {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your minimum number: ");
int minNumber = input.nextInt();
System.out.println("Enter your maximum number: ");
int maxNumber = input.nextInt();
int[] array = new int[(maxNumber-minNumber)+1];
int[]readInArray = new int[maxNumber-minNumber+1];
readInArray=readNumbers(minNumber, maxNumber, array);
printNumbers(readInArray, minNumber);
searchForANumber(readInArray, minNumber);
sumNumbers(readInArray);
printBackward(readInArray);
}//end of main method
private static void printBackward(int[] readInArray) {
for (int i=(readInArray.length-1);i>0;i--){
System.out.print(readInArray[i] + " ");
}
}
private static void sumNumbers(int[] readInArray) {
int total = 0;
for (int i=0;i<readInArray.length;i++){
total = total + readInArray[i];
}
System.out.println(total);
}
private static void searchForANumber(int[] readInArray, int minNumber) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number to search for: ");
int searchValue = input.nextInt();
boolean returnValue = false;
for (int i = 0; i < readInArray.length;i++) {
if (searchValue == readInArray[i])
returnValue=true;
break;
}// end of for
System.out.println(returnValue);
}
private static void printNumbers(int[] readInArray, int minNumber) {
for (int i = 0; i < readInArray.length;i++) {
System.out.print(readInArray[i] + " ");
minNumber++;
}
System.out.println(" ");
}
private static int[] readNumbers(int minNumber, int maxNumber, int[] array) {
for (int i = 0; i < array.length;i++) {// input grades for each students
array[i]=minNumber;
minNumber++;
} // end of for loop
return array;
} // end of readArray method
}//end of class
you can do it in two ways.
make your method searchForANumber return boolean.
private static boolean searchForANumber(int[] readInArray, int minNumber) {
//before for loop
for (int i = 0; i < readInArray.length;i++) {
if (searchValue == readInArray[i])
return true;
}
return false;
}
use break and a boolean
private static void searchForANumber(int[] readInArray, int minNumber) {
//before for loop
boolean found = false;
for (int i = 0; i < readInArray.length;i++) {
if (searchValue == readInArray[i]){
found = true;
break;
}
}
if(found)
System.out.println("Found");
else
System.out.println("Not Found");
}