In the getArray method, the resulting array is always empty - java

public static void main(String[] args) throws FileNotFoundxception {
File usdCoins = new File("C:\\Users\\saif9\\OneDrive\\Desktop\\USD coins.txt");
getArray(usdCoins);
}
public static void getArray (File coins) {
try {
Scanner reader = new Scanner(coins);
int counter = 0;
while (reader.hasNextDouble()) {
System.out.print(reader.nextDouble() + " / ");
System.out.println(counter);
counter++;
}
double jodCoins[] = new double[counter];
int i = 0;
while (reader.hasNextDouble()) {
jodCoins [i] = reader.nextDouble();
i++;
for (int j= 0; j < i; j++) {
System.out.println(jodCoins[j]);
}
}
}
catch (Exception e) {
// ????
}

You should re-initialise the reader ,after the first while , the reader dont have more double to read , so you need to assign it again to a new Scanner (entries are not clear here if you need to reuse the same data of coins file ) :
public static void main(String[] args) throws FileNotFoundxception {
File usdCoins = new File("C:\\Users\\saif9\\OneDrive\\Desktop\\USD coins.txt");
getArray(usdCoins);
}
public static void getArray (File coins) {
try {
Scanner reader = new Scanner(coins);
int counter = 0;
while (reader.hasNextDouble()) {
System.out.print(reader.nextDouble() + " / ");
System.out.println(counter);
counter++;
}
double jodCoins[] = new double[counter];
int i = 0;
// re-initialise the reader here :
reader = new Scanner(coins);
while (reader.hasNextDouble()) {
jodCoins [i] = reader.nextDouble();
i++;
for (int j= 0; j < i; j++) {
System.out.println(jodCoins[j]);
}
}
}
catch (Exception e) {
// ????
}

Related

How do I turn this function from java to recieve an url to show the results

So I'm recieving this url http://cei.edu.uy/plata.txt which contains numbers, what my function does is try to give the least amount of money required to get to that number, but I don't know how to actually use the numbers in that url on my function and save the result in the file "result.txt", because as of now I'm giving the numbers mannualy with the var "V" I give the amount of money to the function. This is my code:
public static void main(String[] args) throws IOException {
try {
URL url = new URL("http://cei.edu.uy/plata.txt");
try (Scanner s = new Scanner(url.openStream())) {
File f = new File("result.txt");
try (PrintStream print = new PrintStream(f)) {
int bills[] = {2000, 1000, 500, 200, 100,50, 20, 10, 5, 2, 1};
int m = bills.length;
int V = 153;
System.out.println ( minBills(bills, m, V));
while (s.hasNext()) {
}
print.flush();
}
}
} catch (MalformedURLException ex) {
}
}
static int minBills(int bills[], int m, int V)
{
int table[] = new int[V + 1];
table[0] = 0;
for (int i = 1; i <= V; i++)
table[i] = Integer.MAX_VALUE;
for (int i = 1; i <= V; i++)
{
for (int j = 0; j < m; j++)
if (bills[j] <= i)
{
int sub = table[i - bills[j]];
if (sub != Integer.MAX_VALUE
&& sub + 1 < table[i])
table[i] = sub + 1;
}
}
if(table[V]==Integer.MAX_VALUE)
return -1;
return table[V];
}
}
you can get the numbers form the URL using InputStreamReader as below
private static List<Integer> getNumbersFromUrl(String string) {
List<Integer> nums = new ArrayList<>();
try {
URL link = new URL(string);
BufferedReader in = new BufferedReader(
new InputStreamReader(link.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
nums.add(Integer.parseInt(inputLine));
}
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return nums;
}
Passing URL string to above method
List<Integer> nums = getNumbersFromUrl("http://cei.edu.uy/plata.txt");
System.out.println("numbers:"+nums);
Output:
number:[8, 153, 10, 312]
EDIT
you can get the numbers from URL by calling getNumbersFromUrl method
and to assign 153 reading from URL, replace below line
int V = 153;
with
List<Integer> nums = getNumbersFromUrl("http://cei.edu.uy/plata.txt");
int v = nums.get(1);
Note: variable name should start with lowercase(camelCase)

why System.err.println not output in order?

I have a simple java class that uses System.err.println to debug the code as it executes. the purpuse of the class is to find the maximum pairwise product of a given numbers.
following is the code and output.
public class MaxPairwiseProduct {
private static boolean enableLog = true;
static long getMaxPairwiseProductFast(int[] numbers) {
long max_product = 0;
int n = numbers.length;
int firstMaxInt = -1;
int secondMaxInt = -1;
int firstMaxIndex = 0;
int secondMaxIndex = 0;
loge("firstMax initialized :" + firstMaxInt);
loge("secondMax initialized :"+ secondMaxInt);
loge("***********************************************");
for (int firstPassIndex = 1; firstPassIndex < n; firstPassIndex++) {
loge("firstpass : Number " +firstPassIndex);
if (numbers[firstPassIndex] > firstMaxInt )
{
loge("\t firstpass : Found max " +numbers[firstPassIndex]);
firstMaxInt = numbers[firstPassIndex] ;
firstMaxIndex = firstPassIndex ;
}
}
for (int secondPassIndex = 1; secondPassIndex < n; secondPassIndex++) {
loge("secondPassIndex : Number " +numbers[secondPassIndex]);
if (numbers[secondPassIndex] > secondMaxInt && secondPassIndex != firstMaxIndex )
{
loge("\t firstpass : Found max " +secondPassIndex);
secondMaxInt = numbers[secondPassIndex] ;
secondMaxIndex = secondPassIndex;
}
}
max_product = firstMaxInt * secondMaxInt ;
return max_product;
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println(getMaxPairwiseProductFast(numbers));
}
private static void loge(String s)
{
if (enableLog == true)
{
System.err.println(s);
}
}
private static void log(String s)
{
if (enableLog == true)
{
System.out.println(s);
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new
InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
the output is (from the output window in Netbeans):
It is clear that the output messages is not in the intended order.
It appears to me as if the program execute in multi-thread.
what is the error in my code and why it output like this ?
I found the answer here
Delay in running thread due to system.out.println statement
a stackOverflow member guided me to this.
basically , changing the loge method to the following fixed the issue.
private static void loge(String s)
{
if (enableLog == true)
{
System.err.println(s);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MaxPairwiseProduct.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Read from a text file, sort it, and write it again

So our professor has assigned us with a program which reads a text file he has provided us with; it sorts it, and creates a new file with the sorted stuff. He wants us to call three methods from the main i.e. read, sort, and write
I have done some of the work, but i'm confused what arguments to provide for io.sort. And how do i convert that text thing into an array to provide an argument Here's my code:
public void read() {
try {
Scanner myLocal = new Scanner(new File("dictionary.txt"));
while (myLocal.hasNextLine()) {
System.out.println(myLocal.nextLine());
}
} catch (IOException e) {
System.out.println(e);
}
}
public void sort(String[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
/* ERROR: When j == 0, j - 1 == -1, which is out of bounds */
if (arr[j - 1].compareTo(arr[j]) > 0) {
swap(j, arr);
}
}
}
}
public void swap(int j, String[] arr) {
String temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
public void write() {
try {
PrintStream writer = new PrintStream(new File("sorted.txt"));
for (int i = 0; i < 100; i++) {
writer.println(i);
}
writer.close();
} catch (IOException e) {
System.out.println(e);
}
}
Here is how i've changed my read() method:
public void read()
{
String[] myArray = new String[1000];
try {
Scanner myLocal = new Scanner( new File("dictionary.txt"));
String a = myLocal.nextLine();
while (myLocal.hasNextLine()){
for (int i=0; i<myArray.length; i++){
myArray[i] = a;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
class IO{
String[] myArray = new String[30000];
public void read()
{
try {
Scanner myLocal = new Scanner( new File("dictionary.txt"));
while (myLocal.hasNextLine()){
for (int i=0; i<myArray.length; i++){
String a = myLocal.nextLine();
myArray[i] = a;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
public void sort()
{
int n = myArray.length;
for (int i=0; i<n-1; i++){
for(int j=0; j<n-i-1; j++){
if(myArray[j+1].compareTo(myArray[j])<0){
String temp = myArray[j];
myArray[j] = myArray[j+1];
myArray[j+1] = temp;
//toLower
}
}
}
}
public void swap(int j, String[] arr)
{
String temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
public void write()
{
try{
PrintStream writer = new PrintStream(new File("sorted.txt"));
for (int i=0; i<myArray.length; i++){
writer.println(myArray[i] + "\n");
}
writer.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
CORRECT CODE (SOLVED)
class IO{
String[] myArray = new String[30000];
public void read()
{
try {
Scanner myLocal = new Scanner( new File("dictionary.txt"));
while (myLocal.hasNextLine()){
for (int i=0; i<myArray.length; i++){
String a = myLocal.nextLine();
myArray[i] = a;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
public void sort()
{
int n = myArray.length;
for (int i=0; i<n; i++){
for(int j=1; j<n-i; j++){
if (myArray[j-1].compareTo(myArray[j])>0){
swap(j, myArray);
}
}
}
}
public void swap(int j, String[] myArray)
{
String temp = myArray[j-1];
myArray[j-1]=myArray[j];
myArray[j]=temp;
}
public void write()
{
try{
PrintStream writer = new PrintStream(new File("myIgnoreNew.txt"));
for (int i=0; i<myArray.length; i++){
writer.println(myArray[i] + "\n");
}
writer.close();
}
catch(IOException e){
System.out.println(e);
}
}
}

Manipulating strings and integers via two dimensional array from an external file java

I am trying to design a program that takes data from an external file, stores the variable to arrays and then allows for manipulation.sample input:
String1 intA1 intA2
String2 intB1 intB2
String3 intC1 intC2
String4 intD1 intD2
String5 intE1 intE2
I want to be able to take these values from the array and manipulate them as follows;
For each string I want to be able to take StringX and computing((intX1+
intX2)/)
And for each int column I want to be able to do for example (intA1 + intB1 + intC1 + intD1 + intE1)
This is what I have so far, any tips?
**please note java naming conventions have not been taught in my course yet.
public class 2D_Array {
public static void inputstream(){
File file = new File("data.txt");
try (FileInputStream fis = new FileInputStream(file)) {
int content;
while ((content = fis.read()) != -1) {
readLines("data.txt");
FivebyThree();
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static int FivebyThree() throws IOException {
Scanner sc = new Scanner(new File("data.txt"));
int[] arr = new int[10];
while(sc.hasNextLine()) {
String line[] = sc.nextLine().split("\\s");
int ele = Integer.parseInt(line[1]);
int index = Integer.parseInt(line[0]);
arr[index] = ele;
}
int sum = 0;
for(int i = 0; i<arr.length; i++) {
sum += arr[i];
System.out.print(arr[i] + "\t");
}
System.out.println("\nSum : " + sum);
return sum;
}
public static String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
lines.add(line);
}
return lines.toArray(new String[lines.size()]);
}
/* int[][] FivebyThree = new int[5][3];
int row, col;
for (row =0; row < 5; row++) {
for(col = 0; col < 3; col++) {
System.out.printf( "%7d", FivebyThree[row][col]);
}
System.out.println();*/
public static void main(String[] args)throws IOException {
inputstream();
}
}
I see that you read data.txt twice and do not use first read result at all. I do not understand, what you want to do with String, but having two-dimension array and calculate sum of columns of int is very easy:
public class Array_2D {
static final class Item {
final String str;
final int val1;
final int val2;
Item(String str, int val1, int val2) {
this.str = str;
this.val1 = val1;
this.val2 = val2;
}
}
private static List<Item> readFile(Reader reader) throws IOException {
try (BufferedReader in = new BufferedReader(reader)) {
List<Item> content = new ArrayList<>();
String str;
while ((str = in.readLine()) != null) {
String[] parts = str.split(" ");
content.add(new Item(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[2])));
}
return content;
}
}
private static void FivebyThree(List<Item> content) {
StringBuilder buf = new StringBuilder();
int sum1 = 0;
int sum2 = 0;
for (Item item : content) {
// TODO do what you want with item.str
sum1 += item.val1;
sum2 += item.val2;
}
System.out.println("str: " + buf);
System.out.println("sum1: " + sum1);
System.out.println("sum2: " + sum2);
}
public static void main(String[] args) throws IOException {
List<Item> content = readFile(new InputStreamReader(Array_2D.class.getResourceAsStream("data.txt")));
FivebyThree(content);
}
}

Why does this program terminate when I enter user input?

The program is supposed to compare a user-inputted string to a text document. If the program finds a match in the file and in part of the string, it should highlight or change the font color of the matching string in what the user inputted. The thing is, once I enter something for user input, the program terminates. Examples of inputs that could have a match in the file are MALEKRQ, MALE, MMALEKR, MMMM, and MALEK. How do I fix this problem? I'm using Eclipse Neon on Mac OS X El Capitan.
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner fileInput = new Scanner(file);
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
int len = userProteinSequence.length();
int size = 4;
int start = 0;
int indexEnd = size;
while (indexEnd < len - size)
{
for (int index = start; index <= len - size; index++)
{
String search = userProteinSequence.substring(index, indexEnd);
System.out.println(search);
while (fileInput.hasNext())
{
String MALEKRQ = fileInput.nextLine();
// System.out.println(MALEKRQ);
int found = MALEKRQ.indexOf(search);
if (found >= 0)
{
System.out.println("Yay.");
}
else
{
System.out.println("Fail.");
}
}
indexEnd++;
}
size++;
if (size > 8) {
size = 8;
start++;
}
}
}
catch (FileNotFoundException e)
{
System.err.format("File does not exist.\n");
}
}
}
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
for (int size = userProteinSequence.length(); size >= 4; size--) {
for (int start = 0; start <= userProteinSequence.length()-size; start++) {
boolean found = false;
String search = userProteinSequence.substring(start, size);
System.out.println(search);
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
int found = MALEKRQ.indexOf(search);
if (found >= 0) {
found = true;
}
}
if (found) {
System.out.println(search+" found (index "+start+")");
fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
MALEKRQ = MALEKRQ.replaceAll(search, "[["+search+"]]");
System.out.println(MALEKRQ);
}
return;
}
}
}
System.out.println(search+" not found");
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
System.out.println(MALEKRQ);
}
} catch (FileNotFoundException e) {
System.err.format("File does not exist.\n");
}
}
}

Categories

Resources