How to integrate a loop in my code - java

I am new to Java. My program first gets inputs from the user about their car, and then it shows the result.
I need to integrate my "Rövarspråk" in to the code, but I am not really sure how.
If the user owns a "Saab" or a "Volvo" the "rövarspråk" loop should change the user's "string name".
If something is unclear, just tell me and I'll try to explain better.
Thanks in advance.
public static void main(String[] args) {
String lookSaab;
String consonantsx;
String input;
String slang;
String add;
// String
int length;
// int
Scanner skriv;
// Scanner
String reg;
String year;
String brand;
String name;
String car;
String when;
String small;
String medium;
String big;
// String
int mod;
int randomNumber;
int quota;
int denominator;
// int
reg = JOptionPane.showInputDialog("Ange registreringsnummer"); // Input plate number of your car
year = JOptionPane.showInputDialog("Ange årsmodell"); // Input model year of the car
mod = Integer.parseInt(year);
brand = JOptionPane.showInputDialog("Ange bilmärke"); //Input car brand
name = JOptionPane.showInputDialog("Ange ägare "
+ "(för - och efternamn)"); //Input owner of the car first name + last name
car = brand + reg;
Date date = new Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE MMM dd");
when = sdf.format(date);
denominator = 1500;
randomNumber = 1500 + (int)(Math.random() * ((40000 - 1500) + 1));
quota = randomNumber / denominator;
small = "Liten service";
medium = "Medium service";
big = "Stor service";
if (randomNumber <= 8000){
JOptionPane.showMessageDialog(null, small, "Typ av service", 1);
} else if ( randomNumber <= 20000){
JOptionPane.showMessageDialog(null, medium, "Typ av service", 1);
} else {
JOptionPane.showMessageDialog(null, big, "Typ av service", 1);
}
String resultat = "Bil: " + car + "\n"
+ "Årsmodell: " + mod + "\n"
+ "Ägare: " + name + "\n"
+ "Mästarställning: " + randomNumber + "\n"
+ "Inlämnad: " + when + "\n"
+ "Klar om: " + quota + " dagar";
JOptionPane.showMessageDialog(null, resultat, "Resulat", 1);
lookSaab = "Saab";
if (brand.equals(lookSaab)){
}
/* Rövarspråket */
consonantsx = "bBcCdDeEfFgGhHjJkKlLmMnNpPqQrRsStTvVwWxXzZ"; //Saves all consonants to string
char consonants[] = consonantsx.toCharArray(); //String to charr
System.out.println("Mata in en mening");
skriv = new Scanner(System.in);
input = skriv.nextLine(); //Saves the input
length = input.length(); //Length inc. space
char array[] = input.toCharArray(); // Input to a char array
slang = "";
System.out.println("På rövarspråk:");
for(int i = 0; i<length; i++) {
for(int x = 0; x<20; x++){
if(array[i] == consonants[x])
{
add = array[i]+"o"+array[i];
slang = slang + add;
break;
}
else{
}
}
}
System.out.println(slang);
}
}

OK so as mentioned a good start would be to put your RoverSpraket translator into its own method:
public String rovarSpraket(String normalString) {
final String consonantsx = "bBcCdDeEfFgGhHjJkKlLmMnNpPqQrRsStTvVwWxXzZ";
char consonants[] = consonantsx.toCharArray(); // String to charr
int length = normalString.length(); // Length inc. space
char array[] = normalString.toCharArray(); // Input to a char array
String slang = "";
System.out.println("På rövarspråk:");
for (int i = 0; i < length; i++) {
for (int x = 0; x < 20; x++) {
if (array[i] == consonants[x]) {
String add = array[i] + "o" + array[i];
slang = slang + add;
break;
} else {
}
}
}
return slang;
}
This method takes a "normal" String as input and returns the Rövarspråk version of it.
Given that it can be used anywhere you want now, like:
/i named my class "Goran" ;)
Goran goran = new Goran(); //instatiate a class object
String hello = "hello world";
System.out.println(goran.rovarSpraket(hello)); //use class object method "roverSpraket"
This will print as the following on the console:
På rövarspråk:
hoheoelollolloldod
Only thing left to do is use this in the remaining code. I guess what you want is that:
if (brand.equals("Saab") || brand.equals("Volvo")){
name = rovarSpraket(name); //translate if brand is Saab or Volvo
}
And a working example for calling the method (one way to do it)
public class Goran {
public static void main(String[] args) {
String brand;
String name;
//i named my class "Goran" ;)
Goran goran = new Goran(); //instatiate a class object
String hello = "hello world";
System.out.println(goran.rovarSpraket(hello)); //use class object method "roverSpraket"
brand = "Saab";
name = "henry";
if (brand.equals("Saab") || brand.equals("Volvo")){
name = goran.rovarSpraket(name); //translate if brand is Saab or Volvo
}
System.out.println("new name is " + name);
}
public String rovarSpraket(String normalString) {
final String consonantsx = "bBcCdDeEfFgGhHjJkKlLmMnNpPqQrRsStTvVwWxXzZ";
char consonants[] = consonantsx.toCharArray(); // String to charr
int length = normalString.length(); // Length inc. space
char array[] = normalString.toCharArray(); // Input to a char array
String slang = "";
System.out.println("På rövarspråk:");
for (int i = 0; i < length; i++) {
for (int x = 0; x < 20; x++) {
if (array[i] == consonants[x]) {
String add = array[i] + "o" + array[i];
slang = slang + add;
break;
} else {
}
}
}
return slang;
}
}
Hope this helps ^^

