I keep getting this error and i can't figure out why:
Glosor.java:102: error: variable språk1 might not have been initialized
JOptionPane.showInputDialog(null, språk1 + ":" + språk1glosor + "\n" + språk2 + ":");
^
Glosor.java:102: error: variable språk2 might not have been initialized
JOptionPane.showInputDialog(null, språk1 + ":" + språk1glosor + "\n" + språk2 + ":");
This is my code:
javax.swing.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.io.*;
public class Glosor {
public static void main(String[] args) throws IOException {
List<String> gloslista1 = new LinkedList<String>(Arrays.asList());
List<String> gloslista2 = new LinkedList<String>(Arrays.asList());
String inputStr1 = JOptionPane.showInputDialog(null,
"**********************************" + "\n\n" +
"1. Skapa glosövning" + "\n\n" +
"2. Starta glosövning" + "\n\n" +
"3. Avsluta" + "\n\n" +
"**********************************");
int input1 = Integer.parseInt(inputStr1);
switch (input1) {
case 1:
String övningsnamn = JOptionPane.showInputDialog(null, "Vad heter övningen?");
String språk1 = JOptionPane.showInputDialog(null, "Språk 1?");
String språk2 = JOptionPane.showInputDialog(null, "Språk 2?");
while (true) {
String glosa1 = JOptionPane.showInputDialog(null, "Skriv in glosa på " + språk1 + "\n\n" +
"När du är klar skriv klar i rutan");
if(glosa1.equals("klar")) {
break;
}
else {
String glosa2 = JOptionPane.showInputDialog(null, "Skriv in glosa på " + språk2);
gloslista1.add(glosa1);
gloslista2.add(glosa2);
}
}
String filnamn1 = "språk1ord.txt";
String filnamn2 = "språk2ord.txt";
PrintWriter utström1 = new PrintWriter
(new BufferedWriter
(new FileWriter(filnamn1)));
//Skapar en text fil för glosorna på svenska
PrintWriter utström2 = new PrintWriter
(new BufferedWriter
(new FileWriter(filnamn2)));
//Skapar en text fil för glosorna på franska
for(int i = 0; i<=gloslista1.size()-1; i++) {
utström1.println(gloslista1.get(i));
utström2.println(gloslista2.get(i));
//Skriver in glosor i text filerna
}
utström1.close();
utström2.close();
case 2:
String inputStr2 = JOptionPane.showInputDialog(null,
"**********************************" + "\n\n" +
"1. Starta glosövning" + "\n\n" +
"2. Avsluta" + "\n\n" +
"**********************************");
int input2 = Integer.parseInt(inputStr2);
if(input2 == 1) {
BufferedReader inström1 = new BufferedReader
(new FileReader("svenskaord.txt"));
String språk1glosor;
BufferedReader inström2 = new BufferedReader
(new FileReader("franskaord.txt"));
String språk2glosor;
int counter = 0;
while (true) {
counter++;
språk1glosor = inström1.readLine();
språk2glosor = inström2.readLine();
if(counter > gloslista1.size())
break;
String svar = JOptionPane.showInputDialog(null, språk1 + ":" + språk1glosor + "\n" + språk2 + ":");
}
}
You are initializing språk1 in your case 1 and referring to it in both case 1 and case 2. You need to move the initialization out of the case statement:
int input1 = Integer.parseInt(inputStr1);
String övningsnamn = JOptionPane.showInputDialog(null, "Vad heter övningen?");
String språk1 = JOptionPane.showInputDialog(null, "Språk 1?");
String språk2 = JOptionPane.showInputDialog(null, "Språk 2?");
switch (input1) {
Related
The logic I'm trying to construct is when the user collects four total affiliates, the console will print that they've reached four but they can still go on if they choose to.
If they decide to stop at four, they should type "quit". The problem rises at the second while loop with the if else statements. I get the error "aff cannot be resolved".
import java.util.Scanner;
public class Seption {
public static void main(String[] args) {
System.out.println("Welcome back!");
Scanner userName = new Scanner(System.in);
System.out.println("Username: ");
String username = userName.next();
Scanner passWord = new Scanner(System.in);
System.out.println("Password: ");
String password = passWord.next();
int affCount = 0;
while (affCount <= 4) {
Scanner newAff = new Scanner(System.in);
System.out.println("enter new affiliate");
String aff = newAff.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
if (affCount == 4) {
System.out.println("Congratulations! You've accumulated 4 affiliates!"
+ " any new affiliates added to this branch will be extra earnings"
+ " You can also make a new branch and start over"
+ " To quit this branch, Type 'quit'");
continue;
}
}
while (affCount > 4) {
if (aff.equals("quit") == false) {
Scanner newAff = new Scanner(System.in);
System.out.println("enter new affiliate");
String aff = newAff.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
}
else if (aff.equals("quit")) {
System.out.println("This branch is now over");
break;
}
}
}
}
You should just create an instance of the Scanner from System.in once and use that same instance anywhere that you need to get an input from the user:
public static void main(String[] args){
System.out.println("Welcome back!");
Scanner scanner = new Scanner(System.in);
System.out.println("Username: "); String
username = scanner.next();
System.out.println("Password: ");
String password = scanner.next();
int affCount = 0;
String aff = "";
while (affCount <= 4) {
System.out.println("enter new affiliate");
aff = scanner.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
if (affCount == 4)
{
System.out.println("Congratulations! You've accumulated 4 affiliates!" + " any new affiliates added to this branch will be extra earnings" + " You can also make a new branch and start over" + " To quit this branch, Type 'quit'");
continue;
}
}
while (affCount > 4) {
if (aff.equals("quit") == false)
{
System.out.println("enter new affiliate");
aff = scanner.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
}
else if (aff.equals("quit"))
{
System.out.println("This branch is now over");
break; }
}
}
I need to access 'sets' outside the first for loop. How can i do that?
I want to sort on the result but i am not bale to access the result 'sets' outside the for loop. if I sort it inside, I am not getting the sort result as expected.
static Set < String > generateReports() {
try {
String[] parts2;
String part2 = null;
String[] parts3;
String part3 = null;
// String sets = null;
for (i = 1; i < 3; i++) {
String line = null;
FileReader fileReader1 = new FileReader("C:/Projects/Wells Fargo IVR/TestFolder/" + (i) + ".log");
BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
while ((line = bufferedReader1.readLine()) != null) {
String string = line;
parts2 = string.split("-");
if (parts2.length > 4) {
part2 = parts2[4];
sids.put(part2, line);
// System.out.println(sids.get(part2));
}
// if(IVRLogFileMerge.getSid().contains(part2)){
if (testSet.contains(part2)) {
// System.out.println("This is file number" + (i)+ " " + line);
for (String current: testSet1) {
if (line.contains(current)) {
//System.out.println(line);
testSetFinal.add(line);
String string1 = line.replace(" ", " ");
String string2 = string1.replace("default task", "Thread");
parts3 = string2.split(" ");
sets = (parts3[1] + " " + parts3[6] + " " + parts3[8] + " ");
//System.out.print(parts3[1] + " " + parts3[6] + " " + parts3[8] + " ");
for (int j = 10; j < parts3.length; j++) {
//System.out.print(parts3[j] + " ");
// bufferWritter.write(parts3[j] + " ");
sets = sets.concat(parts3[j] + " ");
}
FileWriter fileWritter = new FileWriter("C:/Projects/Wells Fargo IVR/TestFolder/file.txt", true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(sets);
bufferWritter.newLine();
bufferWritter.close();
// System.out.println();
String[] str = new String[] {
sets
};
Arrays.sort(str);
for (String s: str) {
//System.out.println(i + " " + s);
}
}
}
}
//bufferedWriter.write("This is file number" + (i)+ " " + line);
//bufferedWriter.newLine();
}
bufferedReader1.close();
}
//System.out.println(testSetFinal);
You have String sets = null; commented out currently. Uncomment that, and switch it to
String sets = "";
Im loosing on append method.
I have a program that inputs an information then printing in a text file.
The problem is, I want to append the new input of information into text file too without overwriting, it means that if I rerun the program the information that I encoded will be in the textfile together with the encoded on the last run of the program.
Please help me. Here is the program:
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
System.out.println("STUDENT INFORMATION");
System.out.println("-------------------");
System.out.println("Full Name : ");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("\nCourse and Year : ");
String yearcourse = sc.nextLine();
System.out.println("\nStudent Number : ");
String studentnumber = sc.nextLine();
System.out.println("\nE-mail Address : ");
String eadd = sc.nextLine();
System.out.println("\nCellphone Number : ");
String cpnumber = sc.nextLine();
System.out.println("\nGender : ");
String gender = sc.nextLine();
System.out.println("\nAge : ");
String age = sc.nextLine();
System.out.println("\nDate of Birth : ");
String dob = sc.nextLine();
System.out.println("\nCivil Status : ");
String status = sc.nextLine();
System.out.println("\nAddress : ");
String address = sc.nextLine();
System.out.println("\n\n________________________________________________");
System.out.println("STUDENT INFORMATION");
System.out.println("\nName : " + name + "");
System.out.println("Year and Course : " + yearcourse + "");
System.out.println("Student Number : " + studentnumber + "");
System.out.println("E-mail Address : " + eadd + "");
System.out.println("Cellphone Number : " + cpnumber + "");
System.out.println("Gender : " + gender + "");
System.out.println("Age : " + age + "");
System.out.println("Date of Birth : " + dob + "");
System.out.println("Civil Status : " + status + "");
System.out.println("Address : " + address + "");
System.out.println("");
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try (PrintWriter writer = new PrintWriter(file)){
BufferedWriter bufferWritter = new BufferedWriter(writer);
writer.println("\nSTUDENT INFORMATION:");
writer.println("--------------------");
writer.println("Name : " + name + "");
writer.println("Year and Course : " + yearcourse + "");
writer.println("Student Number : " + studentnumber + "");
writer.println("E-mail Address : " + eadd + "");
writer.println("Cellphone Number : " + cpnumber + "");
writer.println("Gender : " + gender + "");
writer.println("Age : " + age + "");
writer.println("Date of Birth : " + dob + "");
writer.println("Civil Status : " + status + "");
writer.println("Address : " + address + "");
writer.flush();
}
}
}
In this. if I rerun the program, the text file will just overwrite with the new encoded information. They said to use append bufferwriter. but I'm really lost.
Try to change your code to something like this:
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println("\nSTUDENT INFORMATION:");
out.println("--------------------");
out.println("Name : " + name + "");
out.println("Year and Course : " + yearcourse + "");
out.println("Student Number : " + studentnumber + "");
out.println("E-mail Address : " + eadd + "");
out.println("Cellphone Number : " + cpnumber + "");
out.println("Gender : " + gender + "");
out.println("Age : " + age + "");
out.println("Date of Birth : " + dob + "");
out.println("Civil Status : " + status + "");
out.println("Address : " + address + "");
}catch (IOException e) {
// Handle IO exception.
}
This part of the code:
new FileWriter(file,true)
tells it to append when it's set to true, as you can see on the docs.
Or you could change your line:
PrintWriter writer = new PrintWriter(file);
To this:
PrintWriter writer = new PrintWriter(new FileWriter(file,true));
instead of this
PrintWriter writer = new PrintWriter(file);
try this
PrintWriter writer= new PrintWriter(new BufferedWriter(new FileWriter(file, true));
See Also
How to append content to file in Java
How to append text to an existing file in Java
Ok, so I really didn't know how to say it right for the title so this should shed some light on the situation.
I'm making a palindrome program in Java. In every which way you look at it, it works just fine. It reads in a file using Scanner, searches through the entire file and outputs if that line in the text file is a palindrome. If you have any special characters or caps it deletes them and turns everything to lowercase.
My issue is that after the check is done on each line, I want to show some extra information next to the result.
Each line should show how many words are in the line, how many characters and if its a palindrome or not.
Anyway here is the code, hopefully someone can help me figure this out. Thanks.
import java.io.File;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
//Global Variables
Scanner cScan = null;
Scanner wScan = null;
Scanner pScan = null;
int charCount = 0, numLines = 0, numChars = 0, wordCount = 0;
//Take in User Input
Scanner iScan = new Scanner(System.in); //Start input Scanner
String fileName = null;
System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();
iScan.close(); //Close input Scanner
//Read File Specified by User
File palin = new File(fileName);
try {
//Checks for Number of Characters
cScan = new Scanner(palin);
while(cScan.hasNextLine()) {
String line = cScan.nextLine();
numChars += line.length();
numLines++;
}
//Checks for Number of Words
wScan = new Scanner(palin);
while (wScan.hasNext()) {
wScan.next();
wordCount++;
}
//Format Lines
pScan = new Scanner(palin);
while (pScan.hasNext()) {
String line = pScan.nextLine();
String reString = line.replaceAll("[^\\p{L}\\p{Nd}]", "");
String lString = reString.toLowerCase();
boolean pali = false;
String tP = "Yes", fP = "No";
int n = lString.length();
for (int i = 0; i < (n / 2) + 1; ++i) {
if (lString.charAt(i) != lString.charAt(n - i - 1)) {
pali = false;
break;
}
else if (lString.charAt(i) == lString.charAt(n - i - 1)) {
pali = true;
break;
}
}
if (pali == true)
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + tP);
else
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + fP);
}
}
catch(Exception e) {
System.out.println("File Could Not be Found");
}
//charCount = (numLines + numChars) - 1; //Minus 1 to Compensate for EOL at EOF
//System.out.println(charCount);
//System.out.println(wordCount);
//System.out.println(spRemover);
}
}
I cleaned up your code a little bit.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Palindrome {
int charCount = 0;
int totalWordCount = 0;
public static String isPalindrome(String str) {
if(str.equals(new StringBuffer().append(str).reverse().toString())) {
return "a";
}
else {
return "not a";
}
}
public static int getNumberOfWords(String str) {
return str.isEmpty() ? 0 : str.split("\\s+").length;
}
public void process(File file) {
try {
Scanner sc = new Scanner(file);
int i = 0;
while(sc.hasNextLine()) {
i++;
String line = sc.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line " + i + "is " + isPalindrome(line) + " palindrome. It has " + wordCount + " words and " + line.length() + " characters.");
charCount = charCount + line.length();
totalWordCount = totalWordCount + wordCount;
}
sc.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner iScan = new Scanner(System.in);
String fileName = null;
System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();
iScan.close();
File file = new File(fileName);
Palindrome pal = new Palindrome();
pal.process(file);
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class IteratingFileWithInformation {
int charCount = 0 ;
int totalWordCount = 0;
private static String checkPalindrome(String line) {
return line.equals(new StringBuffer().append(line).reverse().toString()) ? "a" : "not a" ;
}
private static int getNumberOfWords(String words) {
return words.isEmpty() ? 0 : words.split("\\s+").length;
}
private void checkFileAndProcess(BufferedReader file) {
Scanner input = new Scanner(file);
int i = 0;
while(input.hasNextLine()) {
i++;
String line = input.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line: " + i + " is " + checkPalindrome(line) + " Palindrome. It has " + wordCount + " words and " + line.length() +
" characters. ");
charCount += line.length();
totalWordCount += wordCount;
}
input.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
}
public static void main(String[] args) throws FileNotFoundException {
Scanner givefileName = new Scanner(System.in);
String fileName = null;
System.out.println("Enter the file name :");
fileName = givefileName.nextLine();
givefileName.close();
FileReader file = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(file);
IteratingFileWithInformation fileWithInformation = new IteratingFileWithInformation();
fileWithInformation.checkFileAndProcess(bufferedReader);
}
}
but when I run the program using the command line. I get a run time error of "java.lang.NoClassDefFoundError". All I did was copy the code from Netbeans and paste it on a notepad file and then tried running it by command prompt. I am not sure what I am/ did wrong. Any feedback is greatly appreciated it! Here is my code BTW
package reader;
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class Reader{
public static final Scanner in = new Scanner( System.in);
static final int adult = 0; // The index representation numbers for the total and count arrays;
static final int child = 1;
static final int adultMale = 2;
static final int adultFemale = 3;
static final int childMale = 4;
static final int childFemale = 5;
static final int people = 6;
static final int family = 7;
public static void main(String[] arg){
if(arg.length > 2){ die("Too many arguments");}
else {System.out.println("Good");}
String inFileName;
if(arg.length > 0){ inFileName = arg[0];}
else {
inFileName = "population.txt";}
Scanner fin = openFile(inFileName);
int[] count = new int[8]; // adults,children,male adult, female adult, male child , female child, people, family
int[] total = new int[8]; //adults,children,male adult, female adult, male child , female child, people, family
for( ; fin.hasNextLine(); ){
String line = fin.nextLine();
String error = check(line);
if(error != null){die(error);}
else{ gather(line, count, total);}
}//loop
for(int i = 0; i< count.length; i++){ System.out.print(count[i] + " ");}
System.out.println();
for(int i = 0; i< total.length; i++){ System.out.print(total[i] + " ");}
System.out.println();
System.out.println((float)count[family]/count[people]);
fin.close();
String outFileName;
if( arg.length > 1){ outFileName = arg[1];}
else{outFileName = "output.txt";}
PrintStream fout = outFile(outFileName);
showCensus(fout,count,total);
}//main
public static void die(String message){
System.err.println("Error: " + message);
System.exit(1);
}//die
public static Scanner openFile(String fileName){
Scanner inputFile = null;
try{
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e){ die("File not found: " + fileName);
}
return inputFile;
}// OpenFIle
public static PrintStream outFile(String fileName){
Scanner temp = null;
try{
temp = new Scanner(new File(fileName));
} catch(FileNotFoundException ei){
PrintStream result = null;
try{
result = new PrintStream( new File(fileName));
}catch(FileNotFoundException eo){die("Can't open " + fileName);}
return result;
}
die("The file " + fileName + " already exists!");
return null;
}
public static String check(String line){
int change = 0;
String sex;
int age;
Scanner sin = new Scanner(line);
if(!sin.hasNext()){return null;}
if(sin.next().equalsIgnoreCase("Comment")){return null;}
Scanner sin2 = new Scanner(line);
while(sin2.hasNext()){
change++;
if(change % 2 == 0){}
else{
sex = sin2.next();
if(!sex.equals("M")&& !sex.equals("F")){return "Gender must be 'M' or 'F', not " + sex;}
if(!sin2.hasNext()){return "No data after " + sex ;}
if(!sin2.hasNextInt()){return "age must be a number not " + sin2.next();}
age = sin2.nextInt();
//System.out.print(sex + " " + age + " ");
}
}
System.out.println();
return null;
}
public static void gather(String line, int[] count, int[] total){
int change = 0;
Scanner sin = new Scanner(line);
if(!sin.hasNext()){return ;}
if(sin.next().equalsIgnoreCase("Comment")){return;}
Scanner sin2 = new Scanner(line);
while(sin2.hasNext()){
change++;
if(change % 2 == 0){}
else{
String sex = sin2.next();
int age = sin2.nextInt();
if(sex.equals("M") && age > 17){
count[adultMale]++;
count[adult]++;
count[people]++;
total[adultMale]+= age;
total[adult]+= age;
total[people]+= age;}
else if(sex.equals("M") && age <= 17){
count[child]++;
count[people]++;
count[childMale]++;
total[child]+= age;
total[people]+= age;
total[childMale]+= age;}
else if(sex.equals("F") && age > 17 ){
count[adult]++;
count[adultFemale]++;
count[people]++;
total[adult]+= age;
total[adultFemale]+= age;
total[people]+= age;}
else if(sex.equals("F") && age <= 17){
count[childFemale]++;
count[child]++;
count[people]++;
total[childFemale]+= age;
total[child]+= age;
total[people]+= age;}
}
}// while
count[family]++;
}
public static void showCensus(PrintStream out, int[] count, int[] total){
out.println("The Family Statistics 2013 Report");
out.println();
out.println("People: " + count[people] + " Average Age: " + (float)total[people]/count[people]);
out.println(" Adults: " + count[adult] + " Average Age: " + (float)total[adult]/count[adult]);
out.println(" Males: " + count[adultMale] + " Average Age: " + (float)total[adultMale]/count[adultMale]);
out.println(" Females: " + count[adultFemale] + " Average Age: " + (float)total[adultFemale]/count[adultFemale]);
out.println(" Children: " + count[child] + " Average Age: " + (float)total[child]/count[child]);
out.println(" Males: " + count[childMale] + " Average Age: " + (float)total[childMale]/count[childMale]);
out.println(" Female: " + count[childFemale] + " Average Age: " + (float)total[childFemale]/count[childFemale]);
out.println("Families: " + count[family] + " Average Family Size " + (float)count[family]/count[people]);
}
}//Reader
Your class Reader is defined in the reader package. You need to give the JVM the proper class path. Create a folder called reader and place your class there. Then use the -classpath flag when call java.
c:\>javac reader\Reader.java
c:\>java -classpath . reader.Reader