Create a program that keeps track of the following information input by the user:
First Name, Last Name, Phone Number, Age
Now - let's store this in a multidimensional array that will hold 10 of these contacts.
So our multidimensional array will need to be 10 rows and 4 columns.
You should be able to add, display and remove contacts in the array.
*/
import java.util.Scanner;
public class compLab2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[][] contacts = new String [10][4];
System.out.println("Select your options: \n");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact to list.");
System.out.println("2: Remove a contact from the list.");
System.out.println("3: Display contacts.");
System.out.println("0: Exit the list.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContacts(contacts);
break;
case 2:
removeContacts(contacts);
break;
case 3:
displayContacts(contacts);
break;
case 0:
System.out.println("Goodbye!");
System.exit(0);
}
}
}
private static void addContacts (String [][] contacts) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
if (contacts[i][0] == null || contacts[i][0].equals(null)) {
contacts[i][0] = input.nextLine();
contacts[i][1] = input.nextLine();
contacts[i][2] = input.nextLine();
contacts[i][3] = input.nextLine();
boolean Inserted = true;
break;
}
}
}
private static void removeContacts(String [][] contacts) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the contact you want to remove: ");
String removeContact = input.nextLine();
for(int i=0; i<contacts.length; i++){
for(int j = 0; j <contacts[i].length; j++){
if(contacts[i][j].equals(removeContact)) {
contacts[i][0]=" ";
contacts[i][1]=" ";
contacts[i][2]=" ";
contacts[i][3]=" ";
}
}
break;
}
}
private static void displayContacts(String [][] contacts) {
for (int i = 0; i< contacts.length; i++) {
for (int j= 0; j < contacts[i].length; j++) {
System.out.print(contacts[i][j] + " ");
}
System.out.println();
}
}
}
You have to move your break inside the if condition(once element is remove break the loop) otherwise your first for loop will break in i=0 condition.
In if condition you have to check removeContact with contacts[i][j] because contacts[i][j] can be null.
Below you can find the code
if (removeContact != null) { //removeContact should not be null
for (int i = 0; i < contacts.length; i++) {
for (int j = 0; j < contacts[i].length; j++) {
if (removeContact.equals(contacts[i][j])) { //removeContact is not null so check removeContact with contacts[i][j]
contacts[i][0] = " ";
contacts[i][1] = " ";
contacts[i][2] = " ";
contacts[i][3] = " ";
break; //break the loop once you remove
}
}
}
}
You should set null insteam of white space(" ")
if (removeContact != null) {
for (int i = 0; i < contacts.length; i++) {
for (int j = 0; j < contacts[i].length; j++) {
if (removeContact.equals(contacts[i][j])) {
contacts[i][0] = null;
contacts[i][1] = null;
contacts[i][2] = null;
contacts[i][3] = null;
break;
}
}
}
}
Because you are checking null while adding a contact. So setting null will free a space in your array and will allow you to add a new contact to that space.
Also you should check null entry during displaying contacts
private static void displayContacts(String [][] contacts) {
for (int i = 0; i < contacts.length; i++) {
if (contacts[i][0] != null) {
for (int j= 0; j < contacts[i].length; j++) {
System.out.print(contacts[i][j] + " ");
}
System.out.println();
}
}
}
An ArrayList with a custom class can solve this problem easily.
Related
I need to make a program that will take string inputs from user and store it in an array. I will then need to make a function that first: sorts each String {character by character} in descending order and second: will sort all String input in descending order {Strings}.
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static String sortString(String str)
{
char[] chArr = str.toCharArray();
String SortString = "";
// For sorting each individual strings character by character
for (int i = 0; i< chArr.length; i++)
{
for (int j = 0; j < chArr.length; j++)
{
if(chArr[i] > chArr[j])
{
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
//converting all of the character into a single string
for (int k = 0; k<chArr.length;k++)
{
SortString = SortString + chArr[k];
}
//Assigning the current String Sortstring to an array
String[] OldArray = new String[5];
for (int counter = 0; counter<5; counter++)
{
OldArray[counter] = SortString;
}
//sorting all of the strings in descending order
for (int i = 0; i< OldArray.length;i++)
{
for (int j = i+1; j< OldArray.length;j++)
{
if(OldArray[i].compareTo(OldArray[j]) > 0)
{
String temp = OldArray[i];
OldArray[i] = OldArray[j];
OldArray[j] = temp;
}
}
}
return OldArray[0];
}
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
//will print the assorted array
for(int i = 4; i >= 0; i--)
{
System.out.println((sortString(names[i])));
}
}
}
Input:
Input String #1: Stackoverflow
Input String #2: Java
Input String #3: ZZrot
Input String #4: coding
Input String #5: sorting
Output
tsronig
onigdc
zztro
vjaa
wvtsroolkfeca
Expected Output:
zztro
wvtsroolkfeca
vjaa
tsronig
onigdc
Sorry for the question I honestly don't know what to do
You're very close to the solution.
It's impossible to sort the array of strings in sortString because it only has access to the one string you pass in. Move the array sorting code to a separate method, and then you can call it while passing it the entire array:
static String sortString(String str) {
char[] chArr = str.toCharArray();
String SortString = "";
// For sorting each individual strings character by character
for (int i = 0; i < chArr.length; i++) {
for (int j = 0; j < chArr.length; j++) {
if (chArr[i] > chArr[j]) {
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
//converting all of the character into a single string
for (int k = 0; k < chArr.length; k++) {
SortString = SortString + chArr[k];
}
return SortString;
}
static void sortArray(String[] OldArray) {
//sorting all of the strings in descending order
for (int i = 0; i< OldArray.length;i++)
{
for (int j = i+1; j< OldArray.length;j++)
{
if(OldArray[i].compareTo(OldArray[j]) > 0)
{
String temp = OldArray[i];
OldArray[i] = OldArray[j];
OldArray[j] = temp;
}
}
}
}
The main method needs a small change too: the characters in the strings have to be sorted before you sort the array. Here, the characters are sorted while reading the input, and then the array is sorted with one call to sortArray:
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = sortString(UserInput.next().toLowerCase());
}while(names[counter].length() > 25);
}
sortArray(names);
//will print the assorted array
for(int i = 4; i >= 0; i--)
{
System.out.println(names[i]);
}
}
Just made some changes to your code. sortString() was working fine.
Made only changes to main() method:
Got expected output, Try this:
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
//will print the assorted array
String[] namesReversed = new String[names.length];
for(int i=0;i<names.length;i++){
namesReversed[i]=sortString(names[i]);
}
Arrays.sort(namesReversed, String::compareToIgnoreCase);
for(int i = namesReversed.length-1; i>=0; i--)
{
System.out.println(namesReversed[i]);
}
}
In this code I have an array with 5 elements and each element contains a value. Below in the while loop, I'm trying to give the user 3 attempts to guess what number is contained in the array (the user enters their guesses). My problem is that I don't know how to make match the user's guess (stored in a variable choose) with the array values caja[i] to print whether the user won or lost depending on a correct or incorrect guess respectively.
public static void main(String[] args)
{
int[] caja = new int [5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++)
{
System.out.println(caja[i]);
}
System.out.println();
int electionGame = 3;
int o = 0;
while(electionGame > 0)
{
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length; i++)
{
o = o + 1;
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
}
electionGame--;
}
}
}
Your problem is that you break out of your loop in every case:
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
Instead of doing this (and printing the result after only the first comparison), you should have a Boolean indicating whether the number was found in the array:
int electionGame = 3;
boolean found = false; //indicates whether user has found right number
while (electionGame > 0 && !found) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length && !found; i++) {
if (choose == caja[i]) {
found = true;
}
}
electionGame--;
if (found) {
System.out.println("you won");
} else {
System.out.println("nope");
}
}
This way, you can check the variable and tell the user whether he won or lost.
Here are some additional suggestions. The answer by Alex (https://stackoverflow.com/a/36133864/6077352) is good. Please note the comments in the code.
import java.util.Scanner;
/** https://stackoverflow.com/q/36133524/6077352 */
public class GuessNumber {
public static void main(String[] args) {
int[] caja = new int[5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++) {
System.out.println(caja[i]);
}
System.out.println();
int tries = 3;
Scanner sc = new Scanner(System.in);// no need to create scanners in loop
while (tries-- > 0) {// count down tries
System.out.print("Please guess a number... ");
int guess = sc.nextInt();
boolean win = false;// flag to determine if won
for (int i : caja) {// iterate through array and check if guess is inside
win |= (i == guess);// when inside: win=true
}
System.out.println("Answer right? " + win);
System.out.println();
}
}
}
So if the user can attempt to get any of the values of the array you might to change your while loop to this one:
while (electionGame > 0) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
boolean ganaste = false;
for (int i = 0; i < caja.length; i++) {
o = o + 1;
if (choose == caja[i]) {
ganaste = true;
break;
}
}
if (ganaste)
System.out.println("Ganastes");
else
System.out.println("Perdiestes");
electionGame--;
}
I cant use Lists, it must be in tables. How to copy a table to another table greater by 1? Im adding some elements to my table and if there is not enough space i want create new/copy table greater by 1.
Code:
Scanner sc = new Scanner(System.in);
String addNew;
String[] newTab = new String[1];
addNew = sc.next();
for(int i = 0; i<newTab.length; i++) {
if (newTab[i] == null) {
newTab[i] = addNew;
}
else {
//here i want to create new table greater than first one
}
}
Trying with Array.CopyOf but still got error java.lang.ArrayIndexOutOfBoundsException: 1
Code:
int defTab = 1;
for(int i = 0; i<newTab.length; i++) {
if (newTab[i] == null) {
newTab[i] = addNew;
//f
for(int j=0; j<newTab.length; j++) {
System.out.println("array content "+newTab[j]);
}
}
else {
String[] newTab2 = Arrays.copyOf(newTab, defTab+1);
for(int j = 0; j<newTab2.length; j++) {
if (newTab2[j] == null) {
newTab2[j] = addNew;
//f
for(int k=0; k<newTab2.length; k++) {
System.out.println("array content "+newTab[k]);
}
}
}
}
}
My code needs to read information from the textfile. And the textfile looks like this:
X...................
....................
....................
....................
....................
....................
....................
....................
....................
..X.................
Yes, I need to get # of rows and columns and also identify the number and location of 'X's. I'm almost done except my second constructor is giving me a StringOutOfBoundException in the line:
treasureLocations[location] = new Coord(i, j);
I need help only with the second constructor. Could smb please help me with that?
import java.util.Scanner; // Required to get input
import java.io.File; // Required to get input from files
// A 2D treasure map which stores locations of treasures in an array
// of coordinates
public class TreasureMap{
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures
Scanner kbd = new Scanner(System.in);
// Prompt the user for info on the treasure map and then create it
// COMPLETE THIS METHOD
public TreasureMap(){
int numberOfTreasures = 0;
System.out.println("Enter map size (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
System.out.println("Enter number of treasures (1 int): ");
numberOfTreasures = kbd.nextInt();
treasureLocations = new Coord[numberOfTreasures];
for (int i = 0; i < numberOfTreasures; i++)
{
System.out.println("Enter treasure " + i + " location (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
treasureLocations[i] = new Coord(rows, cols);
}
}
// Read the string representation of a map from a file
// COMPLETE THIS METHOD
public TreasureMap(String fileName) throws Exception{
rows = 0;
cols = 0;
int treasures = 0;
char x = 'X';
Scanner data = new Scanner(new File(fileName));
while(data.hasNextLine())
{
String line = data.nextLine();
for (int i = 0; i < line.length(); i++)
{
if(x == line.charAt(i))
{
treasures++;
}
}
cols = line.length();
rows++;
}
int location = 0;
treasureLocations = new Coord[treasures];
Scanner temp = new Scanner (new File(fileName));
while(temp.hasNextLine())
{
String line = temp.nextLine();
for(int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
}
}
// true if there is treasure at the given (r,c) coordinates, false
// otherwise
// This method does not require modification
public boolean treasureAt(int r, int c){
for(int i=0; i<treasureLocations.length; i++){
Coord coord = treasureLocations[i];
if(coord.row == r && coord.col == c){
return true;
}
}
return false;
}
// Create a string representation of the treasure map
// This method does not require modification
public String toString(){
String [][] map = new String[this.rows][this.cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
map[i][j] = ".";
}
}
for(int i=0; i<treasureLocations.length; i++){
Coord c = treasureLocations[i];
map[c.row][c.col] = "X";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
sb.append(map[i][j]);
}
sb.append("\n");
}
return sb.toString();
}
}
You should not use the for i as you do. Your i means the current row, doesn't it? So every time you input a line(temp.nextLine()), your i must be added one.
int i=0;
while(temp.hasNextLine())
{
String line = temp.nextLine();
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
++i;
}
public class leftrec {
static int isleft(String[] left,String[] right)
{
int f=0;
for(int i=0;i<left.length;i++)
{
for(int j=0;j<right.length;j++)
{
if(left[i].charAt(0)==right[j].charAt(0))
{
System.out.println("Grammar is left recursive");
f=1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
String[] left=new String[10];
String[] right=new String[10];
Scanner sc=new Scanner(System.in);
System.out.println("enter no of prod");
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("enter left prod");
left[i]=sc.next();
System.out.println("enter right prod");
right[i]=sc.next();
}
System.out.println("the productions are");
for(int i=0;i<n;i++)
{
System.out.println(left[i]+"->"+right[i]);
}
int flag=0;
flag=isleft(left,right);
if(flag==1)
{
System.out.println("Removing left recursion");
}
else
{
System.out.println("No left recursion");
}
}
}
I've written this code to find out if the given grammar is left recursive or not. When i compile the program it gives me NullPointerException in lines
if(left[i].charAt(0)==right[j].charAt(0))
and
isleft(left,right);
How do i remove the exception ?
I Guess the problem with your inputs , You are just taking the String Array lengths as 10.
String[] left=new String[10];
String[] right=new String[10];
Dont HardCode the String Array length
int n=sc.nextInt();
String[] left=new String[n];
String[] right=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter left prod");
left[i]=sc.next();
System.out.println("enter right prod");
right[i]=sc.next();
}
Might ,this would be the problem
You need to change the code as follows::
package com.cgi.ie2.common;
import java.util.Scanner;
public class LeftRecursive {
static int isleft(String[] left, String[] right)
{
int f = 0;
for (int i = 0; i < left.length; i++) {
for (int j = 0; j < right.length; j++)
{
if (left[i].charAt(0) == right[j].charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
//Changes done here::::
String[] left = new String[n];
String[] right = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
left[i] = sc.next();
System.out.println("enter right prod");
right[i] = sc.next();
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left[i] + "->" + right[i]);
}
int flag = 0;
flag = isleft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}
}
This code will eliminate the NullpointerExceptions
If you getting the no. of prod from the console, the String arrays need to set accordingly,for that the changes i have done are::
System.out.println("enter no of prod");
int n = sc.nextInt();
//Changes done here::::
String[] left = new String[n];
String[] right = new String[n];
And for better codes what i can suggest you is you need to follow basic coding conventions,which makes your codes readable,codes are not perfect only if it runs corectly,codes are perfect if a coding conventions are follow,so please go through the following links to undestand basic idea of coding conventions::
http://www.javacodegeeks.com/2012/10/java-coding-conventions-considered-harmful.html
http://java.about.com/od/javasyntax/a/nameconventions.htm
you can`t initialize an array without size. You have already given the array sizes as 10 and if you enter products which bigger than 10 or smaller than 10 you will get errors. There fore if you want to use dynamic size , you should use a java collection. best approach for this is array list
static int isLeft(ArrayList left, ArrayList right)
{
int f = 0;
for (int i = 0; i < left.size(); i++) {
for (int j = 0; j < right.size(); j++)
{
if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
String leftText = sc.next();
left.add(leftText);
System.out.println("enter right prod");
String rightText = sc.next();
right.add(rightText);
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left.get(i) + "->" + right.get(i));
}
int flag;
flag = isLeft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}