Related

I am unsure of why my code is resulting in an Exception in thread "main" java.util.NoSuchElementException error and how I should resolve it

Query by loan ID
// Method that allows the user to query by loan ID
public static void QuerybyloanID(List<Loan> data) {
try (Scanner entry = new Scanner(System.in)) {
System.out.print("Please, enter the loan ID: ");
String userentry = entry.next();
// For loop is used to locate the loan ID within the list of loans
for (int i = 0; i < data.size(); i++) {
String loanID = data.get(i).getLoanID();
if (loanID.equals(userentry)) {
boolean pass = true;
String loanPassword = data.get(i).getPasscode();
// Three possible character from the loan password
int one;
int two;
int three;
int [] randomCharacters = randomUniqueGenerator(3, loanPassword.length());
one = randomCharacters[0];
two = randomCharacters[1];
three = randomCharacters[2];
// Check to see if the random numbers are the same or different. -> Implement a Hash Map.
char entry_one = loanPassword.charAt(one);
char entry_two = loanPassword.charAt(two);
char entry_three = loanPassword.charAt(three);
String entry_one_modify = Character.toString(entry_one);
String entry_two_modify = Character.toString(entry_two);
String entry_three_modify = Character.toString(entry_three);
String [] entriesmain = {entry_one_modify, entry_two_modify, entry_three_modify};
try (Scanner entrytwo = new Scanner(System.in)) {
for (int k = 0; k < 3; k ++) {
System.out.print("Enter character " + randomCharacters[k] + " of the loan pass code: ");
String userentrytwo = entrytwo.next();
entrytwo.nextLine();
if (userentrytwo.equals(entriesmain[k])) {
continue;
} else {
pass = false;
continue;
}
}
}
// Check to see if pass is true or false then take the appropriate action
if (pass) {
System.out.println("Customer Name: " + data.get(i).getFirstName() + " " + data.get(i).getLastName());
System.out.println("Branch Code: " + data.get(i).getBrachCode());
System.out.println("Gender: " + data.get(i).getGender());
System.out.println("Date of Birth: " + data.get(i).getDOB());
System.out.println("Loan Amount: " + data.get(i).getLoanAmount());
System.out.println("Customer Phone Number: " + data.get(i).getPhoneNumber());
MainMenu.options();
} else {
System.out.println("Wrong Passcode !");
MainMenu.options();
}
}

How do I check to see if a user Input matches an element of a 2D array? JAVA

I am creating a student grade book that allows a user to input their students names and 4 grades, then have options to calculate student and class averages, as shown in the pic below.
With the code below, I am receiving the student average as "0.0%" and no errors. Am I correctly instructing the program to see if the students name matches the appropriate element in the two-dimensional array?
I have all the other parts of the program working.
private String[][] grades = new String[16][5];
//Declare Variables
String firstName, lastName, name;
String test1, test2, test3, test4;
test1 = t1Input.getText();
test2 = t2Input.getText();
test3 = t3Input.getText();
test4 = t4Input.getText();
firstName = firstInput.getText();
lastName = lastInput.getText();
name = firstName + " " + lastName + ": ";
grades[students][0] = name;
grades[students][1] = test1;
grades[students][2] = test2;
grades[students][3] = test3;
grades[students][4] = test4;
students++;
private void sAvgInputActionPerformed(java.awt.event.ActionEvent evt) {
String firstName = firstInput.getText();
String lastName = lastInput.getText();
String name = firstName + " " + lastName + ": ";
int sum = 0;
double divide = 0;
for (int i = 0; i <= 1; i++) {
if (name.equals(grades[0][1])) {
for (int grade = 1; grade <= 4; grade++) {
sum = Integer.parseInt(grades[i][1]) + i;
}
break;
}
}
divide = sum / 4;
gradesOutput.setText(firstName + "'s grade average is " + divide + "%.");
}
Change the loop to this:
//assume it as a simple table since its 2d array
//Since you are storing the name in first(0th index) column,
//only row should be loop
for (int i = 0; grades[i][0] != null; i++) {
if (name.equals(grades[i][0])) {
for (int grade = 1; grade <= 4; grade++)
//same row,different column
sum = sum + Integer.parseInt(grades[i][grade]);
break;
}
}

I keep getting the error "Index 5 out of bounds for length 5" but don't know what to change

I'm pretty new to coding so please bear with me, I am just experimenting with ways to shuffle an array for eventual use in shuffling a deck of cards in a card game I am creating in Java. I know that index 5 is out of bounds for length 5 but what is puzzling to me is that the error doesn't ALWAYS pop up. Sometimes I try to run my code and it works just fine, other times I get the error even if I haven't changed anything between times that I run it.
public class Card{
public static void shuffle(Object[] array) {
int noOfCards = array.length;
for (int i = 0; i < noOfCards; i++) {
int s = i + (int)(Math.random() * (noOfCards - 1));
Object temp = array[s]; //this is the first line it says has a problem
array[s] = array[i];
array[i] = temp;
}
}
public static void main(String[] args) {
String[] strOfCards = {"A","B","C","D","E"};
Card.shuffle(strOfCards); //this is the second line that has a problem
for(int i = 0; i < strOfCards.length; i++) {
System.out.println(strOfCards[i] + " ");
}
}
}
I have no idea how to change the flawed lines, any suggestions are welcome!
*** i have tried changing the number of letters in the string but then the error changes with it i.e. "Index 6 out of bounds for length 6"
Consider the lines:
for (int i = 0; i < noOfCards; i++) {
int s = i + (int)(Math.random() * (noOfCards - 1));
Object temp = array[s]; //this is the first line it says has a problem
i varies from 0 to noOfCards - 1
Your random number expression varies from 0 to noOfCards - 2
So s varies from 0 to (2 * noOfCards) - 3
Then array[s] will throw an exception whenever s >= noOfCards
It doesn't happen every time you run it because sometimes the random numbers all happen to be under noOfCards
If you want to swap with a random other card then you could try:
Random random = new Random();
int s = (i + random.nextInt(noOfCards - 1)) % noOfCards;
I realise you're using this as a learning opportunity, but in case you weren't aware, there is a Collections.shuffle method that can be used to shuffle collections such as ArrayList in one command.
Max index of array with length N is (N-1). Code should be like this:
public static void shuffle(Object[] array) {
int noOfCards = array.length;
Random random = new Random();
for (int i = 0; i < noOfCards; i++) {
int s = random.nextInt(noOfCards);
Object temp = array[s];
array[s] = array[i];
array[i] = temp;
}
}
Here is the line that causes the trouble:
int s = i + (int)(Math.random() * (noOfCards - 1));
Whenever the value s is >= 5, the array[s] will point to something out of bound.
For example i can be 3, if Math.random() returns something like 0.5, then 3 + (int)(0.5 * 4) is equal to 5, which is out of bound (0..4)
It doesn't happen all the times, because some times the Math.random() generates small enough number, so the evaluation of s is smaller than 5.
To ensure that the value of s always in the range (0..4), you should modulo the result to 5.
Here is how the line should be:
int s = (i + (int)(Math.random() * (noOfCards - 1))) % 5;
change this line
int s = i + (int)(Math.random() * (noOfCards - 1));
to this
int s = (int)(Math.random() * (noOfCards - 1));
just remove i variable from the above code
You need to remember that indices are zero-based in Java.
Note a couple of things:
- make things final if they're final
- use SecureRandom: it is more random than Random
- use the nextInt(n) method of SecureRandom to get an int in your range
- note the use of Streams to print out the result
import java.security.SecureRandom;
import java.util.stream.Stream;
public class Card {
public static void shuffle(final Object[] array) {
final SecureRandom random = new SecureRandom();
final int noOfCards = array.length;
for (int i = 0; i < noOfCards; i++) {
final int s = random.nextInt(noOfCards);
final Object temp = array[s];
array[s] = array[i];
array[i] = temp;
}
}
public static void main(final String[] args) throws Exception {
final String[] strOfCards = {"A","B","C","D","E"};
Card.shuffle(strOfCards);
Stream.of(strOfCards).forEach(System.out::println);
}
}
If you fancy using a List it's a bit more compact:
import java.security.SecureRandom;
import java.util.*;
import java.util.stream.IntStream;
public class Card {
public static void main(final String[] args) throws Exception {
final SecureRandom random = new SecureRandom();
final List<String> cards = Arrays.asList("A", "B", "C", "D", "E");
IntStream.range(0, cards.size()).forEach(i ->
Collections.swap(cards, i, random.nextInt(cards.size()))
);
cards.forEach(System.out::println);
}
}
M getting the same issue with this code and still no idea how to solve it
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Main
{
public static void main (String[] args)
{
while (true)
{
String number = JOptionPane.showInputDialog("Please Enter \n"
+ "1 for 'Add new Employee'"
+ "\n 2 for 'Search in employee'"
+ "\n 3 for 'Exit'");
int convertnumber = Integer.parseInt(number);
if (convertnumber == 1)
{
addEmployee();
}
else if (convertnumber == 2)
{
String eId = JOptionPane.showInputDialog("Enter ID to search");
searchEmplye(eId);
}
else if (convertnumber == 3)
{
JOptionPane.showMessageDialog(null, "Developed By: BC180401942 SHEHZAD ADEEL");
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null, "Invalid input");
}
}
}
public static void searchEmplye(String eId)
{
try
{
String tokens[] = null;
String id, name, dob, qual, expe, pays;
FileReader fr = new FileReader("empData.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
if (line == null)
{
JOptionPane.showMessageDialog(null, "Employee Not found");
}
while (line != null)
{
tokens = line.split (",");
id = tokens[0];
name = tokens[1];
dob = tokens[2];
qual = tokens[3];
expe = tokens[4];
pays = tokens[5];
Employee emp = new Employee (id, name, dob, qual, expe, pays);
ArrayList list = new ArrayList();
list.add(emp);
line = br.readLine();
/*
for (int i = 0; i < list.size(); i++)
{
Employee p = (Employee) list.get(i);
if (eId.equals(p.getEmpId()))
{
JOptionPane.showMessageDialog(null, "Employee: \n"
+ "Employee ID: " + p.getEmpId()
+ " \n Employee Name: " +p.getEmpName()
+ " \n Employee DOB: " + p.getEmpDoB()
+ " \n Qualification: " + p.getEmpQualf()
+ " \n Experience: " + p.getEmpExp()
+ " \n Pay Scal: " + p.getEmpPSacle()
);
}
*/
for (int i = 0; i < list.size(); i++)
{
Employee p = (Employee) list.get(i);
if (eId.equals(p.getEmpId()))
{
JOptionPane.showMessageDialog( null, "Employee: \n" +
"EmpId: " + p.getEmpId() + "\n" +
"Name: " + p.getEmpName() + "\n" +
"DoB: " + p.getEmpDoB() + "\n" +
"Qualification: " + p.getEmpQualf() + "\n" +
"Experience: " + p.getEmpExp() + "\n" +
"PayScale: " + p.getEmpPScale() );
}
else
{
JOptionPane.showMessageDialog(null, "Employee Not found");
}
}
}
br.close();
fr.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void addEmployee()
{
try
{
ArrayList list = new ArrayList();
String id = JOptionPane.showInputDialog("Enter Employee ID: ");
String name = JOptionPane.showInputDialog("Enter name: ");
String dob = JOptionPane.showInputDialog("Enter DoB (year): ");
String qual = JOptionPane.showInputDialog("Enter Qualification: ");
String exp = JOptionPane.showInputDialog("Enter Employee experience (in months): ");
String pays = JOptionPane.showInputDialog("Enter Employee Pay Scale (in number): ");
Employee emp = new Employee (id, name, dob, qual, exp, pays);
list.add(emp);
/*
ArrayList list = new ArrayList();
String id = JOptionPane.showInputDialog("Enter ID ");
String name = JOptionPane.showInputDialog("Enter Name ");
String dob = JOptionPane.showInputDialog("Enter DOB ");
String qualification = JOptionPane.showInputDialog("Enter qualification ");
String experience = JOptionPane.showInputDialog("Enter Employee Experience");
String paScale = JOptionPane.showInputDialog("Enter Employee pay scale ");
Employee emp = new Employee(id, name, qualification, experience, paScale);
list.add(emp);
*/
String line;
FileWriter fw = new FileWriter("empData.txt");
PrintWriter pw = new PrintWriter(fw);
for (int i = 0; i < list.size(); i++)
{
emp = (Employee) list.get(i);
//line = emp.getEmpId() + "," + emp.getEmpName() + "," + emp.getEmpDoB() + "," + emp.getEmpQualf() + "," + emp.getEmpExp() + "," + emp.getEmpPSacle();
line = emp.getEmpId() + "," +
emp.getEmpName() + "," +
emp.getEmpDoB() + "," +
emp.getEmpQualf() + "," +
emp.getEmpPScale();
pw.println(line);
}
pw.flush();
pw.close();
fw.close();
}
catch (IOException ioEx)
{
System.out.println(ioEx);
}
}
}

Keep track of string matches to create a new ID

This is the prompt
Write a program that reads in a name and outputs an ID based on the name. The ID should be uppercase and formatted using the first three letters of the name and three digits starting at 005. The digits should be incremented by 5 if an ID already exists.
This is my code so far
import java.util.Scanner;
public class substring_match {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int id = 5;
int repeatId = 5;
int nameCount = 1;
String[] nameArray = new String[5];
String name;
String subName = null;
for (int i = 0; i<nameArray.length; i++){
name = scan.nextLine();
subName = name.substring(0, 3);
nameArray[i] = subName;
}
for(int x = 0; x < nameArray.length; x++){
if(nameArray[x].substring(0, 3) == subName.substring(0,3)){
nameCount = nameCount + 1;
System.out.println("nameCount " + nameCount);
repeatId = nameCount * id;
if(repeatId == 5){
System.out.println(nameArray[x].toUpperCase() + "00" + repeatId);
}else{ // if repeatId is 10 or higher, won't need the extra 0
System.out.println(nameArray[x].toUpperCase() + "0" + repeatId);
}
}else{
System.out.println(nameArray[x].substring(0, 3).toUpperCase() + "00" + id);
}
}
}
}
I would probably consider doing this another way...
Have an empty hashmap<String sub, int multiplier>
Read in the name
Generate the subname
Fetch from or create subname in hashmap
If new, set multiplier to 1
If exists, increment multiplier
Return String.format(“%s%3d”, subname, multiplier x 5).toUpperCase()
I would give you code but writing the above was hard enough on an iPad 😂

Java queue only printing out last element within for loop.

I'm creating a Java array of queues program to represent patients in a doctor array. It lets me add nodes in data structure but when I try to print it out it blows up on me. Here is the method
static boolean [] openflag = new boolean[6];
static queue [] Clinic = new queue[6];
static String [] Doctor = {"Doctor 1", Doctor 2", "Doctor 3","Doctor
4","Doctor 5","Doctor 6"};
final static String HEADING = "The clinic moniter of Dylan Rychlik";
static int MAX = 6;
public static void Listpaitents()
{
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is notaviable");
}
else{
Paitent[] array = Clinic[queuechoice -1].toArray();
//int size = Clinic[queuechoice -1].getSize();
int limit = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 1; x <= limit; x++) {
out += array[x-1].Print() + "\n";
// System.out.println(array[x-1] + "\n");
}
JOptionPane.showMessageDialog(null,out);
}
}
Here is the toarray() method in queue class.
public static Paitent[] toArray()
{
int x = Length;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = Length; ((Current != null) && (x >= 1));x--)
{
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
}
return Array;
}
And finally, here is the paitent class
public class Paitent {
protected static String name;
protected static String telephone;
protected static int ID;
//Creates a constructor for a paitent object
public void paitent()
{
name = "";
telephone = " ";
ID = 0;
}
//updates the country object
public void update(Paitent thisThing)
{
name = thisThing.name;
telephone = thisThing.telephone;
ID = thisThing.ID;
}
//asks for user input for country objects
public void input(int i)
{
String PatronHeading = "Country Data Entry";
String entername;
int enterID;
String enterphone;
entername = JOptionPane.showInputDialog(null, "Please Enter the name of
paitent #" + i +": ", PatronHeading, JOptionPane.QUESTION_MESSAGE);
enterphone = JOptionPane.showInputDialog(null, "Please Enter the telephone
number for paitent #" + i +": ", PatronHeading,
JOptionPane.QUESTION_MESSAGE);
String PNumberString = JOptionPane.showInputDialog(null, "Please Enter the
ID for paitent #" + i +": ", PatronHeading, JOptionPane.QUESTION_MESSAGE);
enterID = Integer.parseInt(PNumberString);
name = entername;
telephone = enterphone;
ID = enterID;
}
//prints the results
public String Print()
{
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number " +
telephone + " ID " + ID;
return outputString;
}
//gets and sets the PCI in order to sort them
}
Any help? Tried several tactics to fix it and nothing seems to be working. There a lot of code so if you need the full code please let me know!
A problem with your code is that you are using static variables. This means they can only ever have one value
so change
protected static String name;
protected static String telephone;
protected static int ID;
to
protected String name;
protected String telephone;
protected int ID;
edit and clean up your code

Categories

Resources