I am a beginner on java.
Why it always show not found?
and how exactly make a not found string value on array?
String[] array = new String[10];
String b = "5";
for (int i = 0; i < 10; i++) {
String in = String.valueOf(i);
array[i] = in;
}
for (int i = 0; i < 10; i++) {
if (b.equals(array[i])) {
System.out.println("found " + array[i]);
} else if (!b.equals(array[i])) {
System.out.println("not found");
System.exit(0);
}
}
}
Your second for loop terminates on i = 0 when you call System.exit(0); (the program actually terminates overall when you call that).
} else if (!b.equals(array[i])) {
System.out.println("not found");
System.exit(0);
}
Suggest changing the logic to break from the loop when the match has been found.
for (int i = 0; i < 10; i++) {
if (b.equals(array[i])) {
System.out.println("found " + array[i]);
break;
}
}
Okay i've been figure it out.
Thanks for the advice.
Just make "not found" statement outside the loop.
String[] array = new String[10];
String b = "10";
boolean c = false;
for (int i = 0; i < 10; i++) {
String in = String.valueOf(i);
array[i] = in;
}
for (int i = 0; i < 10; i++) {
if (b.equals(array[i])) {
System.out.println("found " + array[i]);
} else if (!b.equals(array[i])) {
c = true;
}
}
if (c == true){
System.out.println("not found");
}
}
Related
In my code:
public static String input() {
Scanner input = new Scanner(System.in);
while(true) {
int qcount = 0;
String key = input.nextLine();
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i++) {
//Here the while loop is supposed to break
if(keyCharArray[i]=='q') {
qcount++;
break;
}
}
int[] radie = new int[(keyCharArray.length)/2];
int[] höjd = new int[(keyCharArray.length)/2];
int counter = 0;
for(int i = 0; i < keyCharArray.length; i++){
if(i % 2 == 0){
radie[i/2] = keyCharArray[i] - '0';
}
else if(i % 2 != 0){
höjd[i/2] = keyCharArray[i] - '0';
}
}
for(int i = 0; i < (keyCharArray.length)/2; i++) {
System.out.print("r = " + radie[i] + " " + "h = " + höjd[i] + "\n\r" + "Basytans area: " + area(radie[i], höjd[i]) + "\n\r" + "Mantelytans area:" + area(radie[i]) + "\n\r" + "Volym: " + volume(radie[i], höjd[i]) + "\n\r");
}
return key;
}
}
The While loop is supposed to repeat the content until keyCharArray[i] =='q' -> There after the while loop is supposed to break
How can I make this work? Thanks
I have tried everything, yet I can't seem to solve it.
Appreciate any efforts, Thanks alot
Tried everything, doesn't work
sadasd
dsadsa
sdadsa
asdsda
You current code is (partially) like this:
public static String input(){
Scanner input = new Scanner(System.in);
while(true){
int qcount = 0;
String key = input.nextLine();
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i++) {
if(keyCharArray[i]=='q') {
qcount++;
break;
}
}
// The rest...
}
}
The problem with this is that the break only breaks the inner for loop.
The simplest solution is to use the qcount variable you already have, and after the for loop check if it's non-zero to break out of the while loop:
for (int i = 0; i<keyCharArray.length;i++) {
if(keyCharArray[i]=='q') {
qcount++;
break;
}
}
if (qcount > 0) {
break; // Breaks out of the while loop
}
As for my suggestion in the comment it would be something like this instead:
private boolean shouldBreak(String key) {
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i++) {
if(keyCharArray[i]=='q') {
return true; // Return that we should break the while loop
}
}
return false; // Do not break the while loop
}
public static String input(){
Scanner input = new Scanner(System.in);
while(true){
String key = input.nextLine();
if (shouldBreak(key)) {
break; // Breaks out of the while loop
}
// The rest...
}
}
I personally recommend something like this, as it makes the code cleaner and easier to read and understand and maintain.
I have the below String variable
String s = "abc,xyz,lmn,ijk";
I want to extract only the portion of the String (i.e - 'lmn')
And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()
And this question was asked in my interview.
I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?
String s = "abc,xyz,lmn,ijk";
int counter = 0;
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ',') {
counter++;
}
}
Here's one way:
public static void main(String[] args) {
String s = "abc,xyz,lmn,ijk";
char[] ch = s.toCharArray();
int counter = 0;
int place = 2;
for (int i = 0; i < ch.length-2; i++) {
if(ch[i] == ',') {
counter++;
}
if(counter == place && ch[i] != ',') {
System.out.print(ch[i]);
}
}
}
It prints everything after the second comma, but before the third one.
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "abc,xyz,lmn,ijk";
StringBuffer sb=new StringBuffer();
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(','==(ch[i]))
{
if (sb.toString().equals("lmn")) {
System.out.println(sb.toString());
}
else
{
int length=sb.length();
sb.delete(0, length);
}
}
else
{
sb.append(ch[i]);
}
}
}
I would do it this way.
String s = "abc,xyz,lmn,ijk";
String x = "c,x"; // String to found
String r = "";
boolean coincidence = false;
int a=0; // Initial index if of the first character in x is found
int b=0; // Last index If it was possible to search for the last character of x
int c=0; // Index "iterator" on String x
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(c == x.length())
break;
else{
if(ch[i] == x.charAt(c) && !coincidence){
a = i; b = i; c++;
coincidence = true;
}
else if(ch[i] == x.charAt(c) && coincidence){
b++; c++;
}else{
coincidence = false;
a = 0; b = 0; c = 0;
}
}
}
System.out.println("String: " + s);
System.out.println("String to find: " + x);
System.out.println("Was found? " + ((coincidence)? "Yes" : "No"));
if(coincidence){
System.out.println("Intervals indexes in String: ["+a + "," + b +"]");
// String extration
for (int i = a; i <= b; i++)
r += s.charAt(i);
System.out.println("String extracted: " + r);
}
I want my code to loop through an array and only give the user an option to delete a student only if there are values in the array. If all the array values are null then I want it to print out a message. The problem is that my message is printing out multiple times for each null element in the array.
My code:
static void deleteStudent() {
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
for (i = studentChoice + 1;i < studentNamesArray.length; i++) {
studentNamesArray[i-1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(i = studentChoice + 1;i < 9;i++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[i-1][y] = studentMarksArray[i][y];
}
}
markArrayCount = markArrayCount - 1;
for(int y = 0;y < 3;y++) {
studentMarksArray[9][y] = 0;
}
} else {
System.out.println("There are no students stored");
}
}
}
The else block runs in each loop iteration. If you want to run it only once at the end, do something like this:
boolean studentFound = false;
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
...
Then after the for:
if (!studentFound) {
System.out.println("There are no students stored");
}
Here is how I would determine if all the elements are null. The reason yours prints it out for each null element is that the print statement is inside the for loop.
boolean allNull = true; // default is that everything is null
for(int i = 0; i < studentNamesArray.length; i++) { // iterate through entire array
if(studentNamesArray[i] != null) { // if even 1 of them is not null
allNull = false; // set allNull to false
break; // and break out of the for loop
}
}
if(allNull) System.out.println("There are no students stored!");
I suggest to use 'boolean' variable, lets name it 'flag'. Initialize it as 'false'. If you found not null element in array, when set 'flag = true'. After 'for' loop check 'if (!flag) System.out.println ("There are no students.");'.
In your for loops, you use the same variable i, in which it overrides the original variable used in the for loop.
Try something like this:
static void deleteStudent() {
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
for (int j = studentChoice + 1;j < studentNamesArray.length; j++) {
studentNamesArray[j-1] = studentNamesArray[j];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(int k = studentChoice + 1;k < 9;k++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[k-1][y] = studentMarksArray[k][y];
}
}
markArrayCount = markArrayCount - 1;
for(int z = 0;z < 3;z++) {
studentMarksArray[9][z] = 0;
}
} else {
System.out.println("hi");
}
}
}
Although, I am not sure what you are trying to print out, I made adjustments to the other variable names based on my intuition; the result might not be exactly as resulted, but I am sure you can make further adjustments with the variable names so that you are not over-riding each other and causing excessive loops.
StackOverflow. I am attempting to make a program that uses a text menu to to a multitude of things to manipulate a single string. One of the methods turns the string into an array of strings. This works fine. However, all of the methods that manipulate it as an array(one prints it out, one reverses the word order, and one sorts them using an exchange sorting method) return a NullPointerException when called. I have looked all through the code and do not see where it is coming from. Here is the .Java file containing all of the code. My problem is only happening when I call the printArray(), reverse(), and sort() methods, near the bottom. Any and all help is appreciated. Sorry for the sloppy code, I have not cleaned it up yet.
Code:
/*
Computer Programming Lab 11
Jim Kimble
3 Mar 2013
Work with strings and implementing a menu.
Acknowledgements:
Uses main structure of HUTPanel as designed at UMU, 2002-2012
*/
import java.io.*;
import java.awt.*;
import javax.swing.*;
public class HUTPanel extends JPanel
{
/***************************************************
* Class-level data members should be declared here.
***************************************************/
int numVowels;
String[] words;
String str;
String vowels;
String menuChoice;
String oString = "A tong lime ago, a daggy shog bossed a cridge over a pillmond,\n"
+"When in the course of human events\n"
+"Mary had a little lamb.\n"
+"The girls' basketball team repeated as tournament champion this weekend.";
public HUTPanel(JFrame frame)
{
// Set panel background color
setBackground(Color.WHITE);
setLayout(null);
setPreferredSize(new Dimension(810, 410));
/***************************
* Now add your code below:
***************************/
// Create a frame around this panel.
frame.setTitle("Computer Programming Lab/Program # 11");
frame.getContentPane().add(this);
str = "A tong lime ago, a daggy shog bossed a cridge over a pillmond,\n"
+"When in the course of human events\n"
+"Mary had a little lamb.\n"
+"The girls' basketball team repeated as tournament champion this weekend.";
System.out.println("Lab 11: Text Manipulation");
//getTheText();
System.out.println("The string is: '"+str+"'.");
handleTheMenu();
} // end of constructor
/*************************
* Add your methods here:
*************************/
// Get a text sequence from the keyboard and put it in str
public void getTheText()
{
Boolean inputDone = false;
while (!inputDone)
{
System.out.print("Enter your text: ");
inputDone = grabText();
}
}
private Boolean grabText()
{
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
menuChoice = inputReader.readLine();
return true;
}
catch(IOException e)
{
System.out.println("Error reading input. Please try again.");
}
return false;
}
public void handleTheMenu()
{
int choice = -1;
Boolean OK;
while (choice != 0)
{
choice = -1;
System.out.println("Menu:");
System.out.println();
System.out.println(" 1. Count the vowels"); //"There are ... vowels in the text."
System.out.println(" 2. Remove all letter e's"); //then print it.
System.out.println(" 3. Replace all t's with '+'"); //then print it
System.out.println(" 4. Search for a requested word (will reset the string)"); //Does 'word' exist in the text?
System.out.println(" 5. Print the words on individual lines");
System.out.println(" 6. Reset the string.");//Reset the string to the original
System.out.println(" 7. Put the words in an array"); //then print it
System.out.println(" 8. Reverse the text word order"); //then print it
System.out.println(" 9. Sort the words in an array"); //Once the words are put into an array
System.out.println();
System.out.print(" 0 to quit --> ");
OK = grabText();
if (OK)
{
try
{
choice = Integer.parseInt(menuChoice);
}
catch(NumberFormatException e)
{
System.out.println("Not a number; please try again.");
System.out.println();
}
switch(choice)
{
case 0: System.out.println();
System.out.println("Thank you.");
break;
case 1: countVowels();
break;
case 2: removeAllEs();
break;
case 3: changeTToPlus();
break;
case 4: find();
break;
case 5: listWords();
break;
case 6: reset();
break;
case 7: makeArray();
break;
case 8: reverse();
break;
case 9: sort();
break;
default: System.out.println("Not a valid choice; please try again.");
}
}
}
}
private void countVowels() {
//count the vowels in str
vowels = "aeiouAEIOU";
numVowels = 0;
for( int i = 0; i < vowels.length(); i ++) {
for(int j = 0; j < str.length(); j++) {
if (str.charAt(j) == vowels.charAt(i)) {
numVowels += 1;
}
}
}
System.out.println("The string has " + numVowels + " vowels in it.");
}
private void removeAllEs() {
String str3 = str.replace('e', ' ');
System.out.print(str3);
str = str3;
}
private void changeTToPlus() {
String str2 = str.replace('t', '+');
System.out.println(str2);
str = str2;
}
private void find() {
str = oString;
getTheText();
if(str.indexOf(menuChoice) != -1)
{
System.out.println("The word " +menuChoice+ " is at index " +str.indexOf(menuChoice));
}
else
{
System.out.println("The word " +menuChoice+ " is not in the string.");
}
}
private void listWords() {
int pos = 0;
int i = 0;
while(i > -1)
{
i = str.indexOf(' ', pos);
if (i > -1)
{
System.out.println(str.substring(pos, i));
pos = i + 1;
}
}
}
private void reset() {
str = oString;
System.out.println();
System.out.println("String reset.");
System.out.println();
}
private void makeArray() {
int n = 1;
String[] words = new String[n];
int pos = 0;
int i = 0;
int j = 0;
while(j > -1)
{
for (i = 0; i < 1000; i++)
{
n += 1;
j = str.indexOf(' ', pos);
if (j > -1)
{
words[i] = str.substring(pos, j);
pos = j + 1;
}
}
}
//printArray();
}
//***FIX***
private void printArray() {
for (int k = 0; k < words.length -1; k++){
System.out.println(words[k]);
}
}
//***FIX***
private void reverse() {
int i = 0;
int j = words.length - 1;
String temp;
while (i < j){
temp = words[i];
words[i] = words[j];
words[j] = temp;
i++;
j--;
}
}
private void sort() {
String temp = "";
for (int i = 1; i < words.length - 1; i++) {
for (int j = i + 1; j < words.length; j++) {
int x = words[i].compareTo(words[j]);
if (x > 0) {
temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
for (int p = 0; p < words.length -1; p++) {
System.out.println(words[p]);
}
}
}
You Error is here:
private void makeArray() {
int n = 1;
String[] words = new String[n];//At This line you are creating local array words.The instance variable words is still null.
int pos = 0;
int i = 0;
int j = 0;
while(j > -1)
{
for (i = 0; i < 1000; i++)
{
n += 1;
j = str.indexOf(' ', pos);
if (j > -1)
{
words[i] = str.substring(pos, j);
pos = j + 1;
}
}
}
use:
words = new String[n]; instead of String[] words = new String[n];
As mentioned by Luiggi Mendoza in the comment section, the local variable words defined within makeArray method is shadowing the instance variable words defined within HUTPanel class.
As side note I want to point out the unnecessary creation of new BufferedReader objects in method grabText() each time you are calling it in getTheText(). It would be much efficient if your make inputReader an instance variable in your class , and instantiate it once within the constructor using inputReader = new BufferedReader(new InputStreamReader(System.in));. This way your grabText method becomes like this :
private Boolean grabText()
{
try {
//No more new object creation for BufferedReader for each call of this method.
menuChoice = inputReader.readLine();
return true;
}
catch(IOException e)
{
System.out.println("Error reading input. Please try again.");
}
return false;
}
Make sure you always you always start with option 7, so your words array gets initialized. This is in fact not something that the user should do. The application should handle it so that the user either can't select other options, or does it automatically.
Update: Vishal K is correct, but this is still a weak point in your application.
This is what I want :
Let the user enter as many numbers as they want until a non number is entered (you may
assume there will be less than 100 numbers). Find the most frequently entered number. (If
there are more than one, print all of them.)
Example output:
Input: 5
Input: 4
Input: 9
Input: 9
Input: 4
Input: 1
Input: a
Most common: 4, 9
I have got to the point in my code where I have managed to find out which are the most common numbers. However, I don't want to print out the same number over and over again; example from above: Most common: 4, 9, 9, 4
What needs to be done?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[100];
System.out.print("Input: ");
input[0] = in.readLine();
int size = 0;
for (int i = 1; i < 100 && isNumeric(input[i-1]); i++) {
System.out.print("Input: ");
input[i] = in.readLine();
size = size + 1;
}
/*for (int i = 0; i < size; i++) { //testing
System.out.println(input[i]);
}*/
int numOccur;
int[] occur = new int[size];
for(int i = 0; i < size; i++) {
numOccur = 0;
for (int j = 0; j < size; j++) {
if(input[i].equals(input[j])) {
numOccur = numOccur + 1;
}
}
occur[i] = numOccur;
//System.out.println(numOccur); //testing
}
int maxOccur = 0;
for(int i = 0; i < size; i++) {
if(occur[i] > maxOccur) {
maxOccur = occur[i];
}
}
//System.out.println(maxOccur); //testing
for (int i = 0; i < size && !numFound; i++) {
if(occur[i] == maxOccur) {
System.out.println(input[i]);
}
}
}
//checks if s is an in, true if it is an int
public static boolean isNumeric (String s) {
try {
Integer.parseInt(s);
return true; //parse was successful
} catch (NumberFormatException nfe) {
return false;
}
}
Found the solution!
String[] mostCommon = new String[size];
int numMostCommon = 0;
boolean numFound = false;
for (int i = 0; i < size; i++) {
int isDifferent = 0;
if (occur[i] == maxOccur) {
for (int j = 0; j < size; j++) {
if (!(input[i].equals(mostCommon[j]))) {
isDifferent = isDifferent + 1;
}
}
if (isDifferent == size) {
mostCommon[numMostCommon] = input[i];
numMostCommon = numMostCommon + 1;
}
}
}
for (int i = 0; i < numMostCommon - 1; i++) {
System.out.print("Most common: " + mostCommon[i] + ", ");
}
System.out.println(mostCommon[numMostCommon - 1]);
you could use the hash table for this to store the frequenceis as the limit is very less i.e. less than 100.
pseudo code would be like:
vector<int> hash(101)
cin>>input
if(isnumeric(input))
hash[input]++
else{
max=max_element(hash.begin(),hash.end());
for(int i=0;i<100;i++)
if(hash[i]==max)
print i
}
Set<Integer> uniqueMaxOccur = new HashSet<Integer>();
for (int i = 0; i < size ; i++) {
if(occur[i] == maxOccur) {
//System.out.println(input[i]);
uniqueMaxOccur.add(input[i]);
}
}
and display the values in the set
You can use a Set and store the values already printed.
What about something like this?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<string,int> numberLookup = new HashMap<string,int>();
Boolean doContinue = true;
while (doContinue)
{
System.out.print("Input: ");
String input = in.readLine();
if (isNumeric(input))
{
if (!numberLookup.containsKey(input))
numberLookup.put(input,1);
else
numberLookup.put(input, numberLookup.get(input) + 1);
}
else
doContinue = false;
}
maxOccur = numberLookup.values().max();
System.out.print("These numbers were all entered " + maxOccur + " times:");
Iterator it = numberLookup.entrySet().iterator();
while (it.hasNext())
{
(Map.Entry)it.next();
System.out.println(pairs.getKey());
}
}
Sorry, I'm a C# person and don't have a Java compiler on me, so this might need some tweaking.