I'm doing an assignment (no I'm not asking you guys to do it for me I just need help with a small part)
Basically I have an oversize 2D array that needs to be outputed when the user chooses.
I'll include all of my code so far but be warned, it's too long. I would appreciate any help, thanks
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
public class customerDatabase {
public static Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws IOException {
FileInputStream fileByteStream = new FileInputStream("myfile.txt");
Scanner inFS = new Scanner(fileByteStream);
char choice = 'z';
int i = 0;
String[][] customerInfo = new String[100][5];
int arrayLength = 0;
while(inFS.hasNext()){
customerInfo[i][0]=inFS.next(); //first name
customerInfo[i][1]=inFS.next(); //last name
customerInfo[i][2]=inFS.next(); //email
customerInfo[i][3]=inFS.nextLine(); //phone number
++i;
++arrayLength;
}
while(choice != 'q'){
choice = printMenu();
}if(choice == 'o'){
outputDatabase(customerInfo,arrayLength);
}
}
public static char printMenu(){
char userChar = 'z';
String choiceString;
System.out.println();
System.out.println("MENU");
System.out.println("o - Output customer database");
System.out.println("s - Sort by name");
System.out.println("a - Add a customer");
System.out.println("r - Remove a customer");
System.out.println("u - Update customer information");
System.out.println("f - Find a customer");
System.out.println("q - Quit");
System.out.println();
while((userChar != 'o') && (userChar != 's') && (userChar!= 'a') && (userChar != 'r') && (userChar != 'u') &&(userChar != 'f') && (userChar!= 'q')){
System.out.println("Choose an option:");
choiceString = scnr.nextLine();
userChar = choiceString.charAt(0);
}
return userChar;
}
public static void outputDatabase(String[][] userArray, int arraySize){
int i;
int j;
for(i=0; i < arraySize; ++i) {
for(j=0; j < arraySize; ++j) {
System.out.print(userArray[i][j]);
}
}
}
}
Then there's a text file which includes names and emails and phone numbers (which is what is being inserted into the array that is being output).
Basically I have an oversize 2d array that needs to be output when the
user chooses for it to be.
You have four properties i.e. First Name, Last Name, Email & Phone Number and hence, your inner loop should only go from index zero to index three,
for(int i=0; i < arraySize; ++i) {
for(int j=0; j < 4; ++j) {
System.out.print(userArray[i][j]);
}
}
Currently, you are setting it to arraySize which will result in an exception if arraySize is greater than four.
Related
Write a program that will read a line of text String and display all the letters that occur in the text, one per line and in alphabetical order, along with the number of times each letter occurs in the text.
For this purpose, you must use an array of type int of length 26, so that the element at index 0 contains the number of a’s, the element at index 1 contains the number of b’s, and so forth.
Allow both uppercase and lowercase letters as input, but treat uppercase and lowercase versions of the same letter as being equal.
Hint: Use the method chatAt(int index) in the String class to get the individual character in a string at the specified index.
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] letters = new int[26];
char choice;
while (true) {
// taking user input
System.out.println("Please enter text ending with period:");
String text = sc.nextLine();
// converting it lowercase
text = getActualText(text).toLowerCase();
char c = 'a';
for (int i = 0; i < letters.length; i++)
// increasing character by 1
letters[i] = countLetters(text, c++);
System.out.println("\nThe frequency of the letters");
c = 'a';
for (int i = 0; i < letters.length; i++) {
// showing only those letters whose frequnecy is greater than 0
if (letters[i] != 0)
System.out.println(c + ": " + letters[i]);
c++;
}
System.out.print("Would you like to try another text?(Y/N) ");
choice = sc.nextLine().charAt(0);
if (choice == 'n' || choice == 'N')
break;
}
}
private static int countLetters(String text, char c) {
int count = 0;
for (int i = 0; i < text.length(); i++)
// counting the frequency
if (text.charAt(i) == c)
count++;
return count;
}
/**
* This method will extract the first sentence from a text ending with full stop(.)
*/
private static String getActualText(String text) {
String newText = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '.')
// breaking out of the loop if the full stop is found
break;
// adding it to the text
newText += text.charAt(i) + "";
}
return newText;
}
}
Try to change existing condition to below new condition:
Existing Condition: (Allowing frequencies which are not equal to 0):
if(letters[i] != 0) {//showing only those letters whose frequency is greater than 0
New Condition: (Allowing frequencies which are greater than or equal to 0):
if(letters[i] >= 0) {
It's enough to go through the text one time and count the occurrence of each letter. And then just show only letters with count >0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.print("\nEnter the text: ");
String str = scan.nextLine();
print(histogram(str));
} while (shouldContinue(scan));
}
private static int[] histogram(String str) {
int[] letters = new int[26];
for (int i = 0; i < str.length(); i++)
if (Character.isLetter(str.charAt(i)))
letters[Character.toLowerCase(str.charAt(i)) - 'a']++;
return letters;
}
private static void print(int[] letters) {
System.out.println("The frequency of the letters:");
for (int i = 0; i < letters.length; i++)
if (letters[i] > 0)
System.out.println((char)('a' + i) + ": " + letters[i]);
}
private static boolean shouldContinue(Scanner scan) {
while (true) {
System.out.print("Would you like to try another text (Y/N)? ");
String str = scan.nextLine();
if (str.length() != 1)
continue;
if ("Y".equalsIgnoreCase(str))
return true;
if ("N".equalsIgnoreCase(str))
return false;
}
}
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.
I am having trouble with my hangman programm in java class I don't seem to get the lost lives counter to work properly and also displaying the already guessed letters that are right don't display in the sequence when you make the next correct guess.
import java.util.Scanner; //imports scanner so I could use user input
import java.util.Random; // imports random picker for words, to pick a random word
public class javaxx {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
StringBuffer buffer = new StringBuffer();
String wordToGuess;
int wordLength;
int wordToGuessLength;
int position;
int livesLost = 0;
int totalLives = 7;
int lettersRemaining;
boolean guessInWord;
char guess;
StringBuffer prevGuessedLetters;
//declare variable
//String wordToGuess[] = new String[29];
//insert array for words and their values
String[] myStringArray = new String[]{"programming","exhaustive","violin","selection","repetition","serendipity","watermelon","football","mobilephone","handbag","teddybear","cardigan","waterfall","cupcake","pineapple","strawberry","collection","chicken","tablecloth","candlestick","notebook","radiator","champagne","wineyard","parent","circus","snowbell","clocktower","mermaid","cardigan"};
//Display the rules of the game
System.out.println("You are playing the game Hang Man. You have to guess the letters in the word. You will see how many letters are in the word and you have 7 changes to be wrong. ");
//choose a random word from the array
wordToGuess = myStringArray[(int) (Math.random() * myStringArray.length)];
//determine the length of the word
wordLength = wordToGuess.length();
//show the player how many letters are in the word
System.out.println("The word you are quessing has " + wordLength + " letters in it");
lettersRemaining = wordLength;
for (position = 0; position < wordLength; position++) {
sb.append("_ ");
}
System.out.println(sb.toString());
//loop starts
while (lettersRemaining > 0 && livesLost < 7) {
//prompt user to guess a letter
System.out.println("Guess a letter:");
guess = myScanner.findWithinHorizon(".", 0).charAt(0);
//check if the letter guessed is in the secretWord
guessInWord = (wordToGuess.indexOf(guess)) != -1;
if (guessInWord == false) {
livesLost++;
System.out.print("Sorry, you have lost a life. You still have ");
System.out.print(totalLives -= livesLost);
System.out.println(" life/lives left. Keep trying.");
} else {
System.out.println("That was a good guess, well done!");
for (position = 0; position < wordLength; position++) {
if (wordToGuess.charAt(position) == guess) {
System.out.print(guess);
lettersRemaining--;
} else {
System.out.print("_ ");
}
}
}
System.out.println();
prevGuessedLetters = buffer.append(guess);
System.out.print("Previously guessed letters: ");
System.out.println(prevGuessedLetters);
System.out.print("Letters remaining: ");
System.out.println(lettersRemaining);
}
if (livesLost == totalLives) {
System.out.println("Sorry, you lose!");
} else {
System.out.print("Well done, you win! The word was ");
System.out.println(wordToGuess);
}
}
}
change this line
System.out.print(totalLives -= livesLost);
to
System.out.print(totalLives - livesLost);
this was the problem with liveslost counter.
I have this java code that basically just prints a christmas tree of X height.However, the program ask for the number, then print the tree and then just end.I would like it to loop until I enter 0,wich would end the program,and also I would like to make it print only if the number entered is from 1-40(not over 40).Im begining in the java world and I dont know how to do that.Heres my code for now:
public class xtree {
public static void main(String[] args)
{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
int temp = scan.nextInt();
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}
}
Thank you, im a beginner to java so please be lenient ;)
Well, I would separate the method out into two:
A printChristmasTree method, which accepts the height as a parameter
Your main method, which just deals with taking user input and calling printChristmasTree or exiting
Most of your current main method would go into the printChristmasTree, and main would be a loop. Something like:
public static void main(String[] args) {
Scanner scan = new Scanner(in);
while (true) {
System.out.print("Please enter a number (0-40): ");
int height = scan.nextInt();
if (height == 0) {
// Exit the program
return;
} else if (height >= 1 && height <= 40) {
printChristmasTree(height);
} else {
System.out.println("Invalid input.");
}
}
}
There are other approaches you could use instead of returning from a while (true) loop, but this looks the simplest to me.
The separation of the "taking input" from the "printing the Christmas tree" aspects leads to much more readable code than keeping them combined, in my view - and it's more flexible in terms of things like writing a different program to print all valid Christmas trees.
Use a while loop:
Scanner scan = new Scanner(System.in);
System.out.print("please enter a number: ");
int temp = scan.nextInt();
while (temp>0) {
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
System.out.print(" ");
}
for(int k = 0; k<z; k++)
{
System.out.print("*");
}
System.out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
System.out.print(" ");
}
System.out.println("*");
temp = scan.nextInt();
}
Here's the code for doing that:
public class xtree {
public static void main(String[] args)
{
int temp;
do{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
temp = scan.nextInt();
if(temp >= 1 && temp <= 40){ //don't display a tree higher than 40
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}else if(temp != 0){
out.print("Please enter a number between 1 and 40!");
}
}while(temp != 0);
}
}
Use nested for loops statements to draw hallow boxes of "*"s. The boxes have the same number of rows and columns and this number should be input from the user (valid range: 5 to 21). I'm having trouble coming up with a way to make the box hollow. this is what i have for the code and it comes as a complete square, but i need it to be hollow or just the border.
System.out.println("How many rows/columns(5-21)?");
rows=input.nextInt();
while(rows<5||rows>21){
System.out.println("Out of range. Reenter: ");
rows=input.nextInt();
}
for(m=1;m<=rows;m++){
for(c=1;c<=rows;c++){
System.out.print("*");
}
System.out.println();
}
the output should look like this:
How many rows/columns (5-21)? 25
Out of range. Reenter: 7
*******
* *
* *
* *
* *
* *
*******
You need to print only some of the *s, so add a test before the print("*"). One option would be to explicitly test the four conditions (top, bottom, left, right) and OR them together logically:
if( (m==1) || //top
(m==rows) || //bottom
(c==1) || //left
(c==rows) //right
) {
System.out.print("*");
} else {
System.out.print(" ");
}
Each m== test or c== test identifies one piece of the square. Since the four tests
are ORed together, the if() is true (and a * is printed) if any one of the four tests is true. If none of them are true, the else runs and prints a space.
I also recommend renaming m to rowIndex and c to colIndex or something. When you come back to the code a week or two later, more descriptive names will make it easier to pick up where you left off. (Ask me how I know!)
import java.util.Scanner;
public class icibos {
public static void main(String[] args) {
Scanner gir = new Scanner(System.in);
System.out.print("Karenin kenarını girin: ");
int kenar = gir.nextInt();
for (int i = 1; i <= kenar; i++) {
for (int j = 1; j <= kenar; j++) {
if (i == 1 || i == kenar || j == 1 || j == kenar)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
for (int i=1;i<=lgh;i++){
for (int a=1;a<=lgh;a++){
if(i>1 && i<lgh && a>1 && a<lgh)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println("");
}
Try this , its bit hard code.
Working Example here
String myStars="*******";
String oneStar="*";
int count=0;
System.out.println(myStars);
count++;
while(count<=7)
{
System.out.println(oneStar+" "+oneStar);
count++;
}
System.out.print(myStars);
You can try this
Example is Here
String pattern;
int noOfTimes;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the pattern to print : ");
pattern = scanner.nextLine();
System.out.print("Enter number of times it should get printed : ");
noOfTimes = scanner.nextInt();
for(int i=1; i<=noOfTimes; i++) {
System.out.println();
if(i==1 || i==noOfTimes) {
for(int j=1; j<=noOfTimes; j++){
System.out.print(pattern+" ");
}
}
else {
for(int k=1; k<=noOfTimes;k++) {
if(k==1 || k == noOfTimes) {
System.out.print(pattern + " ");
}
else {
System.out.print(" ");
}
}
}
}
import java.util.Scanner;
public class holsqr{
public static void main(String args[]){
Scanner ma=new Scanner(System.in);
System.out.print("Enter the number:");
int max=ma.nextInt();
for(int i=1;i<=max;i++){
for(int j=1;j<=max;j++){
if((i==1)||(i==max)){
System.out.print("#");
}else{
if(j==1||j==max){
System.out.print("#");
}
else{
System.out.print(" ");
}
}
}
System.out.println();
}
}
}
It pretty simple, using two while loop:
public static void main(String[] args) {
int size = 0;
int r = 0;
String star = "*";
String space = " ";
System.out.print("Input size of side of square: ");
Scanner input = new Scanner(System.in);
size = input.nextInt();
while (r < size) {
int c = 0;
while (c < size) {
System.out.print(r > 0 && r < size - 1 && c > 0 && c < size - 1 ? space : star);
++c;
}
System.out.println();
++r;
}
}