I am writing a program that reverses 2 4 digit numbers, and I wrote a method that will do it. There are no errors in the project build, but I get "String index out of range: -3" when I try to run it. I am fairly new to programming and I have no idea what I did wrong.
Here's the code:
public static void main(String[] args)
{
int num1 = 1;
int num2 = 1;
Scanner console = new Scanner(System.in);
while (num1 <1000 || num1 > 9999)
{
System.out.println("Please enter a positive 4 digit number");
num1 = console.nextInt();
}
String numString1 = Integer.toString(num1);
while (num2 <1000 || num2 > 9999)
{
System.out.println("Please enter another positive 4 digit number");
num2 = console.nextInt();
}
String numString2 = Integer.toString(num2);
int numReverse1 = stringReverse(numString1);
int numReverse2 = stringReverse(numString2);
System.out.println(numReverse1 + numReverse2);
System.out.println("The product of your 2 reversed numbers is: " + (numReverse1 * numReverse2));
}
public static int stringReverse (String numString)
{
String c1c2c3 = numString.substring(4);
String c2c3c4 = numString.substring(1);
String c1c2 = c1c2c3.substring(3);
String c3c4 = c2c3c4.substring(1);
String c1 = c1c2.substring(2);
String c2 = c1c2.substring(1);
String c3 = c3c4.substring(2);
String c4 = c3c4.substring(1);
String numStringReverse = c4 + c3 + c2 + c1;
int reversedString = Integer.parseInt(numStringReverse);
return reversedString;
}
}
In the line:
String c1c2c3 = numString.substring(4);
String c1c2 = c1c2c3.substring(3);
You are trying to access a position that does not exists. Arrays in Java are started by 0 til " - 1".
Start index is inclusive, end index is exclusive in substring method.
A correct version for stringReverse` would be this:
public static int stringReverse (String numString)
{
String c1c2c3 = numString.substring(0,3);
String c2c3c4 = numString.substring(1,4);
String c1c2 = c1c2c3.substring(0,2);
String c3c4 = c2c3c4.substring(1,3);
String c1 = c1c2.substring(0,1);
String c2 = c1c2.substring(1,2);
String c3 = c3c4.substring(0,1);
String c4 = c3c4.substring(1,2);
String numStringReverse = c4 + c3 + c2 + c1;
int reversedString = Integer.parseInt(numStringReverse);
return reversedString;
}
Also, try reading this answer.
There are perhaps more elegant ways to reverse a string in Java. If you want an easy alternative in Java look at the class java.lang.StringBuilder.
Check the documentation and look for the reverse method.
Related
I'm having an issue with this particular program. To cut a long story short, what this program is supposed to do is to get input from a text file, in this case the names and scores of bowlers, and read data off of it. The issue I'm having is trying to extract the scores from the file and storing them in separate variables.
`
import java.util.*;
import java.io.*;
public class lab5{
public static void main (String args[]) throws IOException {
String bowler;
String name;
int score1 = 0, score2 = 0, score3 = 0;
int game = 0;
int average = 0;
//Scanner scan = new Scanner (new FileReader("bowl1.txt."));
Scanner scan = new Scanner (new File ("bowl1.txt"));
while (scan.hasNext()){
bowler = scan.nextLine();
System.out.println("\n" + bowler);
String charCheck = "";
String indent = "";
int count = bowler.length() - 1;
while (count <= bowler.length()){
indent = bowler.lastIndexOf(" ");
charCheck = bowler.substring(0,indent);
System.out.println(charCheck);
count++;
score1 = Integer.parseInt(charCheck);
score2 = Integer.parseInt(charCheck);
score3 = Integer.parseInt(charCheck);
}//end while
System.out.println(score1 + score2 + score3);
}//end fileScan while
}//end main
}//end class
I apologize that my code is a bit sloppy, but I am still learning some of the basics of java. Basically, the idea here is that I need to use the Substring and lastIndexOf(" ") methods to read the scores from the file, and then using Integer.parseInt() to turn them into integers.
(The file is called "bowl1.txt", and this is the data on it)
Atkison, Darren 188 218 177
Barnes, Chris 202 194 195
Dolan, Anthony 203 193 225
Easton, Charles 255 213 190
Any help or hints on what I'm missing would be greatly appreciated.
When you call bowler.substring(0, indent) you actually substring the name of the bowler, so it doesn't contains the scores.
If you want to get only the scores part of the string, use bowler.substring(indent + 1, bowler.length). You still have to break it to 3 different strings and convert each one of them into a integer.
Anyway, a better approach will be to split each line into an array of strings using String#split print the first strings, since it is the bowler name and then convert the last 3 into integers. You can also use Scanner#nextInt() and Scanner#nextString() methods, since the structure of the file is known.
Introduced a class Bowler to store each row of data. You can now use the list of bowler objects to continue your process. String.split() gives an array of Strings tokenized based on the character specified. Space has been used here to split.
import java.util.*;
import java.io.*;
public class lab5 {
public static void main(String args[]) throws IOException {
Scanner scan = new Scanner(new File("C:\\TEMP\\bowl1.txt"));
String bowler;
List<Bowler> bowlers = new ArrayList<Bowler>();
while (scan.hasNext()) {
bowler = scan.nextLine();
if (!bowler.trim().equals("")) {
System.out.println("\n" + bowler);
String[] tokens = bowler.split(" ");
Bowler b = new Bowler(tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]),
Integer.parseInt(tokens[4]));
bowlers.add(b);
}
} // end fileScan while
for (Bowler bow : bowlers) {
System.out.println(bow.score1 + ", " + bow.score2 + ", " + bow.score3);
}
}// end main
}// end class
class Bowler {
String firstName;
String lastName;
int score1;
int score2;
int score3;
public Bowler(String firstName, String lastName, int score1, int score2, int score3) {
this.firstName = firstName;
this.lastName = lastName;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
}
}
Okay this is a straight forward method....it is done only using lastIndexOf(" ") and substring("") method as you said. but there are lot efficient and more easy ways as Narayana Ganesh mentioned above....this method also can be more
precised if you want....
import java.io.;
import java.util.;
public class test2
{
public static void main(String[] args)
{
String bowler;
String name;
int score1 = 0, score2 = 0, score3 = 0;
int game = 0;
int average = 0;
String filename = "bowl1.txt";
File textfile = new File(filename);
try{
Scanner scan = new Scanner(textfile);
while (scan.hasNextLine()){
bowler = scan.nextLine();
System.out.println("\n" + bowler);
String text1 = "";
String text2 = "";
int index=0;
int length = bowler.length();
index = bowler.lastIndexOf(" ");
text1 = bowler.substring(0,index);
text2 = bowler.substring(index+1,length);
score1 = Integer.parseInt(text2);
length = text1.length();
index = text1.lastIndexOf(" ");
text2 = text1.substring(index+1,length);
text1 = text1.substring(0,index);
score2 = Integer.parseInt(text2);
length = text1.length();
index = text1.lastIndexOf(" ");
text2 = text1.substring(index+1,length);
text1 = text1.substring(0,index);
score3 = Integer.parseInt(text2);
System.out.println(score1);
System.out.println(score2);
System.out.println(score3);
System.out.println("Total:"+(score1 + score2 + score3));
}
}catch(FileNotFoundException e){};
}
}
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 😂
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 ^^
I need help with my java-program. This program is supposed to ask for the highest value fibonacci can have, and print out the number of series up to that value, but it doesn't work. Any suggestions?
import java.util.Scanner;
public class Fibonacci {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("The largest number fibonacci can be: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
}
int i;
int f0 = 0;
int f1 = 1;
int fn;
int value=0;
for (i = 0; i<=value; i++){
fn = f0 + f1;
System.out.println("Fibonacci-number " + i + " = " + f0);
f0 = f1;
f1 = fn;
value = number - f0;
}
}
}
If i put in number = 12, the program is supposed to print:
fibonacci-number 0 = 0
...
fibonnaci-number 12 = 144
Just change the loop to compare value of increment-er (i) to 'number ' variable
for (i = 0; i<=number; i++){
//.........
}
Also use double instead of int if you want to print higher number in the series correctly.
There is no use of the 'value' variable.
Also, the phrase 'the highest value fibonacci can have' is misleading.You have mentioned number denotes number of terms in the series in your example.
If you want 'number' to be the highest value in the series, use following approach,
do{
fn = f0 + f1;
System.out.println("Fibonnaci-tall " + i + " = " + f0);
f0 = f1;
f1 = fn;
i++;
}while(f0<=number);
Is this what you are looking for?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int f0 = 0;
int f1 = 1;
int fn = 0;
System.out.println("The largest number fibonnaci can be: ");
System.out.println("Input your number: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
} else {
System.out.println(f0);
System.out.println(f1);
while (fn < number){
fn = f0 + f1;
f0 = f1;
f1 = fn;
if (fn < number){
System.out.println(fn);
}
}
}
}
enter image description here
Use this program, it will solve your query.
Try this...It works!
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("The largest number fibonacci can be: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
}
else{
int i=0;
int f0 = 0;
int f1 = 1;
int fn;
int value=0;
do{
//for (i = 0; i<=value; i++){
fn = f0 + f1;
System.out.println("Fibonacci-number " + i + " = " + f0);
f0 = f1;
f1 = fn;
value = number - f0;
i++;
}while(f0<=number);
}//else
}
This is my second time asking this question because this assignment is due tomorrow, and I am still unclear how to progress in my code! I am in an AP Computer programming class so I am a complete beginner at this. My goal (so far) is to multiply two fractions. Is there any way to use a variable inside a particular method outside of that method in another method? I hope that wasn't confusing, thank you!!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
Is there any way to use a variable inside a particular method outside of that method in another method?
Yes you can do that. You can declare a variable in a method, use it there and pass it to another method, where you might want to use it. Something like this
void test1() {
int var = 1;
System.out.println(var); // using it
test2(var); // calling other method and passing the value of var
}
void test2(int passedVarValue) {
System.out.println(passedVarValue); // using the passed value of the variable
// other stuffs
